node-entry.js 628 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504
  1. /*
  2. @license
  3. Rollup.js v1.32.1
  4. Fri, 06 Mar 2020 09:32:39 GMT - commit f458cbf6cb8cfcc1678593d8dc595e4b8757eb6d
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. 'use strict';
  9. var util = require('util');
  10. var path = require('path');
  11. var fs = require('fs');
  12. var acorn = require('acorn');
  13. var crypto = require('crypto');
  14. var events = require('events');
  15. var module$1 = require('module');
  16. /*! *****************************************************************************
  17. Copyright (c) Microsoft Corporation. All rights reserved.
  18. Licensed under the Apache License, Version 2.0 (the "License"); you may not use
  19. this file except in compliance with the License. You may obtain a copy of the
  20. License at http://www.apache.org/licenses/LICENSE-2.0
  21. THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22. KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
  23. WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
  24. MERCHANTABLITY OR NON-INFRINGEMENT.
  25. See the Apache Version 2.0 License for specific language governing permissions
  26. and limitations under the License.
  27. ***************************************************************************** */
  28. function __awaiter(thisArg, _arguments, P, generator) {
  29. return new (P || (P = Promise))(function (resolve, reject) {
  30. function fulfilled(value) { try {
  31. step(generator.next(value));
  32. }
  33. catch (e) {
  34. reject(e);
  35. } }
  36. function rejected(value) { try {
  37. step(generator["throw"](value));
  38. }
  39. catch (e) {
  40. reject(e);
  41. } }
  42. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  43. step((generator = generator.apply(thisArg, _arguments || [])).next());
  44. });
  45. }
  46. var version = "1.32.1";
  47. var charToInteger = {};
  48. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  49. for (var i = 0; i < chars.length; i++) {
  50. charToInteger[chars.charCodeAt(i)] = i;
  51. }
  52. function decode(mappings) {
  53. var decoded = [];
  54. var line = [];
  55. var segment = [
  56. 0,
  57. 0,
  58. 0,
  59. 0,
  60. 0,
  61. ];
  62. var j = 0;
  63. for (var i = 0, shift = 0, value = 0; i < mappings.length; i++) {
  64. var c = mappings.charCodeAt(i);
  65. if (c === 44) { // ","
  66. segmentify(line, segment, j);
  67. j = 0;
  68. }
  69. else if (c === 59) { // ";"
  70. segmentify(line, segment, j);
  71. j = 0;
  72. decoded.push(line);
  73. line = [];
  74. segment[0] = 0;
  75. }
  76. else {
  77. var integer = charToInteger[c];
  78. if (integer === undefined) {
  79. throw new Error('Invalid character (' + String.fromCharCode(c) + ')');
  80. }
  81. var hasContinuationBit = integer & 32;
  82. integer &= 31;
  83. value += integer << shift;
  84. if (hasContinuationBit) {
  85. shift += 5;
  86. }
  87. else {
  88. var shouldNegate = value & 1;
  89. value >>>= 1;
  90. if (shouldNegate) {
  91. value = value === 0 ? -0x80000000 : -value;
  92. }
  93. segment[j] += value;
  94. j++;
  95. value = shift = 0; // reset
  96. }
  97. }
  98. }
  99. segmentify(line, segment, j);
  100. decoded.push(line);
  101. return decoded;
  102. }
  103. function segmentify(line, segment, j) {
  104. // This looks ugly, but we're creating specialized arrays with a specific
  105. // length. This is much faster than creating a new array (which v8 expands to
  106. // a capacity of 17 after pushing the first item), or slicing out a subarray
  107. // (which is slow). Length 4 is assumed to be the most frequent, followed by
  108. // length 5 (since not everything will have an associated name), followed by
  109. // length 1 (it's probably rare for a source substring to not have an
  110. // associated segment data).
  111. if (j === 4)
  112. line.push([segment[0], segment[1], segment[2], segment[3]]);
  113. else if (j === 5)
  114. line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]);
  115. else if (j === 1)
  116. line.push([segment[0]]);
  117. }
  118. function encode(decoded) {
  119. var sourceFileIndex = 0; // second field
  120. var sourceCodeLine = 0; // third field
  121. var sourceCodeColumn = 0; // fourth field
  122. var nameIndex = 0; // fifth field
  123. var mappings = '';
  124. for (var i = 0; i < decoded.length; i++) {
  125. var line = decoded[i];
  126. if (i > 0)
  127. mappings += ';';
  128. if (line.length === 0)
  129. continue;
  130. var generatedCodeColumn = 0; // first field
  131. var lineMappings = [];
  132. for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
  133. var segment = line_1[_i];
  134. var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
  135. generatedCodeColumn = segment[0];
  136. if (segment.length > 1) {
  137. segmentMappings +=
  138. encodeInteger(segment[1] - sourceFileIndex) +
  139. encodeInteger(segment[2] - sourceCodeLine) +
  140. encodeInteger(segment[3] - sourceCodeColumn);
  141. sourceFileIndex = segment[1];
  142. sourceCodeLine = segment[2];
  143. sourceCodeColumn = segment[3];
  144. }
  145. if (segment.length === 5) {
  146. segmentMappings += encodeInteger(segment[4] - nameIndex);
  147. nameIndex = segment[4];
  148. }
  149. lineMappings.push(segmentMappings);
  150. }
  151. mappings += lineMappings.join(',');
  152. }
  153. return mappings;
  154. }
  155. function encodeInteger(num) {
  156. var result = '';
  157. num = num < 0 ? (-num << 1) | 1 : num << 1;
  158. do {
  159. var clamped = num & 31;
  160. num >>>= 5;
  161. if (num > 0) {
  162. clamped |= 32;
  163. }
  164. result += chars[clamped];
  165. } while (num > 0);
  166. return result;
  167. }
  168. var BitSet = function BitSet(arg) {
  169. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  170. };
  171. BitSet.prototype.add = function add(n) {
  172. this.bits[n >> 5] |= 1 << (n & 31);
  173. };
  174. BitSet.prototype.has = function has(n) {
  175. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  176. };
  177. var Chunk = function Chunk(start, end, content) {
  178. this.start = start;
  179. this.end = end;
  180. this.original = content;
  181. this.intro = '';
  182. this.outro = '';
  183. this.content = content;
  184. this.storeName = false;
  185. this.edited = false;
  186. // we make these non-enumerable, for sanity while debugging
  187. Object.defineProperties(this, {
  188. previous: { writable: true, value: null },
  189. next: { writable: true, value: null }
  190. });
  191. };
  192. Chunk.prototype.appendLeft = function appendLeft(content) {
  193. this.outro += content;
  194. };
  195. Chunk.prototype.appendRight = function appendRight(content) {
  196. this.intro = this.intro + content;
  197. };
  198. Chunk.prototype.clone = function clone() {
  199. var chunk = new Chunk(this.start, this.end, this.original);
  200. chunk.intro = this.intro;
  201. chunk.outro = this.outro;
  202. chunk.content = this.content;
  203. chunk.storeName = this.storeName;
  204. chunk.edited = this.edited;
  205. return chunk;
  206. };
  207. Chunk.prototype.contains = function contains(index) {
  208. return this.start < index && index < this.end;
  209. };
  210. Chunk.prototype.eachNext = function eachNext(fn) {
  211. var chunk = this;
  212. while (chunk) {
  213. fn(chunk);
  214. chunk = chunk.next;
  215. }
  216. };
  217. Chunk.prototype.eachPrevious = function eachPrevious(fn) {
  218. var chunk = this;
  219. while (chunk) {
  220. fn(chunk);
  221. chunk = chunk.previous;
  222. }
  223. };
  224. Chunk.prototype.edit = function edit(content, storeName, contentOnly) {
  225. this.content = content;
  226. if (!contentOnly) {
  227. this.intro = '';
  228. this.outro = '';
  229. }
  230. this.storeName = storeName;
  231. this.edited = true;
  232. return this;
  233. };
  234. Chunk.prototype.prependLeft = function prependLeft(content) {
  235. this.outro = content + this.outro;
  236. };
  237. Chunk.prototype.prependRight = function prependRight(content) {
  238. this.intro = content + this.intro;
  239. };
  240. Chunk.prototype.split = function split(index) {
  241. var sliceIndex = index - this.start;
  242. var originalBefore = this.original.slice(0, sliceIndex);
  243. var originalAfter = this.original.slice(sliceIndex);
  244. this.original = originalBefore;
  245. var newChunk = new Chunk(index, this.end, originalAfter);
  246. newChunk.outro = this.outro;
  247. this.outro = '';
  248. this.end = index;
  249. if (this.edited) {
  250. // TODO is this block necessary?...
  251. newChunk.edit('', false);
  252. this.content = '';
  253. }
  254. else {
  255. this.content = originalBefore;
  256. }
  257. newChunk.next = this.next;
  258. if (newChunk.next) {
  259. newChunk.next.previous = newChunk;
  260. }
  261. newChunk.previous = this;
  262. this.next = newChunk;
  263. return newChunk;
  264. };
  265. Chunk.prototype.toString = function toString() {
  266. return this.intro + this.content + this.outro;
  267. };
  268. Chunk.prototype.trimEnd = function trimEnd(rx) {
  269. this.outro = this.outro.replace(rx, '');
  270. if (this.outro.length) {
  271. return true;
  272. }
  273. var trimmed = this.content.replace(rx, '');
  274. if (trimmed.length) {
  275. if (trimmed !== this.content) {
  276. this.split(this.start + trimmed.length).edit('', undefined, true);
  277. }
  278. return true;
  279. }
  280. else {
  281. this.edit('', undefined, true);
  282. this.intro = this.intro.replace(rx, '');
  283. if (this.intro.length) {
  284. return true;
  285. }
  286. }
  287. };
  288. Chunk.prototype.trimStart = function trimStart(rx) {
  289. this.intro = this.intro.replace(rx, '');
  290. if (this.intro.length) {
  291. return true;
  292. }
  293. var trimmed = this.content.replace(rx, '');
  294. if (trimmed.length) {
  295. if (trimmed !== this.content) {
  296. this.split(this.end - trimmed.length);
  297. this.edit('', undefined, true);
  298. }
  299. return true;
  300. }
  301. else {
  302. this.edit('', undefined, true);
  303. this.outro = this.outro.replace(rx, '');
  304. if (this.outro.length) {
  305. return true;
  306. }
  307. }
  308. };
  309. var btoa = function () {
  310. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  311. };
  312. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  313. btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
  314. }
  315. else if (typeof Buffer === 'function') {
  316. btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
  317. }
  318. var SourceMap = function SourceMap(properties) {
  319. this.version = 3;
  320. this.file = properties.file;
  321. this.sources = properties.sources;
  322. this.sourcesContent = properties.sourcesContent;
  323. this.names = properties.names;
  324. this.mappings = encode(properties.mappings);
  325. };
  326. SourceMap.prototype.toString = function toString() {
  327. return JSON.stringify(this);
  328. };
  329. SourceMap.prototype.toUrl = function toUrl() {
  330. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  331. };
  332. function guessIndent(code) {
  333. var lines = code.split('\n');
  334. var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
  335. var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
  336. if (tabbed.length === 0 && spaced.length === 0) {
  337. return null;
  338. }
  339. // More lines tabbed than spaced? Assume tabs, and
  340. // default to tabs in the case of a tie (or nothing
  341. // to go on)
  342. if (tabbed.length >= spaced.length) {
  343. return '\t';
  344. }
  345. // Otherwise, we need to guess the multiple
  346. var min = spaced.reduce(function (previous, current) {
  347. var numSpaces = /^ +/.exec(current)[0].length;
  348. return Math.min(numSpaces, previous);
  349. }, Infinity);
  350. return new Array(min + 1).join(' ');
  351. }
  352. function getRelativePath(from, to) {
  353. var fromParts = from.split(/[/\\]/);
  354. var toParts = to.split(/[/\\]/);
  355. fromParts.pop(); // get dirname
  356. while (fromParts[0] === toParts[0]) {
  357. fromParts.shift();
  358. toParts.shift();
  359. }
  360. if (fromParts.length) {
  361. var i = fromParts.length;
  362. while (i--) {
  363. fromParts[i] = '..';
  364. }
  365. }
  366. return fromParts.concat(toParts).join('/');
  367. }
  368. var toString = Object.prototype.toString;
  369. function isObject(thing) {
  370. return toString.call(thing) === '[object Object]';
  371. }
  372. function getLocator(source) {
  373. var originalLines = source.split('\n');
  374. var lineOffsets = [];
  375. for (var i = 0, pos = 0; i < originalLines.length; i++) {
  376. lineOffsets.push(pos);
  377. pos += originalLines[i].length + 1;
  378. }
  379. return function locate(index) {
  380. var i = 0;
  381. var j = lineOffsets.length;
  382. while (i < j) {
  383. var m = (i + j) >> 1;
  384. if (index < lineOffsets[m]) {
  385. j = m;
  386. }
  387. else {
  388. i = m + 1;
  389. }
  390. }
  391. var line = i - 1;
  392. var column = index - lineOffsets[line];
  393. return { line: line, column: column };
  394. };
  395. }
  396. var Mappings = function Mappings(hires) {
  397. this.hires = hires;
  398. this.generatedCodeLine = 0;
  399. this.generatedCodeColumn = 0;
  400. this.raw = [];
  401. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  402. this.pending = null;
  403. };
  404. Mappings.prototype.addEdit = function addEdit(sourceIndex, content, loc, nameIndex) {
  405. if (content.length) {
  406. var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  407. if (nameIndex >= 0) {
  408. segment.push(nameIndex);
  409. }
  410. this.rawSegments.push(segment);
  411. }
  412. else if (this.pending) {
  413. this.rawSegments.push(this.pending);
  414. }
  415. this.advance(content);
  416. this.pending = null;
  417. };
  418. Mappings.prototype.addUneditedChunk = function addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  419. var originalCharIndex = chunk.start;
  420. var first = true;
  421. while (originalCharIndex < chunk.end) {
  422. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  423. this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
  424. }
  425. if (original[originalCharIndex] === '\n') {
  426. loc.line += 1;
  427. loc.column = 0;
  428. this.generatedCodeLine += 1;
  429. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  430. this.generatedCodeColumn = 0;
  431. first = true;
  432. }
  433. else {
  434. loc.column += 1;
  435. this.generatedCodeColumn += 1;
  436. first = false;
  437. }
  438. originalCharIndex += 1;
  439. }
  440. this.pending = sourceIndex > 0
  441. ? [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]
  442. : null;
  443. };
  444. Mappings.prototype.advance = function advance(str) {
  445. if (!str) {
  446. return;
  447. }
  448. var lines = str.split('\n');
  449. if (lines.length > 1) {
  450. for (var i = 0; i < lines.length - 1; i++) {
  451. this.generatedCodeLine++;
  452. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  453. }
  454. this.generatedCodeColumn = 0;
  455. }
  456. this.generatedCodeColumn += lines[lines.length - 1].length;
  457. };
  458. var n = '\n';
  459. var warned = {
  460. insertLeft: false,
  461. insertRight: false,
  462. storeName: false
  463. };
  464. var MagicString = function MagicString(string, options) {
  465. if (options === void 0)
  466. options = {};
  467. var chunk = new Chunk(0, string.length, string);
  468. Object.defineProperties(this, {
  469. original: { writable: true, value: string },
  470. outro: { writable: true, value: '' },
  471. intro: { writable: true, value: '' },
  472. firstChunk: { writable: true, value: chunk },
  473. lastChunk: { writable: true, value: chunk },
  474. lastSearchedChunk: { writable: true, value: chunk },
  475. byStart: { writable: true, value: {} },
  476. byEnd: { writable: true, value: {} },
  477. filename: { writable: true, value: options.filename },
  478. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  479. sourcemapLocations: { writable: true, value: new BitSet() },
  480. storedNames: { writable: true, value: {} },
  481. indentStr: { writable: true, value: guessIndent(string) }
  482. });
  483. this.byStart[0] = chunk;
  484. this.byEnd[string.length] = chunk;
  485. };
  486. MagicString.prototype.addSourcemapLocation = function addSourcemapLocation(char) {
  487. this.sourcemapLocations.add(char);
  488. };
  489. MagicString.prototype.append = function append(content) {
  490. if (typeof content !== 'string') {
  491. throw new TypeError('outro content must be a string');
  492. }
  493. this.outro += content;
  494. return this;
  495. };
  496. MagicString.prototype.appendLeft = function appendLeft(index, content) {
  497. if (typeof content !== 'string') {
  498. throw new TypeError('inserted content must be a string');
  499. }
  500. this._split(index);
  501. var chunk = this.byEnd[index];
  502. if (chunk) {
  503. chunk.appendLeft(content);
  504. }
  505. else {
  506. this.intro += content;
  507. }
  508. return this;
  509. };
  510. MagicString.prototype.appendRight = function appendRight(index, content) {
  511. if (typeof content !== 'string') {
  512. throw new TypeError('inserted content must be a string');
  513. }
  514. this._split(index);
  515. var chunk = this.byStart[index];
  516. if (chunk) {
  517. chunk.appendRight(content);
  518. }
  519. else {
  520. this.outro += content;
  521. }
  522. return this;
  523. };
  524. MagicString.prototype.clone = function clone() {
  525. var cloned = new MagicString(this.original, { filename: this.filename });
  526. var originalChunk = this.firstChunk;
  527. var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  528. while (originalChunk) {
  529. cloned.byStart[clonedChunk.start] = clonedChunk;
  530. cloned.byEnd[clonedChunk.end] = clonedChunk;
  531. var nextOriginalChunk = originalChunk.next;
  532. var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  533. if (nextClonedChunk) {
  534. clonedChunk.next = nextClonedChunk;
  535. nextClonedChunk.previous = clonedChunk;
  536. clonedChunk = nextClonedChunk;
  537. }
  538. originalChunk = nextOriginalChunk;
  539. }
  540. cloned.lastChunk = clonedChunk;
  541. if (this.indentExclusionRanges) {
  542. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  543. }
  544. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  545. cloned.intro = this.intro;
  546. cloned.outro = this.outro;
  547. return cloned;
  548. };
  549. MagicString.prototype.generateDecodedMap = function generateDecodedMap(options) {
  550. var this$1 = this;
  551. options = options || {};
  552. var sourceIndex = 0;
  553. var names = Object.keys(this.storedNames);
  554. var mappings = new Mappings(options.hires);
  555. var locate = getLocator(this.original);
  556. if (this.intro) {
  557. mappings.advance(this.intro);
  558. }
  559. this.firstChunk.eachNext(function (chunk) {
  560. var loc = locate(chunk.start);
  561. if (chunk.intro.length) {
  562. mappings.advance(chunk.intro);
  563. }
  564. if (chunk.edited) {
  565. mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1);
  566. }
  567. else {
  568. mappings.addUneditedChunk(sourceIndex, chunk, this$1.original, loc, this$1.sourcemapLocations);
  569. }
  570. if (chunk.outro.length) {
  571. mappings.advance(chunk.outro);
  572. }
  573. });
  574. return {
  575. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  576. sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
  577. sourcesContent: options.includeContent ? [this.original] : [null],
  578. names: names,
  579. mappings: mappings.raw
  580. };
  581. };
  582. MagicString.prototype.generateMap = function generateMap(options) {
  583. return new SourceMap(this.generateDecodedMap(options));
  584. };
  585. MagicString.prototype.getIndentString = function getIndentString() {
  586. return this.indentStr === null ? '\t' : this.indentStr;
  587. };
  588. MagicString.prototype.indent = function indent(indentStr, options) {
  589. var pattern = /^[^\r\n]/gm;
  590. if (isObject(indentStr)) {
  591. options = indentStr;
  592. indentStr = undefined;
  593. }
  594. indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
  595. if (indentStr === '') {
  596. return this;
  597. } // noop
  598. options = options || {};
  599. // Process exclusion ranges
  600. var isExcluded = {};
  601. if (options.exclude) {
  602. var exclusions = typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  603. exclusions.forEach(function (exclusion) {
  604. for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
  605. isExcluded[i] = true;
  606. }
  607. });
  608. }
  609. var shouldIndentNextCharacter = options.indentStart !== false;
  610. var replacer = function (match) {
  611. if (shouldIndentNextCharacter) {
  612. return ("" + indentStr + match);
  613. }
  614. shouldIndentNextCharacter = true;
  615. return match;
  616. };
  617. this.intro = this.intro.replace(pattern, replacer);
  618. var charIndex = 0;
  619. var chunk = this.firstChunk;
  620. while (chunk) {
  621. var end = chunk.end;
  622. if (chunk.edited) {
  623. if (!isExcluded[charIndex]) {
  624. chunk.content = chunk.content.replace(pattern, replacer);
  625. if (chunk.content.length) {
  626. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  627. }
  628. }
  629. }
  630. else {
  631. charIndex = chunk.start;
  632. while (charIndex < end) {
  633. if (!isExcluded[charIndex]) {
  634. var char = this.original[charIndex];
  635. if (char === '\n') {
  636. shouldIndentNextCharacter = true;
  637. }
  638. else if (char !== '\r' && shouldIndentNextCharacter) {
  639. shouldIndentNextCharacter = false;
  640. if (charIndex === chunk.start) {
  641. chunk.prependRight(indentStr);
  642. }
  643. else {
  644. this._splitChunk(chunk, charIndex);
  645. chunk = chunk.next;
  646. chunk.prependRight(indentStr);
  647. }
  648. }
  649. }
  650. charIndex += 1;
  651. }
  652. }
  653. charIndex = chunk.end;
  654. chunk = chunk.next;
  655. }
  656. this.outro = this.outro.replace(pattern, replacer);
  657. return this;
  658. };
  659. MagicString.prototype.insert = function insert() {
  660. throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
  661. };
  662. MagicString.prototype.insertLeft = function insertLeft(index, content) {
  663. if (!warned.insertLeft) {
  664. console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console
  665. warned.insertLeft = true;
  666. }
  667. return this.appendLeft(index, content);
  668. };
  669. MagicString.prototype.insertRight = function insertRight(index, content) {
  670. if (!warned.insertRight) {
  671. console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console
  672. warned.insertRight = true;
  673. }
  674. return this.prependRight(index, content);
  675. };
  676. MagicString.prototype.move = function move(start, end, index) {
  677. if (index >= start && index <= end) {
  678. throw new Error('Cannot move a selection inside itself');
  679. }
  680. this._split(start);
  681. this._split(end);
  682. this._split(index);
  683. var first = this.byStart[start];
  684. var last = this.byEnd[end];
  685. var oldLeft = first.previous;
  686. var oldRight = last.next;
  687. var newRight = this.byStart[index];
  688. if (!newRight && last === this.lastChunk) {
  689. return this;
  690. }
  691. var newLeft = newRight ? newRight.previous : this.lastChunk;
  692. if (oldLeft) {
  693. oldLeft.next = oldRight;
  694. }
  695. if (oldRight) {
  696. oldRight.previous = oldLeft;
  697. }
  698. if (newLeft) {
  699. newLeft.next = first;
  700. }
  701. if (newRight) {
  702. newRight.previous = last;
  703. }
  704. if (!first.previous) {
  705. this.firstChunk = last.next;
  706. }
  707. if (!last.next) {
  708. this.lastChunk = first.previous;
  709. this.lastChunk.next = null;
  710. }
  711. first.previous = newLeft;
  712. last.next = newRight || null;
  713. if (!newLeft) {
  714. this.firstChunk = first;
  715. }
  716. if (!newRight) {
  717. this.lastChunk = last;
  718. }
  719. return this;
  720. };
  721. MagicString.prototype.overwrite = function overwrite(start, end, content, options) {
  722. if (typeof content !== 'string') {
  723. throw new TypeError('replacement content must be a string');
  724. }
  725. while (start < 0) {
  726. start += this.original.length;
  727. }
  728. while (end < 0) {
  729. end += this.original.length;
  730. }
  731. if (end > this.original.length) {
  732. throw new Error('end is out of bounds');
  733. }
  734. if (start === end) {
  735. throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead');
  736. }
  737. this._split(start);
  738. this._split(end);
  739. if (options === true) {
  740. if (!warned.storeName) {
  741. 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
  742. warned.storeName = true;
  743. }
  744. options = { storeName: true };
  745. }
  746. var storeName = options !== undefined ? options.storeName : false;
  747. var contentOnly = options !== undefined ? options.contentOnly : false;
  748. if (storeName) {
  749. var original = this.original.slice(start, end);
  750. this.storedNames[original] = true;
  751. }
  752. var first = this.byStart[start];
  753. var last = this.byEnd[end];
  754. if (first) {
  755. if (end > first.end && first.next !== this.byStart[first.end]) {
  756. throw new Error('Cannot overwrite across a split point');
  757. }
  758. first.edit(content, storeName, contentOnly);
  759. if (first !== last) {
  760. var chunk = first.next;
  761. while (chunk !== last) {
  762. chunk.edit('', false);
  763. chunk = chunk.next;
  764. }
  765. chunk.edit('', false);
  766. }
  767. }
  768. else {
  769. // must be inserting at the end
  770. var newChunk = new Chunk(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') {
  779. throw new TypeError('outro content must be a string');
  780. }
  781. this.intro = content + this.intro;
  782. return this;
  783. };
  784. MagicString.prototype.prependLeft = function prependLeft(index, content) {
  785. if (typeof content !== 'string') {
  786. throw new TypeError('inserted content must be a string');
  787. }
  788. this._split(index);
  789. var chunk = this.byEnd[index];
  790. if (chunk) {
  791. chunk.prependLeft(content);
  792. }
  793. else {
  794. this.intro = content + this.intro;
  795. }
  796. return this;
  797. };
  798. MagicString.prototype.prependRight = function prependRight(index, content) {
  799. if (typeof content !== 'string') {
  800. throw new TypeError('inserted content must be a string');
  801. }
  802. this._split(index);
  803. var chunk = this.byStart[index];
  804. if (chunk) {
  805. chunk.prependRight(content);
  806. }
  807. else {
  808. this.outro = content + this.outro;
  809. }
  810. return this;
  811. };
  812. MagicString.prototype.remove = function remove(start, end) {
  813. while (start < 0) {
  814. start += this.original.length;
  815. }
  816. while (end < 0) {
  817. end += this.original.length;
  818. }
  819. if (start === end) {
  820. return this;
  821. }
  822. if (start < 0 || end > this.original.length) {
  823. throw new Error('Character is out of bounds');
  824. }
  825. if (start > end) {
  826. throw new Error('end must be greater than start');
  827. }
  828. this._split(start);
  829. this._split(end);
  830. var chunk = this.byStart[start];
  831. while (chunk) {
  832. chunk.intro = '';
  833. chunk.outro = '';
  834. chunk.edit('');
  835. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  836. }
  837. return this;
  838. };
  839. MagicString.prototype.lastChar = function lastChar() {
  840. if (this.outro.length) {
  841. return this.outro[this.outro.length - 1];
  842. }
  843. var chunk = this.lastChunk;
  844. do {
  845. if (chunk.outro.length) {
  846. return chunk.outro[chunk.outro.length - 1];
  847. }
  848. if (chunk.content.length) {
  849. return chunk.content[chunk.content.length - 1];
  850. }
  851. if (chunk.intro.length) {
  852. return chunk.intro[chunk.intro.length - 1];
  853. }
  854. } while (chunk = chunk.previous);
  855. if (this.intro.length) {
  856. return this.intro[this.intro.length - 1];
  857. }
  858. return '';
  859. };
  860. MagicString.prototype.lastLine = function lastLine() {
  861. var lineIndex = this.outro.lastIndexOf(n);
  862. if (lineIndex !== -1) {
  863. return this.outro.substr(lineIndex + 1);
  864. }
  865. var lineStr = this.outro;
  866. var chunk = this.lastChunk;
  867. do {
  868. if (chunk.outro.length > 0) {
  869. lineIndex = chunk.outro.lastIndexOf(n);
  870. if (lineIndex !== -1) {
  871. return chunk.outro.substr(lineIndex + 1) + lineStr;
  872. }
  873. lineStr = chunk.outro + lineStr;
  874. }
  875. if (chunk.content.length > 0) {
  876. lineIndex = chunk.content.lastIndexOf(n);
  877. if (lineIndex !== -1) {
  878. return chunk.content.substr(lineIndex + 1) + lineStr;
  879. }
  880. lineStr = chunk.content + lineStr;
  881. }
  882. if (chunk.intro.length > 0) {
  883. lineIndex = chunk.intro.lastIndexOf(n);
  884. if (lineIndex !== -1) {
  885. return chunk.intro.substr(lineIndex + 1) + lineStr;
  886. }
  887. lineStr = chunk.intro + lineStr;
  888. }
  889. } while (chunk = chunk.previous);
  890. lineIndex = this.intro.lastIndexOf(n);
  891. if (lineIndex !== -1) {
  892. return this.intro.substr(lineIndex + 1) + lineStr;
  893. }
  894. return this.intro + lineStr;
  895. };
  896. MagicString.prototype.slice = function slice(start, end) {
  897. if (start === void 0)
  898. start = 0;
  899. if (end === void 0)
  900. end = this.original.length;
  901. while (start < 0) {
  902. start += this.original.length;
  903. }
  904. while (end < 0) {
  905. end += this.original.length;
  906. }
  907. var result = '';
  908. // find start chunk
  909. var chunk = this.firstChunk;
  910. while (chunk && (chunk.start > start || chunk.end <= start)) {
  911. // found end chunk before start
  912. if (chunk.start < end && chunk.end >= end) {
  913. return result;
  914. }
  915. chunk = chunk.next;
  916. }
  917. if (chunk && chunk.edited && chunk.start !== start) {
  918. throw new Error(("Cannot use replaced character " + start + " as slice start anchor."));
  919. }
  920. var startChunk = chunk;
  921. while (chunk) {
  922. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  923. result += chunk.intro;
  924. }
  925. var containsEnd = chunk.start < end && chunk.end >= end;
  926. if (containsEnd && chunk.edited && chunk.end !== end) {
  927. throw new Error(("Cannot use replaced character " + end + " as slice end anchor."));
  928. }
  929. var sliceStart = startChunk === chunk ? start - chunk.start : 0;
  930. var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  931. result += chunk.content.slice(sliceStart, sliceEnd);
  932. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  933. result += chunk.outro;
  934. }
  935. if (containsEnd) {
  936. break;
  937. }
  938. chunk = chunk.next;
  939. }
  940. return result;
  941. };
  942. // TODO deprecate this? not really very useful
  943. MagicString.prototype.snip = function snip(start, end) {
  944. var clone = this.clone();
  945. clone.remove(0, start);
  946. clone.remove(end, clone.original.length);
  947. return clone;
  948. };
  949. MagicString.prototype._split = function _split(index) {
  950. if (this.byStart[index] || this.byEnd[index]) {
  951. return;
  952. }
  953. var chunk = this.lastSearchedChunk;
  954. var searchForward = index > chunk.end;
  955. while (chunk) {
  956. if (chunk.contains(index)) {
  957. return this._splitChunk(chunk, index);
  958. }
  959. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  960. }
  961. };
  962. MagicString.prototype._splitChunk = function _splitChunk(chunk, index) {
  963. if (chunk.edited && chunk.content.length) {
  964. // zero-length edited chunks are a special case (overlapping replacements)
  965. var loc = getLocator(this.original)(index);
  966. throw new Error(("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")"));
  967. }
  968. var newChunk = chunk.split(index);
  969. this.byEnd[index] = chunk;
  970. this.byStart[index] = newChunk;
  971. this.byEnd[newChunk.end] = newChunk;
  972. if (chunk === this.lastChunk) {
  973. this.lastChunk = newChunk;
  974. }
  975. this.lastSearchedChunk = chunk;
  976. return true;
  977. };
  978. MagicString.prototype.toString = function toString() {
  979. var str = this.intro;
  980. var chunk = this.firstChunk;
  981. while (chunk) {
  982. str += chunk.toString();
  983. chunk = chunk.next;
  984. }
  985. return str + this.outro;
  986. };
  987. MagicString.prototype.isEmpty = function isEmpty() {
  988. var chunk = this.firstChunk;
  989. do {
  990. if (chunk.intro.length && chunk.intro.trim() ||
  991. chunk.content.length && chunk.content.trim() ||
  992. chunk.outro.length && chunk.outro.trim()) {
  993. return false;
  994. }
  995. } while (chunk = chunk.next);
  996. return true;
  997. };
  998. MagicString.prototype.length = function length() {
  999. var chunk = this.firstChunk;
  1000. var length = 0;
  1001. do {
  1002. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  1003. } while (chunk = chunk.next);
  1004. return length;
  1005. };
  1006. MagicString.prototype.trimLines = function trimLines() {
  1007. return this.trim('[\\r\\n]');
  1008. };
  1009. MagicString.prototype.trim = function trim(charType) {
  1010. return this.trimStart(charType).trimEnd(charType);
  1011. };
  1012. MagicString.prototype.trimEndAborted = function trimEndAborted(charType) {
  1013. var rx = new RegExp((charType || '\\s') + '+$');
  1014. this.outro = this.outro.replace(rx, '');
  1015. if (this.outro.length) {
  1016. return true;
  1017. }
  1018. var chunk = this.lastChunk;
  1019. do {
  1020. var end = chunk.end;
  1021. var aborted = chunk.trimEnd(rx);
  1022. // if chunk was trimmed, we have a new lastChunk
  1023. if (chunk.end !== end) {
  1024. if (this.lastChunk === chunk) {
  1025. this.lastChunk = chunk.next;
  1026. }
  1027. this.byEnd[chunk.end] = chunk;
  1028. this.byStart[chunk.next.start] = chunk.next;
  1029. this.byEnd[chunk.next.end] = chunk.next;
  1030. }
  1031. if (aborted) {
  1032. return true;
  1033. }
  1034. chunk = chunk.previous;
  1035. } while (chunk);
  1036. return false;
  1037. };
  1038. MagicString.prototype.trimEnd = function trimEnd(charType) {
  1039. this.trimEndAborted(charType);
  1040. return this;
  1041. };
  1042. MagicString.prototype.trimStartAborted = function trimStartAborted(charType) {
  1043. var rx = new RegExp('^' + (charType || '\\s') + '+');
  1044. this.intro = this.intro.replace(rx, '');
  1045. if (this.intro.length) {
  1046. return true;
  1047. }
  1048. var chunk = this.firstChunk;
  1049. do {
  1050. var end = chunk.end;
  1051. var aborted = chunk.trimStart(rx);
  1052. if (chunk.end !== end) {
  1053. // special case...
  1054. if (chunk === this.lastChunk) {
  1055. this.lastChunk = chunk.next;
  1056. }
  1057. this.byEnd[chunk.end] = chunk;
  1058. this.byStart[chunk.next.start] = chunk.next;
  1059. this.byEnd[chunk.next.end] = chunk.next;
  1060. }
  1061. if (aborted) {
  1062. return true;
  1063. }
  1064. chunk = chunk.next;
  1065. } while (chunk);
  1066. return false;
  1067. };
  1068. MagicString.prototype.trimStart = function trimStart(charType) {
  1069. this.trimStartAborted(charType);
  1070. return this;
  1071. };
  1072. var hasOwnProp = Object.prototype.hasOwnProperty;
  1073. var Bundle = function Bundle(options) {
  1074. if (options === void 0)
  1075. options = {};
  1076. this.intro = options.intro || '';
  1077. this.separator = options.separator !== undefined ? options.separator : '\n';
  1078. this.sources = [];
  1079. this.uniqueSources = [];
  1080. this.uniqueSourceIndexByFilename = {};
  1081. };
  1082. Bundle.prototype.addSource = function addSource(source) {
  1083. if (source instanceof MagicString) {
  1084. return this.addSource({
  1085. content: source,
  1086. filename: source.filename,
  1087. separator: this.separator
  1088. });
  1089. }
  1090. if (!isObject(source) || !source.content) {
  1091. throw new Error('bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`');
  1092. }
  1093. ['filename', 'indentExclusionRanges', 'separator'].forEach(function (option) {
  1094. if (!hasOwnProp.call(source, option)) {
  1095. source[option] = source.content[option];
  1096. }
  1097. });
  1098. if (source.separator === undefined) {
  1099. // TODO there's a bunch of this sort of thing, needs cleaning up
  1100. source.separator = this.separator;
  1101. }
  1102. if (source.filename) {
  1103. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  1104. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  1105. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  1106. }
  1107. else {
  1108. var uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  1109. if (source.content.original !== uniqueSource.content) {
  1110. throw new Error(("Illegal source: same filename (" + (source.filename) + "), different contents"));
  1111. }
  1112. }
  1113. }
  1114. this.sources.push(source);
  1115. return this;
  1116. };
  1117. Bundle.prototype.append = function append(str, options) {
  1118. this.addSource({
  1119. content: new MagicString(str),
  1120. separator: (options && options.separator) || ''
  1121. });
  1122. return this;
  1123. };
  1124. Bundle.prototype.clone = function clone() {
  1125. var bundle = new Bundle({
  1126. intro: this.intro,
  1127. separator: this.separator
  1128. });
  1129. this.sources.forEach(function (source) {
  1130. bundle.addSource({
  1131. filename: source.filename,
  1132. content: source.content.clone(),
  1133. separator: source.separator
  1134. });
  1135. });
  1136. return bundle;
  1137. };
  1138. Bundle.prototype.generateDecodedMap = function generateDecodedMap(options) {
  1139. var this$1 = this;
  1140. if (options === void 0)
  1141. options = {};
  1142. var names = [];
  1143. this.sources.forEach(function (source) {
  1144. Object.keys(source.content.storedNames).forEach(function (name) {
  1145. if (!~names.indexOf(name)) {
  1146. names.push(name);
  1147. }
  1148. });
  1149. });
  1150. var mappings = new Mappings(options.hires);
  1151. if (this.intro) {
  1152. mappings.advance(this.intro);
  1153. }
  1154. this.sources.forEach(function (source, i) {
  1155. if (i > 0) {
  1156. mappings.advance(this$1.separator);
  1157. }
  1158. var sourceIndex = source.filename ? this$1.uniqueSourceIndexByFilename[source.filename] : -1;
  1159. var magicString = source.content;
  1160. var locate = getLocator(magicString.original);
  1161. if (magicString.intro) {
  1162. mappings.advance(magicString.intro);
  1163. }
  1164. magicString.firstChunk.eachNext(function (chunk) {
  1165. var loc = locate(chunk.start);
  1166. if (chunk.intro.length) {
  1167. mappings.advance(chunk.intro);
  1168. }
  1169. if (source.filename) {
  1170. if (chunk.edited) {
  1171. mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1);
  1172. }
  1173. else {
  1174. mappings.addUneditedChunk(sourceIndex, chunk, magicString.original, loc, magicString.sourcemapLocations);
  1175. }
  1176. }
  1177. else {
  1178. mappings.advance(chunk.content);
  1179. }
  1180. if (chunk.outro.length) {
  1181. mappings.advance(chunk.outro);
  1182. }
  1183. });
  1184. if (magicString.outro) {
  1185. mappings.advance(magicString.outro);
  1186. }
  1187. });
  1188. return {
  1189. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  1190. sources: this.uniqueSources.map(function (source) {
  1191. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  1192. }),
  1193. sourcesContent: this.uniqueSources.map(function (source) {
  1194. return options.includeContent ? source.content : null;
  1195. }),
  1196. names: names,
  1197. mappings: mappings.raw
  1198. };
  1199. };
  1200. Bundle.prototype.generateMap = function generateMap(options) {
  1201. return new SourceMap(this.generateDecodedMap(options));
  1202. };
  1203. Bundle.prototype.getIndentString = function getIndentString() {
  1204. var indentStringCounts = {};
  1205. this.sources.forEach(function (source) {
  1206. var indentStr = source.content.indentStr;
  1207. if (indentStr === null) {
  1208. return;
  1209. }
  1210. if (!indentStringCounts[indentStr]) {
  1211. indentStringCounts[indentStr] = 0;
  1212. }
  1213. indentStringCounts[indentStr] += 1;
  1214. });
  1215. return (Object.keys(indentStringCounts).sort(function (a, b) {
  1216. return indentStringCounts[a] - indentStringCounts[b];
  1217. })[0] || '\t');
  1218. };
  1219. Bundle.prototype.indent = function indent(indentStr) {
  1220. var this$1 = this;
  1221. if (!arguments.length) {
  1222. indentStr = this.getIndentString();
  1223. }
  1224. if (indentStr === '') {
  1225. return this;
  1226. } // noop
  1227. var trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  1228. this.sources.forEach(function (source, i) {
  1229. var separator = source.separator !== undefined ? source.separator : this$1.separator;
  1230. var indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  1231. source.content.indent(indentStr, {
  1232. exclude: source.indentExclusionRanges,
  1233. indentStart: indentStart //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  1234. });
  1235. trailingNewline = source.content.lastChar() === '\n';
  1236. });
  1237. if (this.intro) {
  1238. this.intro =
  1239. indentStr +
  1240. this.intro.replace(/^[^\n]/gm, function (match, index) {
  1241. return index > 0 ? indentStr + match : match;
  1242. });
  1243. }
  1244. return this;
  1245. };
  1246. Bundle.prototype.prepend = function prepend(str) {
  1247. this.intro = str + this.intro;
  1248. return this;
  1249. };
  1250. Bundle.prototype.toString = function toString() {
  1251. var this$1 = this;
  1252. var body = this.sources
  1253. .map(function (source, i) {
  1254. var separator = source.separator !== undefined ? source.separator : this$1.separator;
  1255. var str = (i > 0 ? separator : '') + source.content.toString();
  1256. return str;
  1257. })
  1258. .join('');
  1259. return this.intro + body;
  1260. };
  1261. Bundle.prototype.isEmpty = function isEmpty() {
  1262. if (this.intro.length && this.intro.trim()) {
  1263. return false;
  1264. }
  1265. if (this.sources.some(function (source) { return !source.content.isEmpty(); })) {
  1266. return false;
  1267. }
  1268. return true;
  1269. };
  1270. Bundle.prototype.length = function length() {
  1271. return this.sources.reduce(function (length, source) { return length + source.content.length(); }, this.intro.length);
  1272. };
  1273. Bundle.prototype.trimLines = function trimLines() {
  1274. return this.trim('[\\r\\n]');
  1275. };
  1276. Bundle.prototype.trim = function trim(charType) {
  1277. return this.trimStart(charType).trimEnd(charType);
  1278. };
  1279. Bundle.prototype.trimStart = function trimStart(charType) {
  1280. var rx = new RegExp('^' + (charType || '\\s') + '+');
  1281. this.intro = this.intro.replace(rx, '');
  1282. if (!this.intro) {
  1283. var source;
  1284. var i = 0;
  1285. do {
  1286. source = this.sources[i++];
  1287. if (!source) {
  1288. break;
  1289. }
  1290. } while (!source.content.trimStartAborted(charType));
  1291. }
  1292. return this;
  1293. };
  1294. Bundle.prototype.trimEnd = function trimEnd(charType) {
  1295. var rx = new RegExp((charType || '\\s') + '+$');
  1296. var source;
  1297. var i = this.sources.length - 1;
  1298. do {
  1299. source = this.sources[i--];
  1300. if (!source) {
  1301. this.intro = this.intro.replace(rx, '');
  1302. break;
  1303. }
  1304. } while (!source.content.trimEndAborted(charType));
  1305. return this;
  1306. };
  1307. var minimalisticAssert = assert;
  1308. function assert(val, msg) {
  1309. if (!val)
  1310. throw new Error(msg || 'Assertion failed');
  1311. }
  1312. assert.equal = function assertEqual(l, r, msg) {
  1313. if (l != r)
  1314. throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
  1315. };
  1316. function createCommonjsModule(fn, module) {
  1317. return module = { exports: {} }, fn(module, module.exports), module.exports;
  1318. }
  1319. var inherits_browser = createCommonjsModule(function (module) {
  1320. if (typeof Object.create === 'function') {
  1321. // implementation from standard node.js 'util' module
  1322. module.exports = function inherits(ctor, superCtor) {
  1323. ctor.super_ = superCtor;
  1324. ctor.prototype = Object.create(superCtor.prototype, {
  1325. constructor: {
  1326. value: ctor,
  1327. enumerable: false,
  1328. writable: true,
  1329. configurable: true
  1330. }
  1331. });
  1332. };
  1333. }
  1334. else {
  1335. // old school shim for old browsers
  1336. module.exports = function inherits(ctor, superCtor) {
  1337. ctor.super_ = superCtor;
  1338. var TempCtor = function () { };
  1339. TempCtor.prototype = superCtor.prototype;
  1340. ctor.prototype = new TempCtor();
  1341. ctor.prototype.constructor = ctor;
  1342. };
  1343. }
  1344. });
  1345. var inherits = createCommonjsModule(function (module) {
  1346. try {
  1347. var util$1 = util;
  1348. if (typeof util$1.inherits !== 'function')
  1349. throw '';
  1350. module.exports = util$1.inherits;
  1351. }
  1352. catch (e) {
  1353. module.exports = inherits_browser;
  1354. }
  1355. });
  1356. var inherits_1 = inherits;
  1357. function isSurrogatePair(msg, i) {
  1358. if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) {
  1359. return false;
  1360. }
  1361. if (i < 0 || i + 1 >= msg.length) {
  1362. return false;
  1363. }
  1364. return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00;
  1365. }
  1366. function toArray(msg, enc) {
  1367. if (Array.isArray(msg))
  1368. return msg.slice();
  1369. if (!msg)
  1370. return [];
  1371. var res = [];
  1372. if (typeof msg === 'string') {
  1373. if (!enc) {
  1374. // Inspired by stringToUtf8ByteArray() in closure-library by Google
  1375. // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
  1376. // Apache License 2.0
  1377. // https://github.com/google/closure-library/blob/master/LICENSE
  1378. var p = 0;
  1379. for (var i = 0; i < msg.length; i++) {
  1380. var c = msg.charCodeAt(i);
  1381. if (c < 128) {
  1382. res[p++] = c;
  1383. }
  1384. else if (c < 2048) {
  1385. res[p++] = (c >> 6) | 192;
  1386. res[p++] = (c & 63) | 128;
  1387. }
  1388. else if (isSurrogatePair(msg, i)) {
  1389. c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF);
  1390. res[p++] = (c >> 18) | 240;
  1391. res[p++] = ((c >> 12) & 63) | 128;
  1392. res[p++] = ((c >> 6) & 63) | 128;
  1393. res[p++] = (c & 63) | 128;
  1394. }
  1395. else {
  1396. res[p++] = (c >> 12) | 224;
  1397. res[p++] = ((c >> 6) & 63) | 128;
  1398. res[p++] = (c & 63) | 128;
  1399. }
  1400. }
  1401. }
  1402. else if (enc === 'hex') {
  1403. msg = msg.replace(/[^a-z0-9]+/ig, '');
  1404. if (msg.length % 2 !== 0)
  1405. msg = '0' + msg;
  1406. for (i = 0; i < msg.length; i += 2)
  1407. res.push(parseInt(msg[i] + msg[i + 1], 16));
  1408. }
  1409. }
  1410. else {
  1411. for (i = 0; i < msg.length; i++)
  1412. res[i] = msg[i] | 0;
  1413. }
  1414. return res;
  1415. }
  1416. var toArray_1 = toArray;
  1417. function toHex(msg) {
  1418. var res = '';
  1419. for (var i = 0; i < msg.length; i++)
  1420. res += zero2(msg[i].toString(16));
  1421. return res;
  1422. }
  1423. var toHex_1 = toHex;
  1424. function htonl(w) {
  1425. var res = (w >>> 24) |
  1426. ((w >>> 8) & 0xff00) |
  1427. ((w << 8) & 0xff0000) |
  1428. ((w & 0xff) << 24);
  1429. return res >>> 0;
  1430. }
  1431. var htonl_1 = htonl;
  1432. function toHex32(msg, endian) {
  1433. var res = '';
  1434. for (var i = 0; i < msg.length; i++) {
  1435. var w = msg[i];
  1436. if (endian === 'little')
  1437. w = htonl(w);
  1438. res += zero8(w.toString(16));
  1439. }
  1440. return res;
  1441. }
  1442. var toHex32_1 = toHex32;
  1443. function zero2(word) {
  1444. if (word.length === 1)
  1445. return '0' + word;
  1446. else
  1447. return word;
  1448. }
  1449. var zero2_1 = zero2;
  1450. function zero8(word) {
  1451. if (word.length === 7)
  1452. return '0' + word;
  1453. else if (word.length === 6)
  1454. return '00' + word;
  1455. else if (word.length === 5)
  1456. return '000' + word;
  1457. else if (word.length === 4)
  1458. return '0000' + word;
  1459. else if (word.length === 3)
  1460. return '00000' + word;
  1461. else if (word.length === 2)
  1462. return '000000' + word;
  1463. else if (word.length === 1)
  1464. return '0000000' + word;
  1465. else
  1466. return word;
  1467. }
  1468. var zero8_1 = zero8;
  1469. function join32(msg, start, end, endian) {
  1470. var len = end - start;
  1471. minimalisticAssert(len % 4 === 0);
  1472. var res = new Array(len / 4);
  1473. for (var i = 0, k = start; i < res.length; i++, k += 4) {
  1474. var w;
  1475. if (endian === 'big')
  1476. w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
  1477. else
  1478. w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
  1479. res[i] = w >>> 0;
  1480. }
  1481. return res;
  1482. }
  1483. var join32_1 = join32;
  1484. function split32(msg, endian) {
  1485. var res = new Array(msg.length * 4);
  1486. for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
  1487. var m = msg[i];
  1488. if (endian === 'big') {
  1489. res[k] = m >>> 24;
  1490. res[k + 1] = (m >>> 16) & 0xff;
  1491. res[k + 2] = (m >>> 8) & 0xff;
  1492. res[k + 3] = m & 0xff;
  1493. }
  1494. else {
  1495. res[k + 3] = m >>> 24;
  1496. res[k + 2] = (m >>> 16) & 0xff;
  1497. res[k + 1] = (m >>> 8) & 0xff;
  1498. res[k] = m & 0xff;
  1499. }
  1500. }
  1501. return res;
  1502. }
  1503. var split32_1 = split32;
  1504. function rotr32(w, b) {
  1505. return (w >>> b) | (w << (32 - b));
  1506. }
  1507. var rotr32_1 = rotr32;
  1508. function rotl32(w, b) {
  1509. return (w << b) | (w >>> (32 - b));
  1510. }
  1511. var rotl32_1 = rotl32;
  1512. function sum32(a, b) {
  1513. return (a + b) >>> 0;
  1514. }
  1515. var sum32_1 = sum32;
  1516. function sum32_3(a, b, c) {
  1517. return (a + b + c) >>> 0;
  1518. }
  1519. var sum32_3_1 = sum32_3;
  1520. function sum32_4(a, b, c, d) {
  1521. return (a + b + c + d) >>> 0;
  1522. }
  1523. var sum32_4_1 = sum32_4;
  1524. function sum32_5(a, b, c, d, e) {
  1525. return (a + b + c + d + e) >>> 0;
  1526. }
  1527. var sum32_5_1 = sum32_5;
  1528. function sum64(buf, pos, ah, al) {
  1529. var bh = buf[pos];
  1530. var bl = buf[pos + 1];
  1531. var lo = (al + bl) >>> 0;
  1532. var hi = (lo < al ? 1 : 0) + ah + bh;
  1533. buf[pos] = hi >>> 0;
  1534. buf[pos + 1] = lo;
  1535. }
  1536. var sum64_1 = sum64;
  1537. function sum64_hi(ah, al, bh, bl) {
  1538. var lo = (al + bl) >>> 0;
  1539. var hi = (lo < al ? 1 : 0) + ah + bh;
  1540. return hi >>> 0;
  1541. }
  1542. var sum64_hi_1 = sum64_hi;
  1543. function sum64_lo(ah, al, bh, bl) {
  1544. var lo = al + bl;
  1545. return lo >>> 0;
  1546. }
  1547. var sum64_lo_1 = sum64_lo;
  1548. function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
  1549. var carry = 0;
  1550. var lo = al;
  1551. lo = (lo + bl) >>> 0;
  1552. carry += lo < al ? 1 : 0;
  1553. lo = (lo + cl) >>> 0;
  1554. carry += lo < cl ? 1 : 0;
  1555. lo = (lo + dl) >>> 0;
  1556. carry += lo < dl ? 1 : 0;
  1557. var hi = ah + bh + ch + dh + carry;
  1558. return hi >>> 0;
  1559. }
  1560. var sum64_4_hi_1 = sum64_4_hi;
  1561. function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
  1562. var lo = al + bl + cl + dl;
  1563. return lo >>> 0;
  1564. }
  1565. var sum64_4_lo_1 = sum64_4_lo;
  1566. function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
  1567. var carry = 0;
  1568. var lo = al;
  1569. lo = (lo + bl) >>> 0;
  1570. carry += lo < al ? 1 : 0;
  1571. lo = (lo + cl) >>> 0;
  1572. carry += lo < cl ? 1 : 0;
  1573. lo = (lo + dl) >>> 0;
  1574. carry += lo < dl ? 1 : 0;
  1575. lo = (lo + el) >>> 0;
  1576. carry += lo < el ? 1 : 0;
  1577. var hi = ah + bh + ch + dh + eh + carry;
  1578. return hi >>> 0;
  1579. }
  1580. var sum64_5_hi_1 = sum64_5_hi;
  1581. function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
  1582. var lo = al + bl + cl + dl + el;
  1583. return lo >>> 0;
  1584. }
  1585. var sum64_5_lo_1 = sum64_5_lo;
  1586. function rotr64_hi(ah, al, num) {
  1587. var r = (al << (32 - num)) | (ah >>> num);
  1588. return r >>> 0;
  1589. }
  1590. var rotr64_hi_1 = rotr64_hi;
  1591. function rotr64_lo(ah, al, num) {
  1592. var r = (ah << (32 - num)) | (al >>> num);
  1593. return r >>> 0;
  1594. }
  1595. var rotr64_lo_1 = rotr64_lo;
  1596. function shr64_hi(ah, al, num) {
  1597. return ah >>> num;
  1598. }
  1599. var shr64_hi_1 = shr64_hi;
  1600. function shr64_lo(ah, al, num) {
  1601. var r = (ah << (32 - num)) | (al >>> num);
  1602. return r >>> 0;
  1603. }
  1604. var shr64_lo_1 = shr64_lo;
  1605. var utils = {
  1606. inherits: inherits_1,
  1607. toArray: toArray_1,
  1608. toHex: toHex_1,
  1609. htonl: htonl_1,
  1610. toHex32: toHex32_1,
  1611. zero2: zero2_1,
  1612. zero8: zero8_1,
  1613. join32: join32_1,
  1614. split32: split32_1,
  1615. rotr32: rotr32_1,
  1616. rotl32: rotl32_1,
  1617. sum32: sum32_1,
  1618. sum32_3: sum32_3_1,
  1619. sum32_4: sum32_4_1,
  1620. sum32_5: sum32_5_1,
  1621. sum64: sum64_1,
  1622. sum64_hi: sum64_hi_1,
  1623. sum64_lo: sum64_lo_1,
  1624. sum64_4_hi: sum64_4_hi_1,
  1625. sum64_4_lo: sum64_4_lo_1,
  1626. sum64_5_hi: sum64_5_hi_1,
  1627. sum64_5_lo: sum64_5_lo_1,
  1628. rotr64_hi: rotr64_hi_1,
  1629. rotr64_lo: rotr64_lo_1,
  1630. shr64_hi: shr64_hi_1,
  1631. shr64_lo: shr64_lo_1
  1632. };
  1633. function BlockHash() {
  1634. this.pending = null;
  1635. this.pendingTotal = 0;
  1636. this.blockSize = this.constructor.blockSize;
  1637. this.outSize = this.constructor.outSize;
  1638. this.hmacStrength = this.constructor.hmacStrength;
  1639. this.padLength = this.constructor.padLength / 8;
  1640. this.endian = 'big';
  1641. this._delta8 = this.blockSize / 8;
  1642. this._delta32 = this.blockSize / 32;
  1643. }
  1644. var BlockHash_1 = BlockHash;
  1645. BlockHash.prototype.update = function update(msg, enc) {
  1646. // Convert message to array, pad it, and join into 32bit blocks
  1647. msg = utils.toArray(msg, enc);
  1648. if (!this.pending)
  1649. this.pending = msg;
  1650. else
  1651. this.pending = this.pending.concat(msg);
  1652. this.pendingTotal += msg.length;
  1653. // Enough data, try updating
  1654. if (this.pending.length >= this._delta8) {
  1655. msg = this.pending;
  1656. // Process pending data in blocks
  1657. var r = msg.length % this._delta8;
  1658. this.pending = msg.slice(msg.length - r, msg.length);
  1659. if (this.pending.length === 0)
  1660. this.pending = null;
  1661. msg = utils.join32(msg, 0, msg.length - r, this.endian);
  1662. for (var i = 0; i < msg.length; i += this._delta32)
  1663. this._update(msg, i, i + this._delta32);
  1664. }
  1665. return this;
  1666. };
  1667. BlockHash.prototype.digest = function digest(enc) {
  1668. this.update(this._pad());
  1669. minimalisticAssert(this.pending === null);
  1670. return this._digest(enc);
  1671. };
  1672. BlockHash.prototype._pad = function pad() {
  1673. var len = this.pendingTotal;
  1674. var bytes = this._delta8;
  1675. var k = bytes - ((len + this.padLength) % bytes);
  1676. var res = new Array(k + this.padLength);
  1677. res[0] = 0x80;
  1678. for (var i = 1; i < k; i++)
  1679. res[i] = 0;
  1680. // Append length
  1681. len <<= 3;
  1682. if (this.endian === 'big') {
  1683. for (var t = 8; t < this.padLength; t++)
  1684. res[i++] = 0;
  1685. res[i++] = 0;
  1686. res[i++] = 0;
  1687. res[i++] = 0;
  1688. res[i++] = 0;
  1689. res[i++] = (len >>> 24) & 0xff;
  1690. res[i++] = (len >>> 16) & 0xff;
  1691. res[i++] = (len >>> 8) & 0xff;
  1692. res[i++] = len & 0xff;
  1693. }
  1694. else {
  1695. res[i++] = len & 0xff;
  1696. res[i++] = (len >>> 8) & 0xff;
  1697. res[i++] = (len >>> 16) & 0xff;
  1698. res[i++] = (len >>> 24) & 0xff;
  1699. res[i++] = 0;
  1700. res[i++] = 0;
  1701. res[i++] = 0;
  1702. res[i++] = 0;
  1703. for (t = 8; t < this.padLength; t++)
  1704. res[i++] = 0;
  1705. }
  1706. return res;
  1707. };
  1708. var common = {
  1709. BlockHash: BlockHash_1
  1710. };
  1711. var rotr32$1 = utils.rotr32;
  1712. function ft_1(s, x, y, z) {
  1713. if (s === 0)
  1714. return ch32(x, y, z);
  1715. if (s === 1 || s === 3)
  1716. return p32(x, y, z);
  1717. if (s === 2)
  1718. return maj32(x, y, z);
  1719. }
  1720. var ft_1_1 = ft_1;
  1721. function ch32(x, y, z) {
  1722. return (x & y) ^ ((~x) & z);
  1723. }
  1724. var ch32_1 = ch32;
  1725. function maj32(x, y, z) {
  1726. return (x & y) ^ (x & z) ^ (y & z);
  1727. }
  1728. var maj32_1 = maj32;
  1729. function p32(x, y, z) {
  1730. return x ^ y ^ z;
  1731. }
  1732. var p32_1 = p32;
  1733. function s0_256(x) {
  1734. return rotr32$1(x, 2) ^ rotr32$1(x, 13) ^ rotr32$1(x, 22);
  1735. }
  1736. var s0_256_1 = s0_256;
  1737. function s1_256(x) {
  1738. return rotr32$1(x, 6) ^ rotr32$1(x, 11) ^ rotr32$1(x, 25);
  1739. }
  1740. var s1_256_1 = s1_256;
  1741. function g0_256(x) {
  1742. return rotr32$1(x, 7) ^ rotr32$1(x, 18) ^ (x >>> 3);
  1743. }
  1744. var g0_256_1 = g0_256;
  1745. function g1_256(x) {
  1746. return rotr32$1(x, 17) ^ rotr32$1(x, 19) ^ (x >>> 10);
  1747. }
  1748. var g1_256_1 = g1_256;
  1749. var common$1 = {
  1750. ft_1: ft_1_1,
  1751. ch32: ch32_1,
  1752. maj32: maj32_1,
  1753. p32: p32_1,
  1754. s0_256: s0_256_1,
  1755. s1_256: s1_256_1,
  1756. g0_256: g0_256_1,
  1757. g1_256: g1_256_1
  1758. };
  1759. var sum32$1 = utils.sum32;
  1760. var sum32_4$1 = utils.sum32_4;
  1761. var sum32_5$1 = utils.sum32_5;
  1762. var ch32$1 = common$1.ch32;
  1763. var maj32$1 = common$1.maj32;
  1764. var s0_256$1 = common$1.s0_256;
  1765. var s1_256$1 = common$1.s1_256;
  1766. var g0_256$1 = common$1.g0_256;
  1767. var g1_256$1 = common$1.g1_256;
  1768. var BlockHash$1 = common.BlockHash;
  1769. var sha256_K = [
  1770. 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
  1771. 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
  1772. 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
  1773. 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
  1774. 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
  1775. 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
  1776. 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
  1777. 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
  1778. 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
  1779. 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
  1780. 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
  1781. 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
  1782. 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
  1783. 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
  1784. 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
  1785. 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
  1786. ];
  1787. function SHA256() {
  1788. if (!(this instanceof SHA256))
  1789. return new SHA256();
  1790. BlockHash$1.call(this);
  1791. this.h = [
  1792. 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
  1793. 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
  1794. ];
  1795. this.k = sha256_K;
  1796. this.W = new Array(64);
  1797. }
  1798. utils.inherits(SHA256, BlockHash$1);
  1799. var _256 = SHA256;
  1800. SHA256.blockSize = 512;
  1801. SHA256.outSize = 256;
  1802. SHA256.hmacStrength = 192;
  1803. SHA256.padLength = 64;
  1804. SHA256.prototype._update = function _update(msg, start) {
  1805. var W = this.W;
  1806. for (var i = 0; i < 16; i++)
  1807. W[i] = msg[start + i];
  1808. for (; i < W.length; i++)
  1809. W[i] = sum32_4$1(g1_256$1(W[i - 2]), W[i - 7], g0_256$1(W[i - 15]), W[i - 16]);
  1810. var a = this.h[0];
  1811. var b = this.h[1];
  1812. var c = this.h[2];
  1813. var d = this.h[3];
  1814. var e = this.h[4];
  1815. var f = this.h[5];
  1816. var g = this.h[6];
  1817. var h = this.h[7];
  1818. minimalisticAssert(this.k.length === W.length);
  1819. for (i = 0; i < W.length; i++) {
  1820. var T1 = sum32_5$1(h, s1_256$1(e), ch32$1(e, f, g), this.k[i], W[i]);
  1821. var T2 = sum32$1(s0_256$1(a), maj32$1(a, b, c));
  1822. h = g;
  1823. g = f;
  1824. f = e;
  1825. e = sum32$1(d, T1);
  1826. d = c;
  1827. c = b;
  1828. b = a;
  1829. a = sum32$1(T1, T2);
  1830. }
  1831. this.h[0] = sum32$1(this.h[0], a);
  1832. this.h[1] = sum32$1(this.h[1], b);
  1833. this.h[2] = sum32$1(this.h[2], c);
  1834. this.h[3] = sum32$1(this.h[3], d);
  1835. this.h[4] = sum32$1(this.h[4], e);
  1836. this.h[5] = sum32$1(this.h[5], f);
  1837. this.h[6] = sum32$1(this.h[6], g);
  1838. this.h[7] = sum32$1(this.h[7], h);
  1839. };
  1840. SHA256.prototype._digest = function digest(enc) {
  1841. if (enc === 'hex')
  1842. return utils.toHex32(this.h, 'big');
  1843. else
  1844. return utils.split32(this.h, 'big');
  1845. };
  1846. const createHash = () => _256();
  1847. function relative(from, to) {
  1848. const fromParts = from.split(/[/\\]/).filter(Boolean);
  1849. const toParts = to.split(/[/\\]/).filter(Boolean);
  1850. if (fromParts[0] === '.')
  1851. fromParts.shift();
  1852. if (toParts[0] === '.')
  1853. toParts.shift();
  1854. while (fromParts[0] && toParts[0] && fromParts[0] === toParts[0]) {
  1855. fromParts.shift();
  1856. toParts.shift();
  1857. }
  1858. while (toParts[0] === '..' && fromParts.length > 0) {
  1859. toParts.shift();
  1860. fromParts.pop();
  1861. }
  1862. while (fromParts.pop()) {
  1863. toParts.unshift('..');
  1864. }
  1865. return toParts.join('/');
  1866. }
  1867. const UnknownKey = Symbol('Unknown Key');
  1868. const EMPTY_PATH = [];
  1869. const UNKNOWN_PATH = [UnknownKey];
  1870. const EntitiesKey = Symbol('Entities');
  1871. class PathTracker {
  1872. constructor() {
  1873. this.entityPaths = Object.create(null, { [EntitiesKey]: { value: new Set() } });
  1874. }
  1875. getEntities(path) {
  1876. let currentPaths = this.entityPaths;
  1877. for (const pathSegment of path) {
  1878. currentPaths = currentPaths[pathSegment] =
  1879. currentPaths[pathSegment] ||
  1880. Object.create(null, { [EntitiesKey]: { value: new Set() } });
  1881. }
  1882. return currentPaths[EntitiesKey];
  1883. }
  1884. }
  1885. const SHARED_RECURSION_TRACKER = new PathTracker();
  1886. const BROKEN_FLOW_NONE = 0;
  1887. const BROKEN_FLOW_BREAK_CONTINUE = 1;
  1888. const BROKEN_FLOW_ERROR_RETURN_LABEL = 2;
  1889. function createInclusionContext() {
  1890. return {
  1891. brokenFlow: BROKEN_FLOW_NONE,
  1892. includedLabels: new Set()
  1893. };
  1894. }
  1895. function createHasEffectsContext() {
  1896. return {
  1897. accessed: new PathTracker(),
  1898. assigned: new PathTracker(),
  1899. brokenFlow: BROKEN_FLOW_NONE,
  1900. called: new PathTracker(),
  1901. ignore: {
  1902. breaks: false,
  1903. continues: false,
  1904. labels: new Set(),
  1905. returnAwaitYield: false
  1906. },
  1907. includedLabels: new Set(),
  1908. instantiated: new PathTracker(),
  1909. replacedVariableInits: new Map()
  1910. };
  1911. }
  1912. const BlockStatement = 'BlockStatement';
  1913. const CallExpression = 'CallExpression';
  1914. const ExportNamespaceSpecifier = 'ExportNamespaceSpecifier';
  1915. const ExpressionStatement = 'ExpressionStatement';
  1916. const FunctionExpression = 'FunctionExpression';
  1917. const Identifier = 'Identifier';
  1918. const ImportDefaultSpecifier = 'ImportDefaultSpecifier';
  1919. const ImportNamespaceSpecifier = 'ImportNamespaceSpecifier';
  1920. const Program = 'Program';
  1921. const Property = 'Property';
  1922. const ReturnStatement = 'ReturnStatement';
  1923. function treeshakeNode(node, code, start, end) {
  1924. code.remove(start, end);
  1925. if (node.annotations) {
  1926. for (const annotation of node.annotations) {
  1927. if (annotation.start < start) {
  1928. code.remove(annotation.start, annotation.end);
  1929. }
  1930. else {
  1931. return;
  1932. }
  1933. }
  1934. }
  1935. }
  1936. function removeAnnotations(node, code) {
  1937. if (!node.annotations && node.parent.type === ExpressionStatement) {
  1938. node = node.parent;
  1939. }
  1940. if (node.annotations) {
  1941. for (const annotation of node.annotations) {
  1942. code.remove(annotation.start, annotation.end);
  1943. }
  1944. }
  1945. }
  1946. const NO_SEMICOLON = { isNoStatement: true };
  1947. // This assumes there are only white-space and comments between start and the string we are looking for
  1948. function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
  1949. let searchPos, charCodeAfterSlash;
  1950. searchPos = code.indexOf(searchString, start);
  1951. while (true) {
  1952. start = code.indexOf('/', start);
  1953. if (start === -1 || start >= searchPos)
  1954. return searchPos;
  1955. charCodeAfterSlash = code.charCodeAt(++start);
  1956. ++start;
  1957. // With our assumption, '/' always starts a comment. Determine comment type:
  1958. start =
  1959. charCodeAfterSlash === 47 /*"/"*/
  1960. ? code.indexOf('\n', start) + 1
  1961. : code.indexOf('*/', start) + 2;
  1962. if (start > searchPos) {
  1963. searchPos = code.indexOf(searchString, start);
  1964. }
  1965. }
  1966. }
  1967. // This assumes "code" only contains white-space and comments
  1968. function findFirstLineBreakOutsideComment(code) {
  1969. let lineBreakPos, charCodeAfterSlash, start = 0;
  1970. lineBreakPos = code.indexOf('\n', start);
  1971. while (true) {
  1972. start = code.indexOf('/', start);
  1973. if (start === -1 || start > lineBreakPos)
  1974. return lineBreakPos;
  1975. // With our assumption, '/' always starts a comment. Determine comment type:
  1976. charCodeAfterSlash = code.charCodeAt(++start);
  1977. if (charCodeAfterSlash === 47 /*"/"*/)
  1978. return lineBreakPos;
  1979. start = code.indexOf('*/', start + 2) + 2;
  1980. if (start > lineBreakPos) {
  1981. lineBreakPos = code.indexOf('\n', start);
  1982. }
  1983. }
  1984. }
  1985. function renderStatementList(statements, code, start, end, options) {
  1986. let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
  1987. let nextNode = statements[0];
  1988. let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
  1989. if (nextNodeNeedsBoundaries) {
  1990. nextNodeStart =
  1991. start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start)) + 1;
  1992. }
  1993. for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
  1994. currentNode = nextNode;
  1995. currentNodeStart = nextNodeStart;
  1996. currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
  1997. nextNode = statements[nextIndex];
  1998. nextNodeNeedsBoundaries =
  1999. nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
  2000. if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
  2001. nextNodeStart =
  2002. currentNode.end +
  2003. findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start)) +
  2004. 1;
  2005. if (currentNode.included) {
  2006. currentNodeNeedsBoundaries
  2007. ? currentNode.render(code, options, {
  2008. end: nextNodeStart,
  2009. start: currentNodeStart
  2010. })
  2011. : currentNode.render(code, options);
  2012. }
  2013. else {
  2014. treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
  2015. }
  2016. }
  2017. else {
  2018. currentNode.render(code, options);
  2019. }
  2020. }
  2021. }
  2022. // This assumes that the first character is not part of the first node
  2023. function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
  2024. const splitUpNodes = [];
  2025. let node, nextNode, nextNodeStart, contentEnd, char;
  2026. let separator = start - 1;
  2027. for (let nextIndex = 0; nextIndex < nodes.length; nextIndex++) {
  2028. nextNode = nodes[nextIndex];
  2029. if (node !== undefined) {
  2030. separator =
  2031. node.end +
  2032. findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
  2033. }
  2034. nextNodeStart = contentEnd =
  2035. separator +
  2036. 2 +
  2037. findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start));
  2038. while (((char = code.original.charCodeAt(nextNodeStart)),
  2039. char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
  2040. nextNodeStart++;
  2041. if (node !== undefined) {
  2042. splitUpNodes.push({
  2043. contentEnd,
  2044. end: nextNodeStart,
  2045. node,
  2046. separator,
  2047. start
  2048. });
  2049. }
  2050. node = nextNode;
  2051. start = nextNodeStart;
  2052. }
  2053. splitUpNodes.push({
  2054. contentEnd: end,
  2055. end,
  2056. node: node,
  2057. separator: null,
  2058. start
  2059. });
  2060. return splitUpNodes;
  2061. }
  2062. // This assumes there are only white-space and comments between start and end
  2063. function removeLineBreaks(code, start, end) {
  2064. while (true) {
  2065. const lineBreakPos = findFirstLineBreakOutsideComment(code.original.slice(start, end));
  2066. if (lineBreakPos === -1) {
  2067. break;
  2068. }
  2069. start = start + lineBreakPos + 1;
  2070. code.remove(start - 1, start);
  2071. }
  2072. }
  2073. const chars$1 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
  2074. const base = 64;
  2075. function toBase64(num) {
  2076. let outStr = '';
  2077. do {
  2078. const curDigit = num % base;
  2079. num = Math.floor(num / base);
  2080. outStr = chars$1[curDigit] + outStr;
  2081. } while (num !== 0);
  2082. return outStr;
  2083. }
  2084. // Verified on IE 6/7 that these keywords can't be used for object properties without escaping:
  2085. // break case catch class const continue debugger default delete do
  2086. // else enum export extends false finally for function if import
  2087. // in instanceof new null return super switch this throw true
  2088. // try typeof var void while with
  2089. const RESERVED_NAMES = Object.assign(Object.create(null), {
  2090. await: true,
  2091. break: true,
  2092. case: true,
  2093. catch: true,
  2094. class: true,
  2095. const: true,
  2096. continue: true,
  2097. debugger: true,
  2098. default: true,
  2099. delete: true,
  2100. do: true,
  2101. else: true,
  2102. enum: true,
  2103. eval: true,
  2104. export: true,
  2105. extends: true,
  2106. false: true,
  2107. finally: true,
  2108. for: true,
  2109. function: true,
  2110. if: true,
  2111. implements: true,
  2112. import: true,
  2113. in: true,
  2114. instanceof: true,
  2115. interface: true,
  2116. let: true,
  2117. new: true,
  2118. null: true,
  2119. package: true,
  2120. private: true,
  2121. protected: true,
  2122. public: true,
  2123. return: true,
  2124. static: true,
  2125. super: true,
  2126. switch: true,
  2127. this: true,
  2128. throw: true,
  2129. true: true,
  2130. try: true,
  2131. typeof: true,
  2132. undefined: true,
  2133. var: true,
  2134. void: true,
  2135. while: true,
  2136. with: true,
  2137. yield: true
  2138. });
  2139. function getSafeName(baseName, usedNames) {
  2140. let safeName = baseName;
  2141. let count = 1;
  2142. while (usedNames.has(safeName) || RESERVED_NAMES[safeName]) {
  2143. safeName = `${baseName}$${toBase64(count++)}`;
  2144. }
  2145. usedNames.add(safeName);
  2146. return safeName;
  2147. }
  2148. const NO_ARGS = [];
  2149. function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
  2150. return Object.create(inheritedDescriptions, memberDescriptions);
  2151. }
  2152. const UnknownValue = Symbol('Unknown Value');
  2153. const UNKNOWN_EXPRESSION = {
  2154. deoptimizePath: () => { },
  2155. getLiteralValueAtPath: () => UnknownValue,
  2156. getReturnExpressionWhenCalledAtPath: () => UNKNOWN_EXPRESSION,
  2157. hasEffectsWhenAccessedAtPath: path => path.length > 0,
  2158. hasEffectsWhenAssignedAtPath: path => path.length > 0,
  2159. hasEffectsWhenCalledAtPath: () => true,
  2160. include: () => { },
  2161. includeCallArguments(context, args) {
  2162. for (const arg of args) {
  2163. arg.include(context, false);
  2164. }
  2165. },
  2166. included: true,
  2167. toString: () => '[[UNKNOWN]]'
  2168. };
  2169. const UNDEFINED_EXPRESSION = {
  2170. deoptimizePath: () => { },
  2171. getLiteralValueAtPath: () => undefined,
  2172. getReturnExpressionWhenCalledAtPath: () => UNKNOWN_EXPRESSION,
  2173. hasEffectsWhenAccessedAtPath: path => path.length > 0,
  2174. hasEffectsWhenAssignedAtPath: path => path.length > 0,
  2175. hasEffectsWhenCalledAtPath: () => true,
  2176. include: () => { },
  2177. includeCallArguments() { },
  2178. included: true,
  2179. toString: () => 'undefined'
  2180. };
  2181. const returnsUnknown = {
  2182. value: {
  2183. callsArgs: null,
  2184. mutatesSelf: false,
  2185. returns: null,
  2186. returnsPrimitive: UNKNOWN_EXPRESSION
  2187. }
  2188. };
  2189. const mutatesSelfReturnsUnknown = {
  2190. value: { returns: null, returnsPrimitive: UNKNOWN_EXPRESSION, callsArgs: null, mutatesSelf: true }
  2191. };
  2192. const callsArgReturnsUnknown = {
  2193. value: { returns: null, returnsPrimitive: UNKNOWN_EXPRESSION, callsArgs: [0], mutatesSelf: false }
  2194. };
  2195. class UnknownArrayExpression {
  2196. constructor() {
  2197. this.included = false;
  2198. }
  2199. deoptimizePath() { }
  2200. getLiteralValueAtPath() {
  2201. return UnknownValue;
  2202. }
  2203. getReturnExpressionWhenCalledAtPath(path) {
  2204. if (path.length === 1) {
  2205. return getMemberReturnExpressionWhenCalled(arrayMembers, path[0]);
  2206. }
  2207. return UNKNOWN_EXPRESSION;
  2208. }
  2209. hasEffectsWhenAccessedAtPath(path) {
  2210. return path.length > 1;
  2211. }
  2212. hasEffectsWhenAssignedAtPath(path) {
  2213. return path.length > 1;
  2214. }
  2215. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  2216. if (path.length === 1) {
  2217. return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, context);
  2218. }
  2219. return true;
  2220. }
  2221. include() {
  2222. this.included = true;
  2223. }
  2224. includeCallArguments(context, args) {
  2225. for (const arg of args) {
  2226. arg.include(context, false);
  2227. }
  2228. }
  2229. toString() {
  2230. return '[[UNKNOWN ARRAY]]';
  2231. }
  2232. }
  2233. const returnsArray = {
  2234. value: {
  2235. callsArgs: null,
  2236. mutatesSelf: false,
  2237. returns: UnknownArrayExpression,
  2238. returnsPrimitive: null
  2239. }
  2240. };
  2241. const mutatesSelfReturnsArray = {
  2242. value: {
  2243. callsArgs: null,
  2244. mutatesSelf: true,
  2245. returns: UnknownArrayExpression,
  2246. returnsPrimitive: null
  2247. }
  2248. };
  2249. const callsArgReturnsArray = {
  2250. value: {
  2251. callsArgs: [0],
  2252. mutatesSelf: false,
  2253. returns: UnknownArrayExpression,
  2254. returnsPrimitive: null
  2255. }
  2256. };
  2257. const callsArgMutatesSelfReturnsArray = {
  2258. value: {
  2259. callsArgs: [0],
  2260. mutatesSelf: true,
  2261. returns: UnknownArrayExpression,
  2262. returnsPrimitive: null
  2263. }
  2264. };
  2265. const UNKNOWN_LITERAL_BOOLEAN = {
  2266. deoptimizePath: () => { },
  2267. getLiteralValueAtPath: () => UnknownValue,
  2268. getReturnExpressionWhenCalledAtPath: path => {
  2269. if (path.length === 1) {
  2270. return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
  2271. }
  2272. return UNKNOWN_EXPRESSION;
  2273. },
  2274. hasEffectsWhenAccessedAtPath: path => path.length > 1,
  2275. hasEffectsWhenAssignedAtPath: path => path.length > 0,
  2276. hasEffectsWhenCalledAtPath: path => {
  2277. if (path.length === 1) {
  2278. const subPath = path[0];
  2279. return typeof subPath !== 'string' || !literalBooleanMembers[subPath];
  2280. }
  2281. return true;
  2282. },
  2283. include: () => { },
  2284. includeCallArguments(context, args) {
  2285. for (const arg of args) {
  2286. arg.include(context, false);
  2287. }
  2288. },
  2289. included: true,
  2290. toString: () => '[[UNKNOWN BOOLEAN]]'
  2291. };
  2292. const returnsBoolean = {
  2293. value: {
  2294. callsArgs: null,
  2295. mutatesSelf: false,
  2296. returns: null,
  2297. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  2298. }
  2299. };
  2300. const callsArgReturnsBoolean = {
  2301. value: {
  2302. callsArgs: [0],
  2303. mutatesSelf: false,
  2304. returns: null,
  2305. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  2306. }
  2307. };
  2308. const UNKNOWN_LITERAL_NUMBER = {
  2309. deoptimizePath: () => { },
  2310. getLiteralValueAtPath: () => UnknownValue,
  2311. getReturnExpressionWhenCalledAtPath: path => {
  2312. if (path.length === 1) {
  2313. return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
  2314. }
  2315. return UNKNOWN_EXPRESSION;
  2316. },
  2317. hasEffectsWhenAccessedAtPath: path => path.length > 1,
  2318. hasEffectsWhenAssignedAtPath: path => path.length > 0,
  2319. hasEffectsWhenCalledAtPath: path => {
  2320. if (path.length === 1) {
  2321. const subPath = path[0];
  2322. return typeof subPath !== 'string' || !literalNumberMembers[subPath];
  2323. }
  2324. return true;
  2325. },
  2326. include: () => { },
  2327. includeCallArguments(context, args) {
  2328. for (const arg of args) {
  2329. arg.include(context, false);
  2330. }
  2331. },
  2332. included: true,
  2333. toString: () => '[[UNKNOWN NUMBER]]'
  2334. };
  2335. const returnsNumber = {
  2336. value: {
  2337. callsArgs: null,
  2338. mutatesSelf: false,
  2339. returns: null,
  2340. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  2341. }
  2342. };
  2343. const mutatesSelfReturnsNumber = {
  2344. value: {
  2345. callsArgs: null,
  2346. mutatesSelf: true,
  2347. returns: null,
  2348. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  2349. }
  2350. };
  2351. const callsArgReturnsNumber = {
  2352. value: {
  2353. callsArgs: [0],
  2354. mutatesSelf: false,
  2355. returns: null,
  2356. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  2357. }
  2358. };
  2359. const UNKNOWN_LITERAL_STRING = {
  2360. deoptimizePath: () => { },
  2361. getLiteralValueAtPath: () => UnknownValue,
  2362. getReturnExpressionWhenCalledAtPath: path => {
  2363. if (path.length === 1) {
  2364. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  2365. }
  2366. return UNKNOWN_EXPRESSION;
  2367. },
  2368. hasEffectsWhenAccessedAtPath: path => path.length > 1,
  2369. hasEffectsWhenAssignedAtPath: path => path.length > 0,
  2370. hasEffectsWhenCalledAtPath: (path, callOptions, context) => {
  2371. if (path.length === 1) {
  2372. return hasMemberEffectWhenCalled(literalStringMembers, path[0], true, callOptions, context);
  2373. }
  2374. return true;
  2375. },
  2376. include: () => { },
  2377. includeCallArguments(context, args) {
  2378. for (const arg of args) {
  2379. arg.include(context, false);
  2380. }
  2381. },
  2382. included: true,
  2383. toString: () => '[[UNKNOWN STRING]]'
  2384. };
  2385. const returnsString = {
  2386. value: {
  2387. callsArgs: null,
  2388. mutatesSelf: false,
  2389. returns: null,
  2390. returnsPrimitive: UNKNOWN_LITERAL_STRING
  2391. }
  2392. };
  2393. class UnknownObjectExpression {
  2394. constructor() {
  2395. this.included = false;
  2396. }
  2397. deoptimizePath() { }
  2398. getLiteralValueAtPath() {
  2399. return UnknownValue;
  2400. }
  2401. getReturnExpressionWhenCalledAtPath(path) {
  2402. if (path.length === 1) {
  2403. return getMemberReturnExpressionWhenCalled(objectMembers, path[0]);
  2404. }
  2405. return UNKNOWN_EXPRESSION;
  2406. }
  2407. hasEffectsWhenAccessedAtPath(path) {
  2408. return path.length > 1;
  2409. }
  2410. hasEffectsWhenAssignedAtPath(path) {
  2411. return path.length > 1;
  2412. }
  2413. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  2414. if (path.length === 1) {
  2415. return hasMemberEffectWhenCalled(objectMembers, path[0], this.included, callOptions, context);
  2416. }
  2417. return true;
  2418. }
  2419. include() {
  2420. this.included = true;
  2421. }
  2422. includeCallArguments(context, args) {
  2423. for (const arg of args) {
  2424. arg.include(context, false);
  2425. }
  2426. }
  2427. toString() {
  2428. return '[[UNKNOWN OBJECT]]';
  2429. }
  2430. }
  2431. const objectMembers = assembleMemberDescriptions({
  2432. hasOwnProperty: returnsBoolean,
  2433. isPrototypeOf: returnsBoolean,
  2434. propertyIsEnumerable: returnsBoolean,
  2435. toLocaleString: returnsString,
  2436. toString: returnsString,
  2437. valueOf: returnsUnknown
  2438. });
  2439. const arrayMembers = assembleMemberDescriptions({
  2440. concat: returnsArray,
  2441. copyWithin: mutatesSelfReturnsArray,
  2442. every: callsArgReturnsBoolean,
  2443. fill: mutatesSelfReturnsArray,
  2444. filter: callsArgReturnsArray,
  2445. find: callsArgReturnsUnknown,
  2446. findIndex: callsArgReturnsNumber,
  2447. forEach: callsArgReturnsUnknown,
  2448. includes: returnsBoolean,
  2449. indexOf: returnsNumber,
  2450. join: returnsString,
  2451. lastIndexOf: returnsNumber,
  2452. map: callsArgReturnsArray,
  2453. pop: mutatesSelfReturnsUnknown,
  2454. push: mutatesSelfReturnsNumber,
  2455. reduce: callsArgReturnsUnknown,
  2456. reduceRight: callsArgReturnsUnknown,
  2457. reverse: mutatesSelfReturnsArray,
  2458. shift: mutatesSelfReturnsUnknown,
  2459. slice: returnsArray,
  2460. some: callsArgReturnsBoolean,
  2461. sort: callsArgMutatesSelfReturnsArray,
  2462. splice: mutatesSelfReturnsArray,
  2463. unshift: mutatesSelfReturnsNumber
  2464. }, objectMembers);
  2465. const literalBooleanMembers = assembleMemberDescriptions({
  2466. valueOf: returnsBoolean
  2467. }, objectMembers);
  2468. const literalNumberMembers = assembleMemberDescriptions({
  2469. toExponential: returnsString,
  2470. toFixed: returnsString,
  2471. toLocaleString: returnsString,
  2472. toPrecision: returnsString,
  2473. valueOf: returnsNumber
  2474. }, objectMembers);
  2475. const literalStringMembers = assembleMemberDescriptions({
  2476. charAt: returnsString,
  2477. charCodeAt: returnsNumber,
  2478. codePointAt: returnsNumber,
  2479. concat: returnsString,
  2480. endsWith: returnsBoolean,
  2481. includes: returnsBoolean,
  2482. indexOf: returnsNumber,
  2483. lastIndexOf: returnsNumber,
  2484. localeCompare: returnsNumber,
  2485. match: returnsBoolean,
  2486. normalize: returnsString,
  2487. padEnd: returnsString,
  2488. padStart: returnsString,
  2489. repeat: returnsString,
  2490. replace: {
  2491. value: {
  2492. callsArgs: [1],
  2493. mutatesSelf: false,
  2494. returns: null,
  2495. returnsPrimitive: UNKNOWN_LITERAL_STRING
  2496. }
  2497. },
  2498. search: returnsNumber,
  2499. slice: returnsString,
  2500. split: returnsArray,
  2501. startsWith: returnsBoolean,
  2502. substr: returnsString,
  2503. substring: returnsString,
  2504. toLocaleLowerCase: returnsString,
  2505. toLocaleUpperCase: returnsString,
  2506. toLowerCase: returnsString,
  2507. toUpperCase: returnsString,
  2508. trim: returnsString,
  2509. valueOf: returnsString
  2510. }, objectMembers);
  2511. function getLiteralMembersForValue(value) {
  2512. switch (typeof value) {
  2513. case 'boolean':
  2514. return literalBooleanMembers;
  2515. case 'number':
  2516. return literalNumberMembers;
  2517. case 'string':
  2518. return literalStringMembers;
  2519. default:
  2520. return Object.create(null);
  2521. }
  2522. }
  2523. function hasMemberEffectWhenCalled(members, memberName, parentIncluded, callOptions, context) {
  2524. if (typeof memberName !== 'string' ||
  2525. !members[memberName] ||
  2526. (members[memberName].mutatesSelf && parentIncluded))
  2527. return true;
  2528. if (!members[memberName].callsArgs)
  2529. return false;
  2530. for (const argIndex of members[memberName].callsArgs) {
  2531. if (callOptions.args[argIndex] &&
  2532. callOptions.args[argIndex].hasEffectsWhenCalledAtPath(EMPTY_PATH, {
  2533. args: NO_ARGS,
  2534. withNew: false
  2535. }, context))
  2536. return true;
  2537. }
  2538. return false;
  2539. }
  2540. function getMemberReturnExpressionWhenCalled(members, memberName) {
  2541. if (typeof memberName !== 'string' || !members[memberName])
  2542. return UNKNOWN_EXPRESSION;
  2543. return members[memberName].returnsPrimitive !== null
  2544. ? members[memberName].returnsPrimitive
  2545. : new members[memberName].returns();
  2546. }
  2547. class Variable {
  2548. constructor(name) {
  2549. this.alwaysRendered = false;
  2550. this.exportName = null;
  2551. this.included = false;
  2552. this.isId = false;
  2553. this.isReassigned = false;
  2554. this.renderBaseName = null;
  2555. this.renderName = null;
  2556. this.safeExportName = null;
  2557. this.name = name;
  2558. }
  2559. /**
  2560. * Binds identifiers that reference this variable to this variable.
  2561. * Necessary to be able to change variable names.
  2562. */
  2563. addReference(_identifier) { }
  2564. deoptimizePath(_path) { }
  2565. getBaseVariableName() {
  2566. return this.renderBaseName || this.renderName || this.name;
  2567. }
  2568. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  2569. return UnknownValue;
  2570. }
  2571. getName() {
  2572. const name = this.renderName || this.name;
  2573. return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name;
  2574. }
  2575. getReturnExpressionWhenCalledAtPath(_path, _recursionTracker, _origin) {
  2576. return UNKNOWN_EXPRESSION;
  2577. }
  2578. hasEffectsWhenAccessedAtPath(path, _context) {
  2579. return path.length > 0;
  2580. }
  2581. hasEffectsWhenAssignedAtPath(_path, _context) {
  2582. return true;
  2583. }
  2584. hasEffectsWhenCalledAtPath(_path, _callOptions, _context) {
  2585. return true;
  2586. }
  2587. /**
  2588. * Marks this variable as being part of the bundle, which is usually the case when one of
  2589. * its identifiers becomes part of the bundle. Returns true if it has not been included
  2590. * previously.
  2591. * Once a variable is included, it should take care all its declarations are included.
  2592. */
  2593. include(_context) {
  2594. this.included = true;
  2595. }
  2596. includeCallArguments(context, args) {
  2597. for (const arg of args) {
  2598. arg.include(context, false);
  2599. }
  2600. }
  2601. markCalledFromTryStatement() { }
  2602. setRenderNames(baseName, name) {
  2603. this.renderBaseName = baseName;
  2604. this.renderName = name;
  2605. }
  2606. setSafeName(name) {
  2607. this.renderName = name;
  2608. }
  2609. toString() {
  2610. return this.name;
  2611. }
  2612. }
  2613. const getPropertyAccess = (name) => {
  2614. return /^(?!\d)[\w$]+$/.test(name) ? `.${name}` : `[${JSON.stringify(name)}]`;
  2615. };
  2616. class ExternalVariable extends Variable {
  2617. constructor(module, name) {
  2618. super(name);
  2619. this.module = module;
  2620. this.isNamespace = name === '*';
  2621. this.referenced = false;
  2622. }
  2623. addReference(identifier) {
  2624. this.referenced = true;
  2625. if (this.name === 'default' || this.name === '*') {
  2626. this.module.suggestName(identifier.name);
  2627. }
  2628. }
  2629. include() {
  2630. if (!this.included) {
  2631. this.included = true;
  2632. this.module.used = true;
  2633. }
  2634. }
  2635. }
  2636. const reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public'.split(' ');
  2637. const builtins = '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(' ');
  2638. const blacklisted = new Set(reservedWords.concat(builtins));
  2639. const illegalCharacters = /[^$_a-zA-Z0-9]/g;
  2640. const startsWithDigit = (str) => /\d/.test(str[0]);
  2641. function isLegal(str) {
  2642. if (startsWithDigit(str) || blacklisted.has(str)) {
  2643. return false;
  2644. }
  2645. return !illegalCharacters.test(str);
  2646. }
  2647. function makeLegal(str) {
  2648. str = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(illegalCharacters, '_');
  2649. if (startsWithDigit(str) || blacklisted.has(str))
  2650. str = `_${str}`;
  2651. return str || '_';
  2652. }
  2653. const absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
  2654. const relativePath = /^\.?\.\//;
  2655. function isAbsolute(path) {
  2656. return absolutePath.test(path);
  2657. }
  2658. function isRelative(path) {
  2659. return relativePath.test(path);
  2660. }
  2661. function normalize(path) {
  2662. if (path.indexOf('\\') == -1)
  2663. return path;
  2664. return path.replace(/\\/g, '/');
  2665. }
  2666. class ExternalModule {
  2667. constructor(graph, id, moduleSideEffects) {
  2668. this.exportsNames = false;
  2669. this.exportsNamespace = false;
  2670. this.mostCommonSuggestion = 0;
  2671. this.reexported = false;
  2672. this.renderPath = undefined;
  2673. this.renormalizeRenderPath = false;
  2674. this.used = false;
  2675. this.graph = graph;
  2676. this.id = id;
  2677. this.execIndex = Infinity;
  2678. this.moduleSideEffects = moduleSideEffects;
  2679. const parts = id.split(/[\\/]/);
  2680. this.variableName = makeLegal(parts.pop());
  2681. this.nameSuggestions = Object.create(null);
  2682. this.declarations = Object.create(null);
  2683. this.exportedVariables = new Map();
  2684. }
  2685. getVariableForExportName(name) {
  2686. if (name === '*') {
  2687. this.exportsNamespace = true;
  2688. }
  2689. else if (name !== 'default') {
  2690. this.exportsNames = true;
  2691. }
  2692. let declaration = this.declarations[name];
  2693. if (declaration)
  2694. return declaration;
  2695. this.declarations[name] = declaration = new ExternalVariable(this, name);
  2696. this.exportedVariables.set(declaration, name);
  2697. return declaration;
  2698. }
  2699. setRenderPath(options, inputBase) {
  2700. this.renderPath = '';
  2701. if (options.paths) {
  2702. this.renderPath =
  2703. typeof options.paths === 'function' ? options.paths(this.id) : options.paths[this.id];
  2704. }
  2705. if (!this.renderPath) {
  2706. if (!isAbsolute(this.id)) {
  2707. this.renderPath = this.id;
  2708. }
  2709. else {
  2710. this.renderPath = normalize(path.relative(inputBase, this.id));
  2711. this.renormalizeRenderPath = true;
  2712. }
  2713. }
  2714. return this.renderPath;
  2715. }
  2716. suggestName(name) {
  2717. if (!this.nameSuggestions[name])
  2718. this.nameSuggestions[name] = 0;
  2719. this.nameSuggestions[name] += 1;
  2720. if (this.nameSuggestions[name] > this.mostCommonSuggestion) {
  2721. this.mostCommonSuggestion = this.nameSuggestions[name];
  2722. this.variableName = name;
  2723. }
  2724. }
  2725. warnUnusedImports() {
  2726. const unused = Object.keys(this.declarations).filter(name => {
  2727. if (name === '*')
  2728. return false;
  2729. const declaration = this.declarations[name];
  2730. return !declaration.included && !this.reexported && !declaration.referenced;
  2731. });
  2732. if (unused.length === 0)
  2733. return;
  2734. const names = unused.length === 1
  2735. ? `'${unused[0]}' is`
  2736. : `${unused
  2737. .slice(0, -1)
  2738. .map(name => `'${name}'`)
  2739. .join(', ')} and '${unused.slice(-1)}' are`;
  2740. this.graph.warn({
  2741. code: 'UNUSED_EXTERNAL_IMPORT',
  2742. message: `${names} imported from external module '${this.id}' but never used`,
  2743. names: unused,
  2744. source: this.id
  2745. });
  2746. }
  2747. }
  2748. function markModuleAndImpureDependenciesAsExecuted(baseModule) {
  2749. baseModule.isExecuted = true;
  2750. const modules = [baseModule];
  2751. const visitedModules = new Set();
  2752. for (const module of modules) {
  2753. for (const dependency of module.dependencies) {
  2754. if (!(dependency instanceof ExternalModule) &&
  2755. !dependency.isExecuted &&
  2756. dependency.moduleSideEffects &&
  2757. !visitedModules.has(dependency.id)) {
  2758. dependency.isExecuted = true;
  2759. visitedModules.add(dependency.id);
  2760. modules.push(dependency);
  2761. }
  2762. }
  2763. }
  2764. }
  2765. // To avoid infinite recursions
  2766. const MAX_PATH_DEPTH = 7;
  2767. class LocalVariable extends Variable {
  2768. constructor(name, declarator, init, context) {
  2769. super(name);
  2770. this.additionalInitializers = null;
  2771. this.calledFromTryStatement = false;
  2772. this.expressionsToBeDeoptimized = [];
  2773. this.declarations = declarator ? [declarator] : [];
  2774. this.init = init;
  2775. this.deoptimizationTracker = context.deoptimizationTracker;
  2776. this.module = context.module;
  2777. }
  2778. addDeclaration(identifier, init) {
  2779. this.declarations.push(identifier);
  2780. if (this.additionalInitializers === null) {
  2781. this.additionalInitializers = this.init === null ? [] : [this.init];
  2782. this.init = UNKNOWN_EXPRESSION;
  2783. this.isReassigned = true;
  2784. }
  2785. if (init !== null) {
  2786. this.additionalInitializers.push(init);
  2787. }
  2788. }
  2789. consolidateInitializers() {
  2790. if (this.additionalInitializers !== null) {
  2791. for (const initializer of this.additionalInitializers) {
  2792. initializer.deoptimizePath(UNKNOWN_PATH);
  2793. }
  2794. this.additionalInitializers = null;
  2795. }
  2796. }
  2797. deoptimizePath(path) {
  2798. if (path.length > MAX_PATH_DEPTH || this.isReassigned)
  2799. return;
  2800. const trackedEntities = this.deoptimizationTracker.getEntities(path);
  2801. if (trackedEntities.has(this))
  2802. return;
  2803. trackedEntities.add(this);
  2804. if (path.length === 0) {
  2805. if (!this.isReassigned) {
  2806. this.isReassigned = true;
  2807. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  2808. this.expressionsToBeDeoptimized = [];
  2809. for (const expression of expressionsToBeDeoptimized) {
  2810. expression.deoptimizeCache();
  2811. }
  2812. if (this.init) {
  2813. this.init.deoptimizePath(UNKNOWN_PATH);
  2814. }
  2815. }
  2816. }
  2817. else if (this.init) {
  2818. this.init.deoptimizePath(path);
  2819. }
  2820. }
  2821. getLiteralValueAtPath(path, recursionTracker, origin) {
  2822. if (this.isReassigned || !this.init || path.length > MAX_PATH_DEPTH) {
  2823. return UnknownValue;
  2824. }
  2825. const trackedEntities = recursionTracker.getEntities(path);
  2826. if (trackedEntities.has(this.init)) {
  2827. return UnknownValue;
  2828. }
  2829. this.expressionsToBeDeoptimized.push(origin);
  2830. trackedEntities.add(this.init);
  2831. const value = this.init.getLiteralValueAtPath(path, recursionTracker, origin);
  2832. trackedEntities.delete(this.init);
  2833. return value;
  2834. }
  2835. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  2836. if (this.isReassigned || !this.init || path.length > MAX_PATH_DEPTH) {
  2837. return UNKNOWN_EXPRESSION;
  2838. }
  2839. const trackedEntities = recursionTracker.getEntities(path);
  2840. if (trackedEntities.has(this.init)) {
  2841. return UNKNOWN_EXPRESSION;
  2842. }
  2843. this.expressionsToBeDeoptimized.push(origin);
  2844. trackedEntities.add(this.init);
  2845. const value = this.init.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  2846. trackedEntities.delete(this.init);
  2847. return value;
  2848. }
  2849. hasEffectsWhenAccessedAtPath(path, context) {
  2850. if (path.length === 0)
  2851. return false;
  2852. if (this.isReassigned || path.length > MAX_PATH_DEPTH)
  2853. return true;
  2854. const trackedExpressions = context.accessed.getEntities(path);
  2855. if (trackedExpressions.has(this))
  2856. return false;
  2857. trackedExpressions.add(this);
  2858. return (this.init && this.init.hasEffectsWhenAccessedAtPath(path, context));
  2859. }
  2860. hasEffectsWhenAssignedAtPath(path, context) {
  2861. if (this.included || path.length > MAX_PATH_DEPTH)
  2862. return true;
  2863. if (path.length === 0)
  2864. return false;
  2865. if (this.isReassigned)
  2866. return true;
  2867. const trackedExpressions = context.assigned.getEntities(path);
  2868. if (trackedExpressions.has(this))
  2869. return false;
  2870. trackedExpressions.add(this);
  2871. return (this.init && this.init.hasEffectsWhenAssignedAtPath(path, context));
  2872. }
  2873. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  2874. if (path.length > MAX_PATH_DEPTH || this.isReassigned)
  2875. return true;
  2876. const trackedExpressions = (callOptions.withNew
  2877. ? context.instantiated
  2878. : context.called).getEntities(path);
  2879. if (trackedExpressions.has(this))
  2880. return false;
  2881. trackedExpressions.add(this);
  2882. return (this.init && this.init.hasEffectsWhenCalledAtPath(path, callOptions, context));
  2883. }
  2884. include(context) {
  2885. if (!this.included) {
  2886. this.included = true;
  2887. if (!this.module.isExecuted) {
  2888. markModuleAndImpureDependenciesAsExecuted(this.module);
  2889. }
  2890. for (const declaration of this.declarations) {
  2891. // If node is a default export, it can save a tree-shaking run to include the full declaration now
  2892. if (!declaration.included)
  2893. declaration.include(context, false);
  2894. let node = declaration.parent;
  2895. while (!node.included) {
  2896. // We do not want to properly include parents in case they are part of a dead branch
  2897. // in which case .include() might pull in more dead code
  2898. node.included = true;
  2899. if (node.type === Program)
  2900. break;
  2901. node = node.parent;
  2902. }
  2903. }
  2904. }
  2905. }
  2906. includeCallArguments(context, args) {
  2907. if (this.isReassigned) {
  2908. for (const arg of args) {
  2909. arg.include(context, false);
  2910. }
  2911. }
  2912. else if (this.init) {
  2913. this.init.includeCallArguments(context, args);
  2914. }
  2915. }
  2916. markCalledFromTryStatement() {
  2917. this.calledFromTryStatement = true;
  2918. }
  2919. }
  2920. class Scope {
  2921. constructor() {
  2922. this.children = [];
  2923. this.variables = new Map();
  2924. }
  2925. addDeclaration(identifier, context, init = null, _isHoisted) {
  2926. const name = identifier.name;
  2927. let variable = this.variables.get(name);
  2928. if (variable) {
  2929. variable.addDeclaration(identifier, init);
  2930. }
  2931. else {
  2932. variable = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
  2933. this.variables.set(name, variable);
  2934. }
  2935. return variable;
  2936. }
  2937. contains(name) {
  2938. return this.variables.has(name);
  2939. }
  2940. findVariable(_name) {
  2941. throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
  2942. }
  2943. }
  2944. class ChildScope extends Scope {
  2945. constructor(parent) {
  2946. super();
  2947. this.accessedOutsideVariables = new Map();
  2948. this.parent = parent;
  2949. parent.children.push(this);
  2950. }
  2951. addAccessedDynamicImport(importExpression) {
  2952. (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
  2953. if (this.parent instanceof ChildScope) {
  2954. this.parent.addAccessedDynamicImport(importExpression);
  2955. }
  2956. }
  2957. addAccessedGlobalsByFormat(globalsByFormat) {
  2958. const accessedGlobalVariablesByFormat = this.accessedGlobalVariablesByFormat || (this.accessedGlobalVariablesByFormat = new Map());
  2959. for (const format of Object.keys(globalsByFormat)) {
  2960. let accessedGlobalVariables = accessedGlobalVariablesByFormat.get(format);
  2961. if (!accessedGlobalVariables) {
  2962. accessedGlobalVariables = new Set();
  2963. accessedGlobalVariablesByFormat.set(format, accessedGlobalVariables);
  2964. }
  2965. for (const name of globalsByFormat[format]) {
  2966. accessedGlobalVariables.add(name);
  2967. }
  2968. }
  2969. if (this.parent instanceof ChildScope) {
  2970. this.parent.addAccessedGlobalsByFormat(globalsByFormat);
  2971. }
  2972. }
  2973. addNamespaceMemberAccess(name, variable) {
  2974. this.accessedOutsideVariables.set(name, variable);
  2975. this.parent.addNamespaceMemberAccess(name, variable);
  2976. }
  2977. addReturnExpression(expression) {
  2978. this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
  2979. }
  2980. addUsedOutsideNames(usedNames, format) {
  2981. for (const variable of this.accessedOutsideVariables.values()) {
  2982. if (variable.included) {
  2983. usedNames.add(variable.getBaseVariableName());
  2984. if (variable.exportName && format === 'system') {
  2985. usedNames.add('exports');
  2986. }
  2987. }
  2988. }
  2989. const accessedGlobalVariables = this.accessedGlobalVariablesByFormat && this.accessedGlobalVariablesByFormat.get(format);
  2990. if (accessedGlobalVariables) {
  2991. for (const name of accessedGlobalVariables) {
  2992. usedNames.add(name);
  2993. }
  2994. }
  2995. }
  2996. contains(name) {
  2997. return this.variables.has(name) || this.parent.contains(name);
  2998. }
  2999. deconflict(format) {
  3000. const usedNames = new Set();
  3001. this.addUsedOutsideNames(usedNames, format);
  3002. if (this.accessedDynamicImports) {
  3003. for (const importExpression of this.accessedDynamicImports) {
  3004. if (importExpression.inlineNamespace) {
  3005. usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
  3006. }
  3007. }
  3008. }
  3009. for (const [name, variable] of this.variables) {
  3010. if (variable.included || variable.alwaysRendered) {
  3011. variable.setSafeName(getSafeName(name, usedNames));
  3012. }
  3013. }
  3014. for (const scope of this.children) {
  3015. scope.deconflict(format);
  3016. }
  3017. }
  3018. findLexicalBoundary() {
  3019. return this.parent.findLexicalBoundary();
  3020. }
  3021. findVariable(name) {
  3022. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  3023. if (knownVariable) {
  3024. return knownVariable;
  3025. }
  3026. const variable = this.parent.findVariable(name);
  3027. this.accessedOutsideVariables.set(name, variable);
  3028. return variable;
  3029. }
  3030. }
  3031. function getLocator$1(source, options) {
  3032. if (options === void 0) {
  3033. options = {};
  3034. }
  3035. var offsetLine = options.offsetLine || 0;
  3036. var offsetColumn = options.offsetColumn || 0;
  3037. var originalLines = source.split('\n');
  3038. var start = 0;
  3039. var lineRanges = originalLines.map(function (line, i) {
  3040. var end = start + line.length + 1;
  3041. var range = { start: start, end: end, line: i };
  3042. start = end;
  3043. return range;
  3044. });
  3045. var i = 0;
  3046. function rangeContains(range, index) {
  3047. return range.start <= index && index < range.end;
  3048. }
  3049. function getLocation(range, index) {
  3050. return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
  3051. }
  3052. function locate(search, startIndex) {
  3053. if (typeof search === 'string') {
  3054. search = source.indexOf(search, startIndex || 0);
  3055. }
  3056. var range = lineRanges[i];
  3057. var d = search >= range.end ? 1 : -1;
  3058. while (range) {
  3059. if (rangeContains(range, search))
  3060. return getLocation(range, search);
  3061. i += d;
  3062. range = lineRanges[i];
  3063. }
  3064. }
  3065. return locate;
  3066. }
  3067. function locate(source, search, options) {
  3068. if (typeof options === 'number') {
  3069. throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
  3070. }
  3071. return getLocator$1(source, options)(search, options && options.startIndex);
  3072. }
  3073. const keys = {
  3074. Literal: [],
  3075. Program: ['body']
  3076. };
  3077. function getAndCreateKeys(esTreeNode) {
  3078. keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object');
  3079. return keys[esTreeNode.type];
  3080. }
  3081. const INCLUDE_PARAMETERS = 'variables';
  3082. class NodeBase {
  3083. constructor(esTreeNode, parent, parentScope) {
  3084. this.included = false;
  3085. this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
  3086. this.parent = parent;
  3087. this.context = parent.context;
  3088. this.createScope(parentScope);
  3089. this.parseNode(esTreeNode);
  3090. this.initialise();
  3091. this.context.magicString.addSourcemapLocation(this.start);
  3092. this.context.magicString.addSourcemapLocation(this.end);
  3093. }
  3094. /**
  3095. * Override this to bind assignments to variables and do any initialisations that
  3096. * require the scopes to be populated with variables.
  3097. */
  3098. bind() {
  3099. for (const key of this.keys) {
  3100. const value = this[key];
  3101. if (value === null || key === 'annotations')
  3102. continue;
  3103. if (Array.isArray(value)) {
  3104. for (const child of value) {
  3105. if (child !== null)
  3106. child.bind();
  3107. }
  3108. }
  3109. else {
  3110. value.bind();
  3111. }
  3112. }
  3113. }
  3114. /**
  3115. * Override if this node should receive a different scope than the parent scope.
  3116. */
  3117. createScope(parentScope) {
  3118. this.scope = parentScope;
  3119. }
  3120. declare(_kind, _init) {
  3121. return [];
  3122. }
  3123. deoptimizePath(_path) { }
  3124. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  3125. return UnknownValue;
  3126. }
  3127. getReturnExpressionWhenCalledAtPath(_path, _recursionTracker, _origin) {
  3128. return UNKNOWN_EXPRESSION;
  3129. }
  3130. hasEffects(context) {
  3131. for (const key of this.keys) {
  3132. const value = this[key];
  3133. if (value === null || key === 'annotations')
  3134. continue;
  3135. if (Array.isArray(value)) {
  3136. for (const child of value) {
  3137. if (child !== null && child.hasEffects(context))
  3138. return true;
  3139. }
  3140. }
  3141. else if (value.hasEffects(context))
  3142. return true;
  3143. }
  3144. return false;
  3145. }
  3146. hasEffectsWhenAccessedAtPath(path, _context) {
  3147. return path.length > 0;
  3148. }
  3149. hasEffectsWhenAssignedAtPath(_path, _context) {
  3150. return true;
  3151. }
  3152. hasEffectsWhenCalledAtPath(_path, _callOptions, _context) {
  3153. return true;
  3154. }
  3155. include(context, includeChildrenRecursively) {
  3156. this.included = true;
  3157. for (const key of this.keys) {
  3158. const value = this[key];
  3159. if (value === null || key === 'annotations')
  3160. continue;
  3161. if (Array.isArray(value)) {
  3162. for (const child of value) {
  3163. if (child !== null)
  3164. child.include(context, includeChildrenRecursively);
  3165. }
  3166. }
  3167. else {
  3168. value.include(context, includeChildrenRecursively);
  3169. }
  3170. }
  3171. }
  3172. includeCallArguments(context, args) {
  3173. for (const arg of args) {
  3174. arg.include(context, false);
  3175. }
  3176. }
  3177. includeWithAllDeclaredVariables(includeChildrenRecursively, context) {
  3178. this.include(context, includeChildrenRecursively);
  3179. }
  3180. /**
  3181. * Override to perform special initialisation steps after the scope is initialised
  3182. */
  3183. initialise() { }
  3184. insertSemicolon(code) {
  3185. if (code.original[this.end - 1] !== ';') {
  3186. code.appendLeft(this.end, ';');
  3187. }
  3188. }
  3189. locate() {
  3190. // useful for debugging
  3191. const location = locate(this.context.code, this.start, { offsetLine: 1 });
  3192. location.file = this.context.fileName;
  3193. location.toString = () => JSON.stringify(location);
  3194. return location;
  3195. }
  3196. parseNode(esTreeNode) {
  3197. for (const key of Object.keys(esTreeNode)) {
  3198. // That way, we can override this function to add custom initialisation and then call super.parseNode
  3199. if (this.hasOwnProperty(key))
  3200. continue;
  3201. const value = esTreeNode[key];
  3202. if (typeof value !== 'object' || value === null || key === 'annotations') {
  3203. this[key] = value;
  3204. }
  3205. else if (Array.isArray(value)) {
  3206. this[key] = [];
  3207. for (const child of value) {
  3208. this[key].push(child === null
  3209. ? null
  3210. : new (this.context.nodeConstructors[child.type] ||
  3211. this.context.nodeConstructors.UnknownNode)(child, this, this.scope));
  3212. }
  3213. }
  3214. else {
  3215. this[key] = new (this.context.nodeConstructors[value.type] ||
  3216. this.context.nodeConstructors.UnknownNode)(value, this, this.scope);
  3217. }
  3218. }
  3219. }
  3220. render(code, options) {
  3221. for (const key of this.keys) {
  3222. const value = this[key];
  3223. if (value === null || key === 'annotations')
  3224. continue;
  3225. if (Array.isArray(value)) {
  3226. for (const child of value) {
  3227. if (child !== null)
  3228. child.render(code, options);
  3229. }
  3230. }
  3231. else {
  3232. value.render(code, options);
  3233. }
  3234. }
  3235. }
  3236. shouldBeIncluded(context) {
  3237. return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
  3238. }
  3239. toString() {
  3240. return this.context.code.slice(this.start, this.end);
  3241. }
  3242. }
  3243. class ClassNode extends NodeBase {
  3244. createScope(parentScope) {
  3245. this.scope = new ChildScope(parentScope);
  3246. }
  3247. hasEffectsWhenAccessedAtPath(path) {
  3248. return path.length > 1;
  3249. }
  3250. hasEffectsWhenAssignedAtPath(path) {
  3251. return path.length > 1;
  3252. }
  3253. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  3254. if (!callOptions.withNew)
  3255. return true;
  3256. return (this.body.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
  3257. (this.superClass !== null &&
  3258. this.superClass.hasEffectsWhenCalledAtPath(path, callOptions, context)));
  3259. }
  3260. initialise() {
  3261. if (this.id !== null) {
  3262. this.id.declare('class', this);
  3263. }
  3264. }
  3265. }
  3266. class ClassDeclaration extends ClassNode {
  3267. initialise() {
  3268. super.initialise();
  3269. if (this.id !== null) {
  3270. this.id.variable.isId = true;
  3271. }
  3272. }
  3273. parseNode(esTreeNode) {
  3274. if (esTreeNode.id !== null) {
  3275. this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope
  3276. .parent);
  3277. }
  3278. super.parseNode(esTreeNode);
  3279. }
  3280. render(code, options) {
  3281. if (options.format === 'system' && this.id && this.id.variable.exportName) {
  3282. code.appendLeft(this.end, ` exports('${this.id.variable.exportName}', ${this.id.variable.getName()});`);
  3283. }
  3284. super.render(code, options);
  3285. }
  3286. }
  3287. class ArgumentsVariable extends LocalVariable {
  3288. constructor(context) {
  3289. super('arguments', null, UNKNOWN_EXPRESSION, context);
  3290. }
  3291. hasEffectsWhenAccessedAtPath(path) {
  3292. return path.length > 1;
  3293. }
  3294. hasEffectsWhenAssignedAtPath() {
  3295. return true;
  3296. }
  3297. hasEffectsWhenCalledAtPath() {
  3298. return true;
  3299. }
  3300. }
  3301. class ThisVariable extends LocalVariable {
  3302. constructor(context) {
  3303. super('this', null, null, context);
  3304. }
  3305. getLiteralValueAtPath() {
  3306. return UnknownValue;
  3307. }
  3308. hasEffectsWhenAccessedAtPath(path, context) {
  3309. return (this.getInit(context).hasEffectsWhenAccessedAtPath(path, context) ||
  3310. super.hasEffectsWhenAccessedAtPath(path, context));
  3311. }
  3312. hasEffectsWhenAssignedAtPath(path, context) {
  3313. return (this.getInit(context).hasEffectsWhenAssignedAtPath(path, context) ||
  3314. super.hasEffectsWhenAssignedAtPath(path, context));
  3315. }
  3316. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  3317. return (this.getInit(context).hasEffectsWhenCalledAtPath(path, callOptions, context) ||
  3318. super.hasEffectsWhenCalledAtPath(path, callOptions, context));
  3319. }
  3320. getInit(context) {
  3321. return context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION;
  3322. }
  3323. }
  3324. class ParameterScope extends ChildScope {
  3325. constructor(parent, context) {
  3326. super(parent);
  3327. this.parameters = [];
  3328. this.hasRest = false;
  3329. this.context = context;
  3330. this.hoistedBodyVarScope = new ChildScope(this);
  3331. }
  3332. /**
  3333. * Adds a parameter to this scope. Parameters must be added in the correct
  3334. * order, e.g. from left to right.
  3335. */
  3336. addParameterDeclaration(identifier) {
  3337. const name = identifier.name;
  3338. let variable = this.hoistedBodyVarScope.variables.get(name);
  3339. if (variable) {
  3340. variable.addDeclaration(identifier, null);
  3341. }
  3342. else {
  3343. variable = new LocalVariable(name, identifier, UNKNOWN_EXPRESSION, this.context);
  3344. }
  3345. this.variables.set(name, variable);
  3346. return variable;
  3347. }
  3348. addParameterVariables(parameters, hasRest) {
  3349. this.parameters = parameters;
  3350. for (const parameterList of parameters) {
  3351. for (const parameter of parameterList) {
  3352. parameter.alwaysRendered = true;
  3353. }
  3354. }
  3355. this.hasRest = hasRest;
  3356. }
  3357. includeCallArguments(context, args) {
  3358. let calledFromTryStatement = false;
  3359. let argIncluded = false;
  3360. const restParam = this.hasRest && this.parameters[this.parameters.length - 1];
  3361. for (let index = args.length - 1; index >= 0; index--) {
  3362. const paramVars = this.parameters[index] || restParam;
  3363. const arg = args[index];
  3364. if (paramVars) {
  3365. calledFromTryStatement = false;
  3366. for (const variable of paramVars) {
  3367. if (variable.included) {
  3368. argIncluded = true;
  3369. }
  3370. if (variable.calledFromTryStatement) {
  3371. calledFromTryStatement = true;
  3372. }
  3373. }
  3374. }
  3375. if (!argIncluded && arg.shouldBeIncluded(context)) {
  3376. argIncluded = true;
  3377. }
  3378. if (argIncluded) {
  3379. arg.include(context, calledFromTryStatement);
  3380. }
  3381. }
  3382. }
  3383. }
  3384. class ReturnValueScope extends ParameterScope {
  3385. constructor() {
  3386. super(...arguments);
  3387. this.returnExpression = null;
  3388. this.returnExpressions = [];
  3389. }
  3390. addReturnExpression(expression) {
  3391. this.returnExpressions.push(expression);
  3392. }
  3393. getReturnExpression() {
  3394. if (this.returnExpression === null)
  3395. this.updateReturnExpression();
  3396. return this.returnExpression;
  3397. }
  3398. updateReturnExpression() {
  3399. if (this.returnExpressions.length === 1) {
  3400. this.returnExpression = this.returnExpressions[0];
  3401. }
  3402. else {
  3403. this.returnExpression = UNKNOWN_EXPRESSION;
  3404. for (const expression of this.returnExpressions) {
  3405. expression.deoptimizePath(UNKNOWN_PATH);
  3406. }
  3407. }
  3408. }
  3409. }
  3410. class FunctionScope extends ReturnValueScope {
  3411. constructor(parent, context) {
  3412. super(parent, context);
  3413. this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
  3414. this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
  3415. }
  3416. findLexicalBoundary() {
  3417. return this;
  3418. }
  3419. includeCallArguments(context, args) {
  3420. super.includeCallArguments(context, args);
  3421. if (this.argumentsVariable.included) {
  3422. for (const arg of args) {
  3423. if (!arg.included) {
  3424. arg.include(context, false);
  3425. }
  3426. }
  3427. }
  3428. }
  3429. }
  3430. function isReference(node, parent) {
  3431. if (node.type === 'MemberExpression') {
  3432. return !node.computed && isReference(node.object, node);
  3433. }
  3434. if (node.type === 'Identifier') {
  3435. if (!parent)
  3436. return true;
  3437. switch (parent.type) {
  3438. // disregard `bar` in `foo.bar`
  3439. case 'MemberExpression': return parent.computed || node === parent.object;
  3440. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  3441. case 'MethodDefinition': return parent.computed;
  3442. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  3443. case 'Property': return parent.computed || node === parent.value;
  3444. // disregard the `bar` in `export { foo as bar }` or
  3445. // the foo in `import { foo as bar }`
  3446. case 'ExportSpecifier':
  3447. case 'ImportSpecifier': return node === parent.local;
  3448. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  3449. case 'LabeledStatement':
  3450. case 'BreakStatement':
  3451. case 'ContinueStatement': return false;
  3452. default: return true;
  3453. }
  3454. }
  3455. return false;
  3456. }
  3457. const BLANK = Object.create(null);
  3458. const ValueProperties = Symbol('Value Properties');
  3459. const PURE = { pure: true };
  3460. const IMPURE = { pure: false };
  3461. // We use shortened variables to reduce file size here
  3462. /* OBJECT */
  3463. const O = {
  3464. // @ts-ignore
  3465. __proto__: null,
  3466. [ValueProperties]: IMPURE
  3467. };
  3468. /* PURE FUNCTION */
  3469. const PF = {
  3470. // @ts-ignore
  3471. __proto__: null,
  3472. [ValueProperties]: PURE
  3473. };
  3474. /* CONSTRUCTOR */
  3475. const C = {
  3476. // @ts-ignore
  3477. __proto__: null,
  3478. [ValueProperties]: IMPURE,
  3479. prototype: O
  3480. };
  3481. /* PURE CONSTRUCTOR */
  3482. const PC = {
  3483. // @ts-ignore
  3484. __proto__: null,
  3485. [ValueProperties]: PURE,
  3486. prototype: O
  3487. };
  3488. const ARRAY_TYPE = {
  3489. // @ts-ignore
  3490. __proto__: null,
  3491. [ValueProperties]: PURE,
  3492. from: PF,
  3493. of: PF,
  3494. prototype: O
  3495. };
  3496. const INTL_MEMBER = {
  3497. // @ts-ignore
  3498. __proto__: null,
  3499. [ValueProperties]: PURE,
  3500. supportedLocalesOf: PC
  3501. };
  3502. const knownGlobals = {
  3503. // Placeholders for global objects to avoid shape mutations
  3504. global: O,
  3505. globalThis: O,
  3506. self: O,
  3507. window: O,
  3508. // Common globals
  3509. // @ts-ignore
  3510. __proto__: null,
  3511. [ValueProperties]: IMPURE,
  3512. Array: {
  3513. // @ts-ignore
  3514. __proto__: null,
  3515. [ValueProperties]: IMPURE,
  3516. from: PF,
  3517. isArray: PF,
  3518. of: PF,
  3519. prototype: O
  3520. },
  3521. ArrayBuffer: {
  3522. // @ts-ignore
  3523. __proto__: null,
  3524. [ValueProperties]: PURE,
  3525. isView: PF,
  3526. prototype: O
  3527. },
  3528. Atomics: O,
  3529. BigInt: C,
  3530. BigInt64Array: C,
  3531. BigUint64Array: C,
  3532. Boolean: PC,
  3533. // @ts-ignore
  3534. constructor: C,
  3535. DataView: PC,
  3536. Date: {
  3537. // @ts-ignore
  3538. __proto__: null,
  3539. [ValueProperties]: PURE,
  3540. now: PF,
  3541. parse: PF,
  3542. prototype: O,
  3543. UTC: PF
  3544. },
  3545. decodeURI: PF,
  3546. decodeURIComponent: PF,
  3547. encodeURI: PF,
  3548. encodeURIComponent: PF,
  3549. Error: PC,
  3550. escape: PF,
  3551. eval: O,
  3552. EvalError: PC,
  3553. Float32Array: ARRAY_TYPE,
  3554. Float64Array: ARRAY_TYPE,
  3555. Function: C,
  3556. // @ts-ignore
  3557. hasOwnProperty: O,
  3558. Infinity: O,
  3559. Int16Array: ARRAY_TYPE,
  3560. Int32Array: ARRAY_TYPE,
  3561. Int8Array: ARRAY_TYPE,
  3562. isFinite: PF,
  3563. isNaN: PF,
  3564. // @ts-ignore
  3565. isPrototypeOf: O,
  3566. JSON: O,
  3567. Map: PC,
  3568. Math: {
  3569. // @ts-ignore
  3570. __proto__: null,
  3571. [ValueProperties]: IMPURE,
  3572. abs: PF,
  3573. acos: PF,
  3574. acosh: PF,
  3575. asin: PF,
  3576. asinh: PF,
  3577. atan: PF,
  3578. atan2: PF,
  3579. atanh: PF,
  3580. cbrt: PF,
  3581. ceil: PF,
  3582. clz32: PF,
  3583. cos: PF,
  3584. cosh: PF,
  3585. exp: PF,
  3586. expm1: PF,
  3587. floor: PF,
  3588. fround: PF,
  3589. hypot: PF,
  3590. imul: PF,
  3591. log: PF,
  3592. log10: PF,
  3593. log1p: PF,
  3594. log2: PF,
  3595. max: PF,
  3596. min: PF,
  3597. pow: PF,
  3598. random: PF,
  3599. round: PF,
  3600. sign: PF,
  3601. sin: PF,
  3602. sinh: PF,
  3603. sqrt: PF,
  3604. tan: PF,
  3605. tanh: PF,
  3606. trunc: PF
  3607. },
  3608. NaN: O,
  3609. Number: {
  3610. // @ts-ignore
  3611. __proto__: null,
  3612. [ValueProperties]: PURE,
  3613. isFinite: PF,
  3614. isInteger: PF,
  3615. isNaN: PF,
  3616. isSafeInteger: PF,
  3617. parseFloat: PF,
  3618. parseInt: PF,
  3619. prototype: O
  3620. },
  3621. Object: {
  3622. // @ts-ignore
  3623. __proto__: null,
  3624. [ValueProperties]: PURE,
  3625. create: PF,
  3626. getNotifier: PF,
  3627. getOwn: PF,
  3628. getOwnPropertyDescriptor: PF,
  3629. getOwnPropertyNames: PF,
  3630. getOwnPropertySymbols: PF,
  3631. getPrototypeOf: PF,
  3632. is: PF,
  3633. isExtensible: PF,
  3634. isFrozen: PF,
  3635. isSealed: PF,
  3636. keys: PF,
  3637. prototype: O
  3638. },
  3639. parseFloat: PF,
  3640. parseInt: PF,
  3641. Promise: {
  3642. // @ts-ignore
  3643. __proto__: null,
  3644. [ValueProperties]: IMPURE,
  3645. all: PF,
  3646. prototype: O,
  3647. race: PF,
  3648. resolve: PF
  3649. },
  3650. // @ts-ignore
  3651. propertyIsEnumerable: O,
  3652. Proxy: O,
  3653. RangeError: PC,
  3654. ReferenceError: PC,
  3655. Reflect: O,
  3656. RegExp: PC,
  3657. Set: PC,
  3658. SharedArrayBuffer: C,
  3659. String: {
  3660. // @ts-ignore
  3661. __proto__: null,
  3662. [ValueProperties]: PURE,
  3663. fromCharCode: PF,
  3664. fromCodePoint: PF,
  3665. prototype: O,
  3666. raw: PF
  3667. },
  3668. Symbol: {
  3669. // @ts-ignore
  3670. __proto__: null,
  3671. [ValueProperties]: PURE,
  3672. for: PF,
  3673. keyFor: PF,
  3674. prototype: O
  3675. },
  3676. SyntaxError: PC,
  3677. // @ts-ignore
  3678. toLocaleString: O,
  3679. // @ts-ignore
  3680. toString: O,
  3681. TypeError: PC,
  3682. Uint16Array: ARRAY_TYPE,
  3683. Uint32Array: ARRAY_TYPE,
  3684. Uint8Array: ARRAY_TYPE,
  3685. Uint8ClampedArray: ARRAY_TYPE,
  3686. // Technically, this is a global, but it needs special handling
  3687. // undefined: ?,
  3688. unescape: PF,
  3689. URIError: PC,
  3690. // @ts-ignore
  3691. valueOf: O,
  3692. WeakMap: PC,
  3693. WeakSet: PC,
  3694. // Additional globals shared by Node and Browser that are not strictly part of the language
  3695. clearInterval: C,
  3696. clearTimeout: C,
  3697. console: O,
  3698. Intl: {
  3699. // @ts-ignore
  3700. __proto__: null,
  3701. [ValueProperties]: IMPURE,
  3702. Collator: INTL_MEMBER,
  3703. DateTimeFormat: INTL_MEMBER,
  3704. ListFormat: INTL_MEMBER,
  3705. NumberFormat: INTL_MEMBER,
  3706. PluralRules: INTL_MEMBER,
  3707. RelativeTimeFormat: INTL_MEMBER
  3708. },
  3709. setInterval: C,
  3710. setTimeout: C,
  3711. TextDecoder: C,
  3712. TextEncoder: C,
  3713. URL: C,
  3714. URLSearchParams: C,
  3715. // Browser specific globals
  3716. AbortController: C,
  3717. AbortSignal: C,
  3718. addEventListener: O,
  3719. alert: O,
  3720. AnalyserNode: C,
  3721. Animation: C,
  3722. AnimationEvent: C,
  3723. applicationCache: O,
  3724. ApplicationCache: C,
  3725. ApplicationCacheErrorEvent: C,
  3726. atob: O,
  3727. Attr: C,
  3728. Audio: C,
  3729. AudioBuffer: C,
  3730. AudioBufferSourceNode: C,
  3731. AudioContext: C,
  3732. AudioDestinationNode: C,
  3733. AudioListener: C,
  3734. AudioNode: C,
  3735. AudioParam: C,
  3736. AudioProcessingEvent: C,
  3737. AudioScheduledSourceNode: C,
  3738. AudioWorkletNode: C,
  3739. BarProp: C,
  3740. BaseAudioContext: C,
  3741. BatteryManager: C,
  3742. BeforeUnloadEvent: C,
  3743. BiquadFilterNode: C,
  3744. Blob: C,
  3745. BlobEvent: C,
  3746. blur: O,
  3747. BroadcastChannel: C,
  3748. btoa: O,
  3749. ByteLengthQueuingStrategy: C,
  3750. Cache: C,
  3751. caches: O,
  3752. CacheStorage: C,
  3753. cancelAnimationFrame: O,
  3754. cancelIdleCallback: O,
  3755. CanvasCaptureMediaStreamTrack: C,
  3756. CanvasGradient: C,
  3757. CanvasPattern: C,
  3758. CanvasRenderingContext2D: C,
  3759. ChannelMergerNode: C,
  3760. ChannelSplitterNode: C,
  3761. CharacterData: C,
  3762. clientInformation: O,
  3763. ClipboardEvent: C,
  3764. close: O,
  3765. closed: O,
  3766. CloseEvent: C,
  3767. Comment: C,
  3768. CompositionEvent: C,
  3769. confirm: O,
  3770. ConstantSourceNode: C,
  3771. ConvolverNode: C,
  3772. CountQueuingStrategy: C,
  3773. createImageBitmap: O,
  3774. Credential: C,
  3775. CredentialsContainer: C,
  3776. crypto: O,
  3777. Crypto: C,
  3778. CryptoKey: C,
  3779. CSS: C,
  3780. CSSConditionRule: C,
  3781. CSSFontFaceRule: C,
  3782. CSSGroupingRule: C,
  3783. CSSImportRule: C,
  3784. CSSKeyframeRule: C,
  3785. CSSKeyframesRule: C,
  3786. CSSMediaRule: C,
  3787. CSSNamespaceRule: C,
  3788. CSSPageRule: C,
  3789. CSSRule: C,
  3790. CSSRuleList: C,
  3791. CSSStyleDeclaration: C,
  3792. CSSStyleRule: C,
  3793. CSSStyleSheet: C,
  3794. CSSSupportsRule: C,
  3795. CustomElementRegistry: C,
  3796. customElements: O,
  3797. CustomEvent: C,
  3798. DataTransfer: C,
  3799. DataTransferItem: C,
  3800. DataTransferItemList: C,
  3801. defaultstatus: O,
  3802. defaultStatus: O,
  3803. DelayNode: C,
  3804. DeviceMotionEvent: C,
  3805. DeviceOrientationEvent: C,
  3806. devicePixelRatio: O,
  3807. dispatchEvent: O,
  3808. document: O,
  3809. Document: C,
  3810. DocumentFragment: C,
  3811. DocumentType: C,
  3812. DOMError: C,
  3813. DOMException: C,
  3814. DOMImplementation: C,
  3815. DOMMatrix: C,
  3816. DOMMatrixReadOnly: C,
  3817. DOMParser: C,
  3818. DOMPoint: C,
  3819. DOMPointReadOnly: C,
  3820. DOMQuad: C,
  3821. DOMRect: C,
  3822. DOMRectReadOnly: C,
  3823. DOMStringList: C,
  3824. DOMStringMap: C,
  3825. DOMTokenList: C,
  3826. DragEvent: C,
  3827. DynamicsCompressorNode: C,
  3828. Element: C,
  3829. ErrorEvent: C,
  3830. Event: C,
  3831. EventSource: C,
  3832. EventTarget: C,
  3833. external: O,
  3834. fetch: O,
  3835. File: C,
  3836. FileList: C,
  3837. FileReader: C,
  3838. find: O,
  3839. focus: O,
  3840. FocusEvent: C,
  3841. FontFace: C,
  3842. FontFaceSetLoadEvent: C,
  3843. FormData: C,
  3844. frames: O,
  3845. GainNode: C,
  3846. Gamepad: C,
  3847. GamepadButton: C,
  3848. GamepadEvent: C,
  3849. getComputedStyle: O,
  3850. getSelection: O,
  3851. HashChangeEvent: C,
  3852. Headers: C,
  3853. history: O,
  3854. History: C,
  3855. HTMLAllCollection: C,
  3856. HTMLAnchorElement: C,
  3857. HTMLAreaElement: C,
  3858. HTMLAudioElement: C,
  3859. HTMLBaseElement: C,
  3860. HTMLBodyElement: C,
  3861. HTMLBRElement: C,
  3862. HTMLButtonElement: C,
  3863. HTMLCanvasElement: C,
  3864. HTMLCollection: C,
  3865. HTMLContentElement: C,
  3866. HTMLDataElement: C,
  3867. HTMLDataListElement: C,
  3868. HTMLDetailsElement: C,
  3869. HTMLDialogElement: C,
  3870. HTMLDirectoryElement: C,
  3871. HTMLDivElement: C,
  3872. HTMLDListElement: C,
  3873. HTMLDocument: C,
  3874. HTMLElement: C,
  3875. HTMLEmbedElement: C,
  3876. HTMLFieldSetElement: C,
  3877. HTMLFontElement: C,
  3878. HTMLFormControlsCollection: C,
  3879. HTMLFormElement: C,
  3880. HTMLFrameElement: C,
  3881. HTMLFrameSetElement: C,
  3882. HTMLHeadElement: C,
  3883. HTMLHeadingElement: C,
  3884. HTMLHRElement: C,
  3885. HTMLHtmlElement: C,
  3886. HTMLIFrameElement: C,
  3887. HTMLImageElement: C,
  3888. HTMLInputElement: C,
  3889. HTMLLabelElement: C,
  3890. HTMLLegendElement: C,
  3891. HTMLLIElement: C,
  3892. HTMLLinkElement: C,
  3893. HTMLMapElement: C,
  3894. HTMLMarqueeElement: C,
  3895. HTMLMediaElement: C,
  3896. HTMLMenuElement: C,
  3897. HTMLMetaElement: C,
  3898. HTMLMeterElement: C,
  3899. HTMLModElement: C,
  3900. HTMLObjectElement: C,
  3901. HTMLOListElement: C,
  3902. HTMLOptGroupElement: C,
  3903. HTMLOptionElement: C,
  3904. HTMLOptionsCollection: C,
  3905. HTMLOutputElement: C,
  3906. HTMLParagraphElement: C,
  3907. HTMLParamElement: C,
  3908. HTMLPictureElement: C,
  3909. HTMLPreElement: C,
  3910. HTMLProgressElement: C,
  3911. HTMLQuoteElement: C,
  3912. HTMLScriptElement: C,
  3913. HTMLSelectElement: C,
  3914. HTMLShadowElement: C,
  3915. HTMLSlotElement: C,
  3916. HTMLSourceElement: C,
  3917. HTMLSpanElement: C,
  3918. HTMLStyleElement: C,
  3919. HTMLTableCaptionElement: C,
  3920. HTMLTableCellElement: C,
  3921. HTMLTableColElement: C,
  3922. HTMLTableElement: C,
  3923. HTMLTableRowElement: C,
  3924. HTMLTableSectionElement: C,
  3925. HTMLTemplateElement: C,
  3926. HTMLTextAreaElement: C,
  3927. HTMLTimeElement: C,
  3928. HTMLTitleElement: C,
  3929. HTMLTrackElement: C,
  3930. HTMLUListElement: C,
  3931. HTMLUnknownElement: C,
  3932. HTMLVideoElement: C,
  3933. IDBCursor: C,
  3934. IDBCursorWithValue: C,
  3935. IDBDatabase: C,
  3936. IDBFactory: C,
  3937. IDBIndex: C,
  3938. IDBKeyRange: C,
  3939. IDBObjectStore: C,
  3940. IDBOpenDBRequest: C,
  3941. IDBRequest: C,
  3942. IDBTransaction: C,
  3943. IDBVersionChangeEvent: C,
  3944. IdleDeadline: C,
  3945. IIRFilterNode: C,
  3946. Image: C,
  3947. ImageBitmap: C,
  3948. ImageBitmapRenderingContext: C,
  3949. ImageCapture: C,
  3950. ImageData: C,
  3951. indexedDB: O,
  3952. innerHeight: O,
  3953. innerWidth: O,
  3954. InputEvent: C,
  3955. IntersectionObserver: C,
  3956. IntersectionObserverEntry: C,
  3957. isSecureContext: O,
  3958. KeyboardEvent: C,
  3959. KeyframeEffect: C,
  3960. length: O,
  3961. localStorage: O,
  3962. location: O,
  3963. Location: C,
  3964. locationbar: O,
  3965. matchMedia: O,
  3966. MediaDeviceInfo: C,
  3967. MediaDevices: C,
  3968. MediaElementAudioSourceNode: C,
  3969. MediaEncryptedEvent: C,
  3970. MediaError: C,
  3971. MediaKeyMessageEvent: C,
  3972. MediaKeySession: C,
  3973. MediaKeyStatusMap: C,
  3974. MediaKeySystemAccess: C,
  3975. MediaList: C,
  3976. MediaQueryList: C,
  3977. MediaQueryListEvent: C,
  3978. MediaRecorder: C,
  3979. MediaSettingsRange: C,
  3980. MediaSource: C,
  3981. MediaStream: C,
  3982. MediaStreamAudioDestinationNode: C,
  3983. MediaStreamAudioSourceNode: C,
  3984. MediaStreamEvent: C,
  3985. MediaStreamTrack: C,
  3986. MediaStreamTrackEvent: C,
  3987. menubar: O,
  3988. MessageChannel: C,
  3989. MessageEvent: C,
  3990. MessagePort: C,
  3991. MIDIAccess: C,
  3992. MIDIConnectionEvent: C,
  3993. MIDIInput: C,
  3994. MIDIInputMap: C,
  3995. MIDIMessageEvent: C,
  3996. MIDIOutput: C,
  3997. MIDIOutputMap: C,
  3998. MIDIPort: C,
  3999. MimeType: C,
  4000. MimeTypeArray: C,
  4001. MouseEvent: C,
  4002. moveBy: O,
  4003. moveTo: O,
  4004. MutationEvent: C,
  4005. MutationObserver: C,
  4006. MutationRecord: C,
  4007. name: O,
  4008. NamedNodeMap: C,
  4009. NavigationPreloadManager: C,
  4010. navigator: O,
  4011. Navigator: C,
  4012. NetworkInformation: C,
  4013. Node: C,
  4014. NodeFilter: O,
  4015. NodeIterator: C,
  4016. NodeList: C,
  4017. Notification: C,
  4018. OfflineAudioCompletionEvent: C,
  4019. OfflineAudioContext: C,
  4020. offscreenBuffering: O,
  4021. OffscreenCanvas: C,
  4022. open: O,
  4023. openDatabase: O,
  4024. Option: C,
  4025. origin: O,
  4026. OscillatorNode: C,
  4027. outerHeight: O,
  4028. outerWidth: O,
  4029. PageTransitionEvent: C,
  4030. pageXOffset: O,
  4031. pageYOffset: O,
  4032. PannerNode: C,
  4033. parent: O,
  4034. Path2D: C,
  4035. PaymentAddress: C,
  4036. PaymentRequest: C,
  4037. PaymentRequestUpdateEvent: C,
  4038. PaymentResponse: C,
  4039. performance: O,
  4040. Performance: C,
  4041. PerformanceEntry: C,
  4042. PerformanceLongTaskTiming: C,
  4043. PerformanceMark: C,
  4044. PerformanceMeasure: C,
  4045. PerformanceNavigation: C,
  4046. PerformanceNavigationTiming: C,
  4047. PerformanceObserver: C,
  4048. PerformanceObserverEntryList: C,
  4049. PerformancePaintTiming: C,
  4050. PerformanceResourceTiming: C,
  4051. PerformanceTiming: C,
  4052. PeriodicWave: C,
  4053. Permissions: C,
  4054. PermissionStatus: C,
  4055. personalbar: O,
  4056. PhotoCapabilities: C,
  4057. Plugin: C,
  4058. PluginArray: C,
  4059. PointerEvent: C,
  4060. PopStateEvent: C,
  4061. postMessage: O,
  4062. Presentation: C,
  4063. PresentationAvailability: C,
  4064. PresentationConnection: C,
  4065. PresentationConnectionAvailableEvent: C,
  4066. PresentationConnectionCloseEvent: C,
  4067. PresentationConnectionList: C,
  4068. PresentationReceiver: C,
  4069. PresentationRequest: C,
  4070. print: O,
  4071. ProcessingInstruction: C,
  4072. ProgressEvent: C,
  4073. PromiseRejectionEvent: C,
  4074. prompt: O,
  4075. PushManager: C,
  4076. PushSubscription: C,
  4077. PushSubscriptionOptions: C,
  4078. queueMicrotask: O,
  4079. RadioNodeList: C,
  4080. Range: C,
  4081. ReadableStream: C,
  4082. RemotePlayback: C,
  4083. removeEventListener: O,
  4084. Request: C,
  4085. requestAnimationFrame: O,
  4086. requestIdleCallback: O,
  4087. resizeBy: O,
  4088. ResizeObserver: C,
  4089. ResizeObserverEntry: C,
  4090. resizeTo: O,
  4091. Response: C,
  4092. RTCCertificate: C,
  4093. RTCDataChannel: C,
  4094. RTCDataChannelEvent: C,
  4095. RTCDtlsTransport: C,
  4096. RTCIceCandidate: C,
  4097. RTCIceTransport: C,
  4098. RTCPeerConnection: C,
  4099. RTCPeerConnectionIceEvent: C,
  4100. RTCRtpReceiver: C,
  4101. RTCRtpSender: C,
  4102. RTCSctpTransport: C,
  4103. RTCSessionDescription: C,
  4104. RTCStatsReport: C,
  4105. RTCTrackEvent: C,
  4106. screen: O,
  4107. Screen: C,
  4108. screenLeft: O,
  4109. ScreenOrientation: C,
  4110. screenTop: O,
  4111. screenX: O,
  4112. screenY: O,
  4113. ScriptProcessorNode: C,
  4114. scroll: O,
  4115. scrollbars: O,
  4116. scrollBy: O,
  4117. scrollTo: O,
  4118. scrollX: O,
  4119. scrollY: O,
  4120. SecurityPolicyViolationEvent: C,
  4121. Selection: C,
  4122. ServiceWorker: C,
  4123. ServiceWorkerContainer: C,
  4124. ServiceWorkerRegistration: C,
  4125. sessionStorage: O,
  4126. ShadowRoot: C,
  4127. SharedWorker: C,
  4128. SourceBuffer: C,
  4129. SourceBufferList: C,
  4130. speechSynthesis: O,
  4131. SpeechSynthesisEvent: C,
  4132. SpeechSynthesisUtterance: C,
  4133. StaticRange: C,
  4134. status: O,
  4135. statusbar: O,
  4136. StereoPannerNode: C,
  4137. stop: O,
  4138. Storage: C,
  4139. StorageEvent: C,
  4140. StorageManager: C,
  4141. styleMedia: O,
  4142. StyleSheet: C,
  4143. StyleSheetList: C,
  4144. SubtleCrypto: C,
  4145. SVGAElement: C,
  4146. SVGAngle: C,
  4147. SVGAnimatedAngle: C,
  4148. SVGAnimatedBoolean: C,
  4149. SVGAnimatedEnumeration: C,
  4150. SVGAnimatedInteger: C,
  4151. SVGAnimatedLength: C,
  4152. SVGAnimatedLengthList: C,
  4153. SVGAnimatedNumber: C,
  4154. SVGAnimatedNumberList: C,
  4155. SVGAnimatedPreserveAspectRatio: C,
  4156. SVGAnimatedRect: C,
  4157. SVGAnimatedString: C,
  4158. SVGAnimatedTransformList: C,
  4159. SVGAnimateElement: C,
  4160. SVGAnimateMotionElement: C,
  4161. SVGAnimateTransformElement: C,
  4162. SVGAnimationElement: C,
  4163. SVGCircleElement: C,
  4164. SVGClipPathElement: C,
  4165. SVGComponentTransferFunctionElement: C,
  4166. SVGDefsElement: C,
  4167. SVGDescElement: C,
  4168. SVGDiscardElement: C,
  4169. SVGElement: C,
  4170. SVGEllipseElement: C,
  4171. SVGFEBlendElement: C,
  4172. SVGFEColorMatrixElement: C,
  4173. SVGFEComponentTransferElement: C,
  4174. SVGFECompositeElement: C,
  4175. SVGFEConvolveMatrixElement: C,
  4176. SVGFEDiffuseLightingElement: C,
  4177. SVGFEDisplacementMapElement: C,
  4178. SVGFEDistantLightElement: C,
  4179. SVGFEDropShadowElement: C,
  4180. SVGFEFloodElement: C,
  4181. SVGFEFuncAElement: C,
  4182. SVGFEFuncBElement: C,
  4183. SVGFEFuncGElement: C,
  4184. SVGFEFuncRElement: C,
  4185. SVGFEGaussianBlurElement: C,
  4186. SVGFEImageElement: C,
  4187. SVGFEMergeElement: C,
  4188. SVGFEMergeNodeElement: C,
  4189. SVGFEMorphologyElement: C,
  4190. SVGFEOffsetElement: C,
  4191. SVGFEPointLightElement: C,
  4192. SVGFESpecularLightingElement: C,
  4193. SVGFESpotLightElement: C,
  4194. SVGFETileElement: C,
  4195. SVGFETurbulenceElement: C,
  4196. SVGFilterElement: C,
  4197. SVGForeignObjectElement: C,
  4198. SVGGElement: C,
  4199. SVGGeometryElement: C,
  4200. SVGGradientElement: C,
  4201. SVGGraphicsElement: C,
  4202. SVGImageElement: C,
  4203. SVGLength: C,
  4204. SVGLengthList: C,
  4205. SVGLinearGradientElement: C,
  4206. SVGLineElement: C,
  4207. SVGMarkerElement: C,
  4208. SVGMaskElement: C,
  4209. SVGMatrix: C,
  4210. SVGMetadataElement: C,
  4211. SVGMPathElement: C,
  4212. SVGNumber: C,
  4213. SVGNumberList: C,
  4214. SVGPathElement: C,
  4215. SVGPatternElement: C,
  4216. SVGPoint: C,
  4217. SVGPointList: C,
  4218. SVGPolygonElement: C,
  4219. SVGPolylineElement: C,
  4220. SVGPreserveAspectRatio: C,
  4221. SVGRadialGradientElement: C,
  4222. SVGRect: C,
  4223. SVGRectElement: C,
  4224. SVGScriptElement: C,
  4225. SVGSetElement: C,
  4226. SVGStopElement: C,
  4227. SVGStringList: C,
  4228. SVGStyleElement: C,
  4229. SVGSVGElement: C,
  4230. SVGSwitchElement: C,
  4231. SVGSymbolElement: C,
  4232. SVGTextContentElement: C,
  4233. SVGTextElement: C,
  4234. SVGTextPathElement: C,
  4235. SVGTextPositioningElement: C,
  4236. SVGTitleElement: C,
  4237. SVGTransform: C,
  4238. SVGTransformList: C,
  4239. SVGTSpanElement: C,
  4240. SVGUnitTypes: C,
  4241. SVGUseElement: C,
  4242. SVGViewElement: C,
  4243. TaskAttributionTiming: C,
  4244. Text: C,
  4245. TextEvent: C,
  4246. TextMetrics: C,
  4247. TextTrack: C,
  4248. TextTrackCue: C,
  4249. TextTrackCueList: C,
  4250. TextTrackList: C,
  4251. TimeRanges: C,
  4252. toolbar: O,
  4253. top: O,
  4254. Touch: C,
  4255. TouchEvent: C,
  4256. TouchList: C,
  4257. TrackEvent: C,
  4258. TransitionEvent: C,
  4259. TreeWalker: C,
  4260. UIEvent: C,
  4261. ValidityState: C,
  4262. visualViewport: O,
  4263. VisualViewport: C,
  4264. VTTCue: C,
  4265. WaveShaperNode: C,
  4266. WebAssembly: O,
  4267. WebGL2RenderingContext: C,
  4268. WebGLActiveInfo: C,
  4269. WebGLBuffer: C,
  4270. WebGLContextEvent: C,
  4271. WebGLFramebuffer: C,
  4272. WebGLProgram: C,
  4273. WebGLQuery: C,
  4274. WebGLRenderbuffer: C,
  4275. WebGLRenderingContext: C,
  4276. WebGLSampler: C,
  4277. WebGLShader: C,
  4278. WebGLShaderPrecisionFormat: C,
  4279. WebGLSync: C,
  4280. WebGLTexture: C,
  4281. WebGLTransformFeedback: C,
  4282. WebGLUniformLocation: C,
  4283. WebGLVertexArrayObject: C,
  4284. WebSocket: C,
  4285. WheelEvent: C,
  4286. Window: C,
  4287. Worker: C,
  4288. WritableStream: C,
  4289. XMLDocument: C,
  4290. XMLHttpRequest: C,
  4291. XMLHttpRequestEventTarget: C,
  4292. XMLHttpRequestUpload: C,
  4293. XMLSerializer: C,
  4294. XPathEvaluator: C,
  4295. XPathExpression: C,
  4296. XPathResult: C,
  4297. XSLTProcessor: C
  4298. };
  4299. for (const global of ['window', 'global', 'self', 'globalThis']) {
  4300. knownGlobals[global] = knownGlobals;
  4301. }
  4302. function getGlobalAtPath(path) {
  4303. let currentGlobal = knownGlobals;
  4304. for (const pathSegment of path) {
  4305. if (typeof pathSegment !== 'string') {
  4306. return null;
  4307. }
  4308. currentGlobal = currentGlobal[pathSegment];
  4309. if (!currentGlobal) {
  4310. return null;
  4311. }
  4312. }
  4313. return currentGlobal[ValueProperties];
  4314. }
  4315. function isPureGlobal(path) {
  4316. const globalAtPath = getGlobalAtPath(path);
  4317. return globalAtPath !== null && globalAtPath.pure;
  4318. }
  4319. function isGlobalMember(path) {
  4320. if (path.length === 1) {
  4321. return path[0] === 'undefined' || getGlobalAtPath(path) !== null;
  4322. }
  4323. return getGlobalAtPath(path.slice(0, -1)) !== null;
  4324. }
  4325. class GlobalVariable extends Variable {
  4326. hasEffectsWhenAccessedAtPath(path) {
  4327. return !isGlobalMember([this.name, ...path]);
  4328. }
  4329. hasEffectsWhenCalledAtPath(path) {
  4330. return !isPureGlobal([this.name, ...path]);
  4331. }
  4332. }
  4333. class Identifier$1 extends NodeBase {
  4334. constructor() {
  4335. super(...arguments);
  4336. this.variable = null;
  4337. this.bound = false;
  4338. }
  4339. addExportedVariables(variables) {
  4340. if (this.variable !== null && this.variable.exportName) {
  4341. variables.push(this.variable);
  4342. }
  4343. }
  4344. bind() {
  4345. if (this.bound)
  4346. return;
  4347. this.bound = true;
  4348. if (this.variable === null && isReference(this, this.parent)) {
  4349. this.variable = this.scope.findVariable(this.name);
  4350. this.variable.addReference(this);
  4351. }
  4352. if (this.variable !== null &&
  4353. this.variable instanceof LocalVariable &&
  4354. this.variable.additionalInitializers !== null) {
  4355. this.variable.consolidateInitializers();
  4356. }
  4357. }
  4358. declare(kind, init) {
  4359. let variable;
  4360. switch (kind) {
  4361. case 'var':
  4362. variable = this.scope.addDeclaration(this, this.context, init, true);
  4363. break;
  4364. case 'function':
  4365. variable = this.scope.addDeclaration(this, this.context, init, 'function');
  4366. break;
  4367. case 'let':
  4368. case 'const':
  4369. case 'class':
  4370. variable = this.scope.addDeclaration(this, this.context, init, false);
  4371. break;
  4372. case 'parameter':
  4373. variable = this.scope.addParameterDeclaration(this);
  4374. break;
  4375. /* istanbul ignore next */
  4376. default:
  4377. /* istanbul ignore next */
  4378. throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
  4379. }
  4380. return [(this.variable = variable)];
  4381. }
  4382. deoptimizePath(path) {
  4383. if (!this.bound)
  4384. this.bind();
  4385. if (path.length === 0 && !this.scope.contains(this.name)) {
  4386. this.disallowImportReassignment();
  4387. }
  4388. this.variable.deoptimizePath(path);
  4389. }
  4390. getLiteralValueAtPath(path, recursionTracker, origin) {
  4391. if (!this.bound)
  4392. this.bind();
  4393. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  4394. }
  4395. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  4396. if (!this.bound)
  4397. this.bind();
  4398. return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  4399. }
  4400. hasEffects() {
  4401. return (this.context.unknownGlobalSideEffects &&
  4402. this.variable instanceof GlobalVariable &&
  4403. this.variable.hasEffectsWhenAccessedAtPath(EMPTY_PATH));
  4404. }
  4405. hasEffectsWhenAccessedAtPath(path, context) {
  4406. return this.variable !== null && this.variable.hasEffectsWhenAccessedAtPath(path, context);
  4407. }
  4408. hasEffectsWhenAssignedAtPath(path, context) {
  4409. return !this.variable || this.variable.hasEffectsWhenAssignedAtPath(path, context);
  4410. }
  4411. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  4412. return !this.variable || this.variable.hasEffectsWhenCalledAtPath(path, callOptions, context);
  4413. }
  4414. include(context) {
  4415. if (!this.included) {
  4416. this.included = true;
  4417. if (this.variable !== null) {
  4418. this.context.includeVariable(context, this.variable);
  4419. }
  4420. }
  4421. }
  4422. includeCallArguments(context, args) {
  4423. this.variable.includeCallArguments(context, args);
  4424. }
  4425. render(code, _options, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
  4426. if (this.variable) {
  4427. const name = this.variable.getName();
  4428. if (name !== this.name) {
  4429. code.overwrite(this.start, this.end, name, {
  4430. contentOnly: true,
  4431. storeName: true
  4432. });
  4433. if (isShorthandProperty) {
  4434. code.prependRight(this.start, `${this.name}: `);
  4435. }
  4436. }
  4437. // In strict mode, any variable named "eval" must be the actual "eval" function
  4438. if (name === 'eval' &&
  4439. renderedParentType === CallExpression &&
  4440. isCalleeOfRenderedParent) {
  4441. code.appendRight(this.start, '0, ');
  4442. }
  4443. }
  4444. }
  4445. disallowImportReassignment() {
  4446. return this.context.error({
  4447. code: 'ILLEGAL_REASSIGNMENT',
  4448. message: `Illegal reassignment to import '${this.name}'`
  4449. }, this.start);
  4450. }
  4451. }
  4452. class RestElement extends NodeBase {
  4453. constructor() {
  4454. super(...arguments);
  4455. this.declarationInit = null;
  4456. }
  4457. addExportedVariables(variables) {
  4458. this.argument.addExportedVariables(variables);
  4459. }
  4460. bind() {
  4461. super.bind();
  4462. if (this.declarationInit !== null) {
  4463. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  4464. }
  4465. }
  4466. declare(kind, init) {
  4467. this.declarationInit = init;
  4468. return this.argument.declare(kind, UNKNOWN_EXPRESSION);
  4469. }
  4470. deoptimizePath(path) {
  4471. path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
  4472. }
  4473. hasEffectsWhenAssignedAtPath(path, context) {
  4474. return path.length > 0 || this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context);
  4475. }
  4476. }
  4477. class FunctionNode extends NodeBase {
  4478. constructor() {
  4479. super(...arguments);
  4480. this.isPrototypeDeoptimized = false;
  4481. }
  4482. createScope(parentScope) {
  4483. this.scope = new FunctionScope(parentScope, this.context);
  4484. }
  4485. deoptimizePath(path) {
  4486. if (path.length === 1) {
  4487. if (path[0] === 'prototype') {
  4488. this.isPrototypeDeoptimized = true;
  4489. }
  4490. else if (path[0] === UnknownKey) {
  4491. this.isPrototypeDeoptimized = true;
  4492. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  4493. // which means the return expression needs to be reassigned as well
  4494. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  4495. }
  4496. }
  4497. }
  4498. getReturnExpressionWhenCalledAtPath(path) {
  4499. return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION;
  4500. }
  4501. hasEffects() {
  4502. return this.id !== null && this.id.hasEffects();
  4503. }
  4504. hasEffectsWhenAccessedAtPath(path) {
  4505. if (path.length <= 1)
  4506. return false;
  4507. return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
  4508. }
  4509. hasEffectsWhenAssignedAtPath(path) {
  4510. if (path.length <= 1) {
  4511. return false;
  4512. }
  4513. return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
  4514. }
  4515. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  4516. if (path.length > 0)
  4517. return true;
  4518. for (const param of this.params) {
  4519. if (param.hasEffects(context))
  4520. return true;
  4521. }
  4522. const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
  4523. context.replacedVariableInits.set(this.scope.thisVariable, callOptions.withNew ? new UnknownObjectExpression() : UNKNOWN_EXPRESSION);
  4524. const { brokenFlow, ignore } = context;
  4525. context.ignore = {
  4526. breaks: false,
  4527. continues: false,
  4528. labels: new Set(),
  4529. returnAwaitYield: true
  4530. };
  4531. if (this.body.hasEffects(context))
  4532. return true;
  4533. context.brokenFlow = brokenFlow;
  4534. if (thisInit) {
  4535. context.replacedVariableInits.set(this.scope.thisVariable, thisInit);
  4536. }
  4537. else {
  4538. context.replacedVariableInits.delete(this.scope.thisVariable);
  4539. }
  4540. context.ignore = ignore;
  4541. return false;
  4542. }
  4543. include(context, includeChildrenRecursively) {
  4544. this.included = true;
  4545. if (this.id)
  4546. this.id.include(context);
  4547. const hasArguments = this.scope.argumentsVariable.included;
  4548. for (const param of this.params) {
  4549. if (!(param instanceof Identifier$1) || hasArguments) {
  4550. param.include(context, includeChildrenRecursively);
  4551. }
  4552. }
  4553. const { brokenFlow } = context;
  4554. context.brokenFlow = BROKEN_FLOW_NONE;
  4555. this.body.include(context, includeChildrenRecursively);
  4556. context.brokenFlow = brokenFlow;
  4557. }
  4558. includeCallArguments(context, args) {
  4559. this.scope.includeCallArguments(context, args);
  4560. }
  4561. initialise() {
  4562. if (this.id !== null) {
  4563. this.id.declare('function', this);
  4564. }
  4565. this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
  4566. this.body.addImplicitReturnExpressionToScope();
  4567. }
  4568. parseNode(esTreeNode) {
  4569. this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
  4570. super.parseNode(esTreeNode);
  4571. }
  4572. }
  4573. FunctionNode.prototype.preventChildBlockScope = true;
  4574. class FunctionDeclaration extends FunctionNode {
  4575. initialise() {
  4576. super.initialise();
  4577. if (this.id !== null) {
  4578. this.id.variable.isId = true;
  4579. }
  4580. }
  4581. parseNode(esTreeNode) {
  4582. if (esTreeNode.id !== null) {
  4583. this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope
  4584. .parent);
  4585. }
  4586. super.parseNode(esTreeNode);
  4587. }
  4588. }
  4589. const WHITESPACE = /\s/;
  4590. // The header ends at the first non-white-space after "default"
  4591. function getDeclarationStart(code, start = 0) {
  4592. start = findFirstOccurrenceOutsideComment(code, 'default', start) + 7;
  4593. while (WHITESPACE.test(code[start]))
  4594. start++;
  4595. return start;
  4596. }
  4597. function getIdInsertPosition(code, declarationKeyword, start = 0) {
  4598. const declarationEnd = findFirstOccurrenceOutsideComment(code, declarationKeyword, start) + declarationKeyword.length;
  4599. code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, '{', declarationEnd));
  4600. const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
  4601. if (generatorStarPos === -1) {
  4602. return declarationEnd;
  4603. }
  4604. return declarationEnd + generatorStarPos + 1;
  4605. }
  4606. class ExportDefaultDeclaration extends NodeBase {
  4607. include(context, includeChildrenRecursively) {
  4608. super.include(context, includeChildrenRecursively);
  4609. if (includeChildrenRecursively) {
  4610. this.context.includeVariable(context, this.variable);
  4611. }
  4612. }
  4613. initialise() {
  4614. const declaration = this.declaration;
  4615. this.declarationName =
  4616. (declaration.id && declaration.id.name) || this.declaration.name;
  4617. this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
  4618. this.context.addExport(this);
  4619. }
  4620. render(code, options, nodeRenderOptions) {
  4621. const { start, end } = nodeRenderOptions;
  4622. const declarationStart = getDeclarationStart(code.original, this.start);
  4623. if (this.declaration instanceof FunctionDeclaration) {
  4624. this.renderNamedDeclaration(code, declarationStart, 'function', this.declaration.id === null, options);
  4625. }
  4626. else if (this.declaration instanceof ClassDeclaration) {
  4627. this.renderNamedDeclaration(code, declarationStart, 'class', this.declaration.id === null, options);
  4628. }
  4629. else if (this.variable.getOriginalVariable() !== this.variable) {
  4630. // Remove altogether to prevent re-declaring the same variable
  4631. if (options.format === 'system' && this.variable.exportName) {
  4632. code.overwrite(start, end, `exports('${this.variable.exportName}', ${this.variable.getName()});`);
  4633. }
  4634. else {
  4635. treeshakeNode(this, code, start, end);
  4636. }
  4637. return;
  4638. }
  4639. else if (this.variable.included) {
  4640. this.renderVariableDeclaration(code, declarationStart, options);
  4641. }
  4642. else {
  4643. code.remove(this.start, declarationStart);
  4644. this.declaration.render(code, options, {
  4645. isCalleeOfRenderedParent: false,
  4646. renderedParentType: ExpressionStatement
  4647. });
  4648. if (code.original[this.end - 1] !== ';') {
  4649. code.appendLeft(this.end, ';');
  4650. }
  4651. return;
  4652. }
  4653. this.declaration.render(code, options);
  4654. }
  4655. renderNamedDeclaration(code, declarationStart, declarationKeyword, needsId, options) {
  4656. const name = this.variable.getName();
  4657. // Remove `export default`
  4658. code.remove(this.start, declarationStart);
  4659. if (needsId) {
  4660. code.appendLeft(getIdInsertPosition(code.original, declarationKeyword, declarationStart), ` ${name}`);
  4661. }
  4662. if (options.format === 'system' &&
  4663. this.declaration instanceof ClassDeclaration &&
  4664. this.variable.exportName) {
  4665. code.appendLeft(this.end, ` exports('${this.variable.exportName}', ${name});`);
  4666. }
  4667. }
  4668. renderVariableDeclaration(code, declarationStart, options) {
  4669. const systemBinding = options.format === 'system' && this.variable.exportName
  4670. ? `exports('${this.variable.exportName}', `
  4671. : '';
  4672. code.overwrite(this.start, declarationStart, `${options.varOrConst} ${this.variable.getName()} = ${systemBinding}`);
  4673. const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
  4674. if (systemBinding) {
  4675. code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
  4676. }
  4677. else if (!hasTrailingSemicolon) {
  4678. code.appendLeft(this.end, ';');
  4679. }
  4680. }
  4681. }
  4682. ExportDefaultDeclaration.prototype.needsBoundaries = true;
  4683. class ExportDefaultVariable extends LocalVariable {
  4684. constructor(name, exportDefaultDeclaration, context) {
  4685. super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context);
  4686. this.hasId = false;
  4687. // Not initialised during construction
  4688. this.originalId = null;
  4689. this.originalVariable = null;
  4690. const declaration = exportDefaultDeclaration.declaration;
  4691. if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
  4692. declaration.id) {
  4693. this.hasId = true;
  4694. this.originalId = declaration.id;
  4695. }
  4696. else if (declaration instanceof Identifier$1) {
  4697. this.originalId = declaration;
  4698. }
  4699. }
  4700. addReference(identifier) {
  4701. if (!this.hasId) {
  4702. this.name = identifier.name;
  4703. }
  4704. }
  4705. getAssignedVariableName() {
  4706. return (this.originalId && this.originalId.name) || null;
  4707. }
  4708. getBaseVariableName() {
  4709. const original = this.getOriginalVariable();
  4710. if (original === this) {
  4711. return super.getBaseVariableName();
  4712. }
  4713. else {
  4714. return original.getBaseVariableName();
  4715. }
  4716. }
  4717. getName() {
  4718. const original = this.getOriginalVariable();
  4719. if (original === this) {
  4720. return super.getName();
  4721. }
  4722. else {
  4723. return original.getName();
  4724. }
  4725. }
  4726. getOriginalVariable() {
  4727. if (this.originalVariable === null) {
  4728. if (!this.originalId || (!this.hasId && this.originalId.variable.isReassigned)) {
  4729. this.originalVariable = this;
  4730. }
  4731. else {
  4732. const assignedOriginal = this.originalId.variable;
  4733. this.originalVariable =
  4734. assignedOriginal instanceof ExportDefaultVariable
  4735. ? assignedOriginal.getOriginalVariable()
  4736. : assignedOriginal;
  4737. }
  4738. }
  4739. return this.originalVariable;
  4740. }
  4741. setRenderNames(baseName, name) {
  4742. const original = this.getOriginalVariable();
  4743. if (original === this) {
  4744. super.setRenderNames(baseName, name);
  4745. }
  4746. else {
  4747. original.setRenderNames(baseName, name);
  4748. }
  4749. }
  4750. setSafeName(name) {
  4751. const original = this.getOriginalVariable();
  4752. if (original === this) {
  4753. super.setSafeName(name);
  4754. }
  4755. else {
  4756. original.setSafeName(name);
  4757. }
  4758. }
  4759. }
  4760. const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
  4761. const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
  4762. const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
  4763. class ExportShimVariable extends Variable {
  4764. constructor(module) {
  4765. super(MISSING_EXPORT_SHIM_VARIABLE);
  4766. this.module = module;
  4767. }
  4768. }
  4769. class NamespaceVariable extends Variable {
  4770. constructor(context, syntheticNamedExports) {
  4771. super(context.getModuleName());
  4772. this.memberVariables = Object.create(null);
  4773. this.containsExternalNamespace = false;
  4774. this.referencedEarly = false;
  4775. this.references = [];
  4776. this.context = context;
  4777. this.module = context.module;
  4778. this.syntheticNamedExports = syntheticNamedExports;
  4779. }
  4780. addReference(identifier) {
  4781. this.references.push(identifier);
  4782. this.name = identifier.name;
  4783. }
  4784. // This is only called if "UNKNOWN_PATH" is reassigned as in all other situations, either the
  4785. // build fails due to an illegal namespace reassignment or MemberExpression already forwards
  4786. // the reassignment to the right variable. This means we lost track of this variable and thus
  4787. // need to reassign all exports.
  4788. deoptimizePath() {
  4789. for (const key in this.memberVariables) {
  4790. this.memberVariables[key].deoptimizePath(UNKNOWN_PATH);
  4791. }
  4792. }
  4793. include(context) {
  4794. if (!this.included) {
  4795. if (this.containsExternalNamespace) {
  4796. return this.context.error({
  4797. code: 'NAMESPACE_CANNOT_CONTAIN_EXTERNAL',
  4798. id: this.module.id,
  4799. message: `Cannot create an explicit namespace object for module "${this.context.getModuleName()}" because it contains a reexported external namespace`
  4800. });
  4801. }
  4802. this.included = true;
  4803. for (const identifier of this.references) {
  4804. if (identifier.context.getModuleExecIndex() <= this.context.getModuleExecIndex()) {
  4805. this.referencedEarly = true;
  4806. break;
  4807. }
  4808. }
  4809. if (this.context.preserveModules) {
  4810. for (const memberName of Object.keys(this.memberVariables))
  4811. this.memberVariables[memberName].include(context);
  4812. }
  4813. else {
  4814. for (const memberName of Object.keys(this.memberVariables))
  4815. this.context.includeVariable(context, this.memberVariables[memberName]);
  4816. }
  4817. }
  4818. }
  4819. initialise() {
  4820. for (const name of this.context.getExports().concat(this.context.getReexports())) {
  4821. if (name[0] === '*' && name.length > 1)
  4822. this.containsExternalNamespace = true;
  4823. this.memberVariables[name] = this.context.traceExport(name);
  4824. }
  4825. }
  4826. renderBlock(options) {
  4827. const _ = options.compact ? '' : ' ';
  4828. const n = options.compact ? '' : '\n';
  4829. const t = options.indent;
  4830. const members = Object.keys(this.memberVariables).map(name => {
  4831. const original = this.memberVariables[name];
  4832. if (this.referencedEarly || original.isReassigned) {
  4833. return `${t}get ${name}${_}()${_}{${_}return ${original.getName()}${options.compact ? '' : ';'}${_}}`;
  4834. }
  4835. const safeName = RESERVED_NAMES[name] ? `'${name}'` : name;
  4836. return `${t}${safeName}: ${original.getName()}`;
  4837. });
  4838. members.unshift(`${t}__proto__:${_}null`);
  4839. if (options.namespaceToStringTag) {
  4840. members.unshift(`${t}[Symbol.toStringTag]:${_}'Module'`);
  4841. }
  4842. const name = this.getName();
  4843. let output = `{${n}${members.join(`,${n}`)}${n}}`;
  4844. if (this.syntheticNamedExports) {
  4845. output = `/*#__PURE__*/Object.assign(${output}, ${this.module.getDefaultExport().getName()})`;
  4846. }
  4847. if (options.freeze) {
  4848. output = `/*#__PURE__*/Object.freeze(${output})`;
  4849. }
  4850. output = `${options.varOrConst} ${name}${_}=${_}${output};`;
  4851. if (options.format === 'system' && this.exportName) {
  4852. output += `${n}exports('${this.exportName}',${_}${name});`;
  4853. }
  4854. return output;
  4855. }
  4856. renderFirst() {
  4857. return this.referencedEarly;
  4858. }
  4859. }
  4860. NamespaceVariable.prototype.isNamespace = true;
  4861. const esModuleExport = `Object.defineProperty(exports, '__esModule', { value: true });`;
  4862. const compactEsModuleExport = `Object.defineProperty(exports,'__esModule',{value:true});`;
  4863. function getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, mechanism = 'return ') {
  4864. const _ = compact ? '' : ' ';
  4865. const n = compact ? '' : '\n';
  4866. if (!namedExportsMode) {
  4867. let local;
  4868. if (exports.length > 0) {
  4869. local = exports[0].local;
  4870. }
  4871. else {
  4872. for (const dep of dependencies) {
  4873. if (dep.reexports) {
  4874. const expt = dep.reexports[0];
  4875. local =
  4876. dep.namedExportsMode && expt.imported !== '*' && expt.imported !== 'default'
  4877. ? `${dep.name}.${expt.imported}`
  4878. : dep.name;
  4879. break;
  4880. }
  4881. }
  4882. }
  4883. return `${mechanism}${local};`;
  4884. }
  4885. let exportBlock = '';
  4886. // star exports must always output first for precedence
  4887. for (const { name, reexports } of dependencies) {
  4888. if (reexports && namedExportsMode) {
  4889. for (const specifier of reexports) {
  4890. if (specifier.reexported === '*') {
  4891. if (exportBlock)
  4892. exportBlock += n;
  4893. if (specifier.needsLiveBinding) {
  4894. exportBlock +=
  4895. `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
  4896. `${t}if${_}(k${_}!==${_}'default')${_}Object.defineProperty(exports,${_}k,${_}{${n}` +
  4897. `${t}${t}enumerable:${_}true,${n}` +
  4898. `${t}${t}get:${_}function${_}()${_}{${n}` +
  4899. `${t}${t}${t}return ${name}[k];${n}` +
  4900. `${t}${t}}${n}${t}});${n}});`;
  4901. }
  4902. else {
  4903. exportBlock +=
  4904. `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
  4905. `${t}if${_}(k${_}!==${_}'default')${_}exports[k]${_}=${_}${name}[k];${n}});`;
  4906. }
  4907. }
  4908. }
  4909. }
  4910. }
  4911. for (const { name, imports, reexports, isChunk, namedExportsMode: depNamedExportsMode, exportsNames } of dependencies) {
  4912. if (reexports && namedExportsMode) {
  4913. for (const specifier of reexports) {
  4914. if (specifier.imported === 'default' && !isChunk) {
  4915. if (exportBlock)
  4916. exportBlock += n;
  4917. if (exportsNames &&
  4918. (reexports.some(specifier => specifier.imported === 'default'
  4919. ? specifier.reexported === 'default'
  4920. : specifier.imported !== '*') ||
  4921. (imports && imports.some(specifier => specifier.imported !== 'default')))) {
  4922. exportBlock += `exports.${specifier.reexported}${_}=${_}${name}${interop !== false ? '__default' : '.default'};`;
  4923. }
  4924. else {
  4925. exportBlock += `exports.${specifier.reexported}${_}=${_}${name};`;
  4926. }
  4927. }
  4928. else if (specifier.imported !== '*') {
  4929. if (exportBlock)
  4930. exportBlock += n;
  4931. const importName = specifier.imported === 'default' && !depNamedExportsMode
  4932. ? name
  4933. : `${name}.${specifier.imported}`;
  4934. exportBlock += specifier.needsLiveBinding
  4935. ? `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` +
  4936. `${t}enumerable:${_}true,${n}` +
  4937. `${t}get:${_}function${_}()${_}{${n}` +
  4938. `${t}${t}return ${importName};${n}${t}}${n}});`
  4939. : `exports.${specifier.reexported}${_}=${_}${importName};`;
  4940. }
  4941. else if (specifier.reexported !== '*') {
  4942. if (exportBlock)
  4943. exportBlock += n;
  4944. exportBlock += `exports.${specifier.reexported}${_}=${_}${name};`;
  4945. }
  4946. }
  4947. }
  4948. }
  4949. for (const expt of exports) {
  4950. const lhs = `exports.${expt.exported}`;
  4951. const rhs = expt.local;
  4952. if (lhs !== rhs) {
  4953. if (exportBlock)
  4954. exportBlock += n;
  4955. exportBlock += `${lhs}${_}=${_}${rhs};`;
  4956. }
  4957. }
  4958. return exportBlock;
  4959. }
  4960. function getInteropBlock(dependencies, options, varOrConst) {
  4961. const _ = options.compact ? '' : ' ';
  4962. return dependencies
  4963. .map(({ name, exportsNames, exportsDefault, namedExportsMode }) => {
  4964. if (!namedExportsMode || !exportsDefault || options.interop === false)
  4965. return null;
  4966. if (exportsNames) {
  4967. return (`${varOrConst} ${name}__default${_}=${_}'default'${_}in ${name}${_}?` +
  4968. `${_}${name}['default']${_}:${_}${name};`);
  4969. }
  4970. return (`${name}${_}=${_}${name}${_}&&${_}Object.prototype.hasOwnProperty.call(${name},${_}'default')${_}?` +
  4971. `${_}${name}['default']${_}:${_}${name};`);
  4972. })
  4973. .filter(Boolean)
  4974. .join(options.compact ? '' : '\n');
  4975. }
  4976. function copyPropertyLiveBinding(_, n, t, i) {
  4977. return (`${i}var d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  4978. `${i}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  4979. `${i}${t}enumerable:${_}true,${n}` +
  4980. `${i}${t}get:${_}function${_}()${_}{${n}` +
  4981. `${i}${t}${t}return e[k];${n}` +
  4982. `${i}${t}}${n}` +
  4983. `${i}});${n}`);
  4984. }
  4985. function copyPropertyStatic(_, n, _t, i) {
  4986. return `${i}n[k]${_}=e${_}[k];${n}`;
  4987. }
  4988. function getInteropNamespace(_, n, t, liveBindings) {
  4989. return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
  4990. `${t}if${_}(e${_}&&${_}e.__esModule)${_}{${_}return e;${_}}${_}else${_}{${n}` +
  4991. `${t}${t}var n${_}=${_}{};${n}` +
  4992. `${t}${t}if${_}(e)${_}{${n}` +
  4993. `${t}${t}${t}Object.keys(e).forEach(function${_}(k)${_}{${n}` +
  4994. (liveBindings ? copyPropertyLiveBinding : copyPropertyStatic)(_, n, t, t + t + t + t) +
  4995. `${t}${t}${t}});${n}` +
  4996. `${t}${t}}${n}` +
  4997. `${t}${t}n['default']${_}=${_}e;${n}` +
  4998. `${t}${t}return n;${n}` +
  4999. `${t}}${n}` +
  5000. `}${n}${n}`);
  5001. }
  5002. const builtins$1 = {
  5003. assert: true,
  5004. buffer: true,
  5005. console: true,
  5006. constants: true,
  5007. domain: true,
  5008. events: true,
  5009. http: true,
  5010. https: true,
  5011. os: true,
  5012. path: true,
  5013. process: true,
  5014. punycode: true,
  5015. querystring: true,
  5016. stream: true,
  5017. string_decoder: true,
  5018. timers: true,
  5019. tty: true,
  5020. url: true,
  5021. util: true,
  5022. vm: true,
  5023. zlib: true
  5024. };
  5025. // Creating a browser chunk that depends on Node.js built-in modules ('util'). You might need to include https://www.npmjs.com/package/rollup-plugin-node-builtins
  5026. function warnOnBuiltins(warn, dependencies) {
  5027. const externalBuiltins = dependencies.map(({ id }) => id).filter(id => id in builtins$1);
  5028. if (!externalBuiltins.length)
  5029. return;
  5030. const detail = externalBuiltins.length === 1
  5031. ? `module ('${externalBuiltins[0]}')`
  5032. : `modules (${externalBuiltins
  5033. .slice(0, -1)
  5034. .map(name => `'${name}'`)
  5035. .join(', ')} and '${externalBuiltins.slice(-1)}')`;
  5036. warn({
  5037. code: 'MISSING_NODE_BUILTINS',
  5038. message: `Creating a browser bundle that depends on Node.js built-in ${detail}. You might need to include https://www.npmjs.com/package/rollup-plugin-node-builtins`,
  5039. modules: externalBuiltins
  5040. });
  5041. }
  5042. // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
  5043. // The assumption is that this makes sense for all relative ids:
  5044. // https://requirejs.org/docs/api.html#jsfiles
  5045. function removeExtensionFromRelativeAmdId(id) {
  5046. if (id[0] === '.' && id.endsWith('.js')) {
  5047. return id.slice(0, -3);
  5048. }
  5049. return id;
  5050. }
  5051. function amd(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, isEntryModuleFacade, namedExportsMode, outro, varOrConst, warn }, options) {
  5052. warnOnBuiltins(warn, dependencies);
  5053. const deps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
  5054. const args = dependencies.map(m => m.name);
  5055. const n = options.compact ? '' : '\n';
  5056. const _ = options.compact ? '' : ' ';
  5057. if (namedExportsMode && hasExports) {
  5058. args.unshift(`exports`);
  5059. deps.unshift(`'exports'`);
  5060. }
  5061. if (accessedGlobals.has('require')) {
  5062. args.unshift('require');
  5063. deps.unshift(`'require'`);
  5064. }
  5065. if (accessedGlobals.has('module')) {
  5066. args.unshift('module');
  5067. deps.unshift(`'module'`);
  5068. }
  5069. const amdOptions = options.amd || {};
  5070. const params = (amdOptions.id ? `'${amdOptions.id}',${_}` : ``) +
  5071. (deps.length ? `[${deps.join(`,${_}`)}],${_}` : ``);
  5072. const useStrict = options.strict !== false ? `${_}'use strict';` : ``;
  5073. const define = amdOptions.define || 'define';
  5074. const wrapperStart = `${define}(${params}function${_}(${args.join(`,${_}`)})${_}{${useStrict}${n}${n}`;
  5075. // var foo__default = 'default' in foo ? foo['default'] : foo;
  5076. const interopBlock = getInteropBlock(dependencies, options, varOrConst);
  5077. if (interopBlock) {
  5078. magicString.prepend(interopBlock + n + n);
  5079. }
  5080. if (accessedGlobals.has(INTEROP_NAMESPACE_VARIABLE)) {
  5081. magicString.prepend(getInteropNamespace(_, n, t, options.externalLiveBindings !== false));
  5082. }
  5083. if (intro)
  5084. magicString.prepend(intro);
  5085. const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t);
  5086. if (exportBlock)
  5087. magicString.append(n + n + exportBlock);
  5088. if (namedExportsMode && hasExports && isEntryModuleFacade && options.esModule)
  5089. magicString.append(`${n}${n}${options.compact ? compactEsModuleExport : esModuleExport}`);
  5090. if (outro)
  5091. magicString.append(outro);
  5092. return magicString
  5093. .indent(t)
  5094. .append(n + n + '});')
  5095. .prepend(wrapperStart);
  5096. }
  5097. function cjs(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, isEntryModuleFacade, namedExportsMode, outro, varOrConst }, options) {
  5098. const n = options.compact ? '' : '\n';
  5099. const _ = options.compact ? '' : ' ';
  5100. intro =
  5101. (options.strict === false ? intro : `'use strict';${n}${n}${intro}`) +
  5102. (namedExportsMode && hasExports && isEntryModuleFacade && options.esModule
  5103. ? `${options.compact ? compactEsModuleExport : esModuleExport}${n}${n}`
  5104. : '');
  5105. let needsInterop = false;
  5106. const interop = options.interop !== false;
  5107. let importBlock;
  5108. let definingVariable = false;
  5109. importBlock = '';
  5110. for (const { id, namedExportsMode, isChunk, name, reexports, imports, exportsNames, exportsDefault } of dependencies) {
  5111. if (!reexports && !imports) {
  5112. if (importBlock) {
  5113. importBlock += !options.compact || definingVariable ? `;${n}` : ',';
  5114. }
  5115. definingVariable = false;
  5116. importBlock += `require('${id}')`;
  5117. }
  5118. else {
  5119. importBlock +=
  5120. options.compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${varOrConst} `;
  5121. definingVariable = true;
  5122. if (!interop || isChunk || !exportsDefault || !namedExportsMode) {
  5123. importBlock += `${name}${_}=${_}require('${id}')`;
  5124. }
  5125. else {
  5126. needsInterop = true;
  5127. if (exportsNames)
  5128. importBlock += `${name}${_}=${_}require('${id}')${options.compact ? ',' : `;\n${varOrConst} `}${name}__default${_}=${_}${INTEROP_DEFAULT_VARIABLE}(${name})`;
  5129. else
  5130. importBlock += `${name}${_}=${_}${INTEROP_DEFAULT_VARIABLE}(require('${id}'))`;
  5131. }
  5132. }
  5133. }
  5134. if (importBlock)
  5135. importBlock += ';';
  5136. if (needsInterop) {
  5137. const ex = options.compact ? 'e' : 'ex';
  5138. intro +=
  5139. `function ${INTEROP_DEFAULT_VARIABLE}${_}(${ex})${_}{${_}return${_}` +
  5140. `(${ex}${_}&&${_}(typeof ${ex}${_}===${_}'object')${_}&&${_}'default'${_}in ${ex})${_}` +
  5141. `?${_}${ex}['default']${_}:${_}${ex}${options.compact ? '' : '; '}}${n}${n}`;
  5142. }
  5143. if (accessedGlobals.has(INTEROP_NAMESPACE_VARIABLE)) {
  5144. intro += getInteropNamespace(_, n, t, options.externalLiveBindings !== false);
  5145. }
  5146. if (importBlock)
  5147. intro += importBlock + n + n;
  5148. const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t, `module.exports${_}=${_}`);
  5149. magicString.prepend(intro);
  5150. if (exportBlock)
  5151. magicString.append(n + n + exportBlock);
  5152. if (outro)
  5153. magicString.append(outro);
  5154. return magicString;
  5155. }
  5156. function esm(magicString, { intro, outro, dependencies, exports }, options) {
  5157. const _ = options.compact ? '' : ' ';
  5158. const n = options.compact ? '' : '\n';
  5159. const importBlock = getImportBlock(dependencies, _);
  5160. if (importBlock.length > 0)
  5161. intro += importBlock.join(n) + n + n;
  5162. if (intro)
  5163. magicString.prepend(intro);
  5164. const exportBlock = getExportBlock$1(exports, _);
  5165. if (exportBlock.length)
  5166. magicString.append(n + n + exportBlock.join(n).trim());
  5167. if (outro)
  5168. magicString.append(outro);
  5169. return magicString.trim();
  5170. }
  5171. function getImportBlock(dependencies, _) {
  5172. const importBlock = [];
  5173. for (const { id, reexports, imports, name } of dependencies) {
  5174. if (!reexports && !imports) {
  5175. importBlock.push(`import${_}'${id}';`);
  5176. continue;
  5177. }
  5178. if (imports) {
  5179. let defaultImport = null;
  5180. let starImport = null;
  5181. const importedNames = [];
  5182. for (const specifier of imports) {
  5183. if (specifier.imported === 'default') {
  5184. defaultImport = specifier;
  5185. }
  5186. else if (specifier.imported === '*') {
  5187. starImport = specifier;
  5188. }
  5189. else {
  5190. importedNames.push(specifier);
  5191. }
  5192. }
  5193. if (starImport) {
  5194. importBlock.push(`import${_}*${_}as ${starImport.local} from${_}'${id}';`);
  5195. }
  5196. if (defaultImport && importedNames.length === 0) {
  5197. importBlock.push(`import ${defaultImport.local} from${_}'${id}';`);
  5198. }
  5199. else if (importedNames.length > 0) {
  5200. importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
  5201. .map(specifier => {
  5202. if (specifier.imported === specifier.local) {
  5203. return specifier.imported;
  5204. }
  5205. else {
  5206. return `${specifier.imported} as ${specifier.local}`;
  5207. }
  5208. })
  5209. .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
  5210. }
  5211. }
  5212. if (reexports) {
  5213. let starExport = null;
  5214. const namespaceReexports = [];
  5215. const namedReexports = [];
  5216. for (const specifier of reexports) {
  5217. if (specifier.reexported === '*') {
  5218. starExport = specifier;
  5219. }
  5220. else if (specifier.imported === '*') {
  5221. namespaceReexports.push(specifier);
  5222. }
  5223. else {
  5224. namedReexports.push(specifier);
  5225. }
  5226. }
  5227. if (starExport) {
  5228. importBlock.push(`export${_}*${_}from${_}'${id}';`);
  5229. }
  5230. if (namespaceReexports.length > 0) {
  5231. if (!imports ||
  5232. !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
  5233. importBlock.push(`import${_}*${_}as ${name} from${_}'${id}';`);
  5234. }
  5235. for (const specifier of namespaceReexports) {
  5236. importBlock.push(`export${_}{${_}${name === specifier.reexported ? name : `${name} as ${specifier.reexported}`} };`);
  5237. }
  5238. }
  5239. if (namedReexports.length > 0) {
  5240. importBlock.push(`export${_}{${_}${namedReexports
  5241. .map(specifier => {
  5242. if (specifier.imported === specifier.reexported) {
  5243. return specifier.imported;
  5244. }
  5245. else {
  5246. return `${specifier.imported} as ${specifier.reexported}`;
  5247. }
  5248. })
  5249. .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
  5250. }
  5251. }
  5252. }
  5253. return importBlock;
  5254. }
  5255. function getExportBlock$1(exports, _) {
  5256. const exportBlock = [];
  5257. const exportDeclaration = [];
  5258. for (const specifier of exports) {
  5259. if (specifier.exported === 'default') {
  5260. exportBlock.push(`export default ${specifier.local};`);
  5261. }
  5262. else {
  5263. exportDeclaration.push(specifier.exported === specifier.local
  5264. ? specifier.local
  5265. : `${specifier.local} as ${specifier.exported}`);
  5266. }
  5267. }
  5268. if (exportDeclaration.length) {
  5269. exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
  5270. }
  5271. return exportBlock;
  5272. }
  5273. function spaces(i) {
  5274. let result = '';
  5275. while (i--)
  5276. result += ' ';
  5277. return result;
  5278. }
  5279. function tabsToSpaces(str) {
  5280. return str.replace(/^\t+/, match => match.split('\t').join(' '));
  5281. }
  5282. function getCodeFrame(source, line, column) {
  5283. let lines = source.split('\n');
  5284. const frameStart = Math.max(0, line - 3);
  5285. let frameEnd = Math.min(line + 2, lines.length);
  5286. lines = lines.slice(frameStart, frameEnd);
  5287. while (!/\S/.test(lines[lines.length - 1])) {
  5288. lines.pop();
  5289. frameEnd -= 1;
  5290. }
  5291. const digits = String(frameEnd).length;
  5292. return lines
  5293. .map((str, i) => {
  5294. const isErrorLine = frameStart + i + 1 === line;
  5295. let lineNum = String(i + frameStart + 1);
  5296. while (lineNum.length < digits)
  5297. lineNum = ` ${lineNum}`;
  5298. if (isErrorLine) {
  5299. const indicator = spaces(digits + 2 + tabsToSpaces(str.slice(0, column)).length) + '^';
  5300. return `${lineNum}: ${tabsToSpaces(str)}\n${indicator}`;
  5301. }
  5302. return `${lineNum}: ${tabsToSpaces(str)}`;
  5303. })
  5304. .join('\n');
  5305. }
  5306. function sanitizeFileName(name) {
  5307. return name.replace(/[\0?*]/g, '_');
  5308. }
  5309. function getAliasName(id) {
  5310. const base = path.basename(id);
  5311. return base.substr(0, base.length - path.extname(id).length);
  5312. }
  5313. function relativeId(id) {
  5314. if (typeof process === 'undefined' || !isAbsolute(id))
  5315. return id;
  5316. return path.relative(process.cwd(), id);
  5317. }
  5318. function isPlainPathFragment(name) {
  5319. // not starting with "/", "./", "../"
  5320. return (name[0] !== '/' &&
  5321. !(name[0] === '.' && (name[1] === '/' || name[1] === '.')) &&
  5322. sanitizeFileName(name) === name);
  5323. }
  5324. function error(base, props) {
  5325. if (!(base instanceof Error))
  5326. base = Object.assign(new Error(base.message), base);
  5327. if (props)
  5328. Object.assign(base, props);
  5329. throw base;
  5330. }
  5331. function augmentCodeLocation(object, pos, source, id) {
  5332. if (typeof pos === 'object') {
  5333. const { line, column } = pos;
  5334. object.loc = { file: id, line, column };
  5335. }
  5336. else {
  5337. object.pos = pos;
  5338. const { line, column } = locate(source, pos, { offsetLine: 1 });
  5339. object.loc = { file: id, line, column };
  5340. }
  5341. if (object.frame === undefined) {
  5342. const { line, column } = object.loc;
  5343. object.frame = getCodeFrame(source, line, column);
  5344. }
  5345. }
  5346. var Errors;
  5347. (function (Errors) {
  5348. Errors["ASSET_NOT_FINALISED"] = "ASSET_NOT_FINALISED";
  5349. Errors["ASSET_NOT_FOUND"] = "ASSET_NOT_FOUND";
  5350. Errors["ASSET_SOURCE_ALREADY_SET"] = "ASSET_SOURCE_ALREADY_SET";
  5351. Errors["ASSET_SOURCE_MISSING"] = "ASSET_SOURCE_MISSING";
  5352. Errors["BAD_LOADER"] = "BAD_LOADER";
  5353. Errors["CANNOT_EMIT_FROM_OPTIONS_HOOK"] = "CANNOT_EMIT_FROM_OPTIONS_HOOK";
  5354. Errors["CHUNK_NOT_GENERATED"] = "CHUNK_NOT_GENERATED";
  5355. Errors["DEPRECATED_FEATURE"] = "DEPRECATED_FEATURE";
  5356. Errors["FILE_NOT_FOUND"] = "FILE_NOT_FOUND";
  5357. Errors["FILE_NAME_CONFLICT"] = "FILE_NAME_CONFLICT";
  5358. Errors["INPUT_HOOK_IN_OUTPUT_PLUGIN"] = "INPUT_HOOK_IN_OUTPUT_PLUGIN";
  5359. Errors["INVALID_CHUNK"] = "INVALID_CHUNK";
  5360. Errors["INVALID_EXPORT_OPTION"] = "INVALID_EXPORT_OPTION";
  5361. Errors["INVALID_EXTERNAL_ID"] = "INVALID_EXTERNAL_ID";
  5362. Errors["INVALID_OPTION"] = "INVALID_OPTION";
  5363. Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK";
  5364. Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE";
  5365. Errors["MIXED_EXPORTS"] = "MIXED_EXPORTS";
  5366. Errors["NAMESPACE_CONFLICT"] = "NAMESPACE_CONFLICT";
  5367. Errors["PLUGIN_ERROR"] = "PLUGIN_ERROR";
  5368. Errors["UNRESOLVED_ENTRY"] = "UNRESOLVED_ENTRY";
  5369. Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT";
  5370. Errors["VALIDATION_ERROR"] = "VALIDATION_ERROR";
  5371. Errors["EXTERNAL_SYNTHETIC_EXPORTS"] = "EXTERNAL_SYNTHETIC_EXPORTS";
  5372. Errors["SYNTHETIC_NAMED_EXPORTS_NEED_DEFAULT"] = "SYNTHETIC_NAMED_EXPORTS_NEED_DEFAULT";
  5373. })(Errors || (Errors = {}));
  5374. function errAssetNotFinalisedForFileName(name) {
  5375. return {
  5376. code: Errors.ASSET_NOT_FINALISED,
  5377. message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first.`
  5378. };
  5379. }
  5380. function errCannotEmitFromOptionsHook() {
  5381. return {
  5382. code: Errors.CANNOT_EMIT_FROM_OPTIONS_HOOK,
  5383. message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.`
  5384. };
  5385. }
  5386. function errChunkNotGeneratedForFileName(name) {
  5387. return {
  5388. code: Errors.CHUNK_NOT_GENERATED,
  5389. message: `Plugin error - Unable to get file name for chunk "${name}". Ensure that generate is called first.`
  5390. };
  5391. }
  5392. function errAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
  5393. return {
  5394. code: Errors.ASSET_NOT_FOUND,
  5395. message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".`
  5396. };
  5397. }
  5398. function errAssetSourceAlreadySet(name) {
  5399. return {
  5400. code: Errors.ASSET_SOURCE_ALREADY_SET,
  5401. message: `Unable to set the source for asset "${name}", source already set.`
  5402. };
  5403. }
  5404. function errNoAssetSourceSet(assetName) {
  5405. return {
  5406. code: Errors.ASSET_SOURCE_MISSING,
  5407. message: `Plugin error creating asset "${assetName}" - no asset source set.`
  5408. };
  5409. }
  5410. function errBadLoader(id) {
  5411. return {
  5412. code: Errors.BAD_LOADER,
  5413. message: `Error loading ${relativeId(id)}: plugin load hook should return a string, a { code, map } object, or nothing/null`
  5414. };
  5415. }
  5416. function errDeprecation(deprecation) {
  5417. return Object.assign({ code: Errors.DEPRECATED_FEATURE }, (typeof deprecation === 'string' ? { message: deprecation } : deprecation));
  5418. }
  5419. function errFileReferenceIdNotFoundForFilename(assetReferenceId) {
  5420. return {
  5421. code: Errors.FILE_NOT_FOUND,
  5422. message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
  5423. };
  5424. }
  5425. function errFileNameConflict(fileName) {
  5426. return {
  5427. code: Errors.FILE_NAME_CONFLICT,
  5428. message: `The emitted file "${fileName}" overwrites a previously emitted file of the same name.`
  5429. };
  5430. }
  5431. function errInputHookInOutputPlugin(pluginName, hookName) {
  5432. return {
  5433. code: Errors.INPUT_HOOK_IN_OUTPUT_PLUGIN,
  5434. 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.`
  5435. };
  5436. }
  5437. function errCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
  5438. return {
  5439. code: Errors.INVALID_CHUNK,
  5440. message: `Cannot assign ${relativeId(moduleId)} to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
  5441. };
  5442. }
  5443. function errInvalidExportOptionValue(optionValue) {
  5444. return {
  5445. code: Errors.INVALID_EXPORT_OPTION,
  5446. message: `"output.exports" must be "default", "named", "none", "auto", or left unspecified (defaults to "auto"), received "${optionValue}"`,
  5447. url: `https://rollupjs.org/guide/en/#output-exports`
  5448. };
  5449. }
  5450. function errIncompatibleExportOptionValue(optionValue, keys, entryModule) {
  5451. return {
  5452. code: 'INVALID_EXPORT_OPTION',
  5453. message: `"${optionValue}" was specified for "output.exports", but entry module "${relativeId(entryModule)}" has the following exports: ${keys.join(', ')}`
  5454. };
  5455. }
  5456. function errInternalIdCannotBeExternal(source, importer) {
  5457. return {
  5458. code: Errors.INVALID_EXTERNAL_ID,
  5459. message: `'${source}' is imported as an external by ${relativeId(importer)}, but is already an existing non-external module id.`
  5460. };
  5461. }
  5462. function errInvalidOption(option, explanation) {
  5463. return {
  5464. code: Errors.INVALID_OPTION,
  5465. message: `Invalid value for option "${option}" - ${explanation}.`
  5466. };
  5467. }
  5468. function errInvalidRollupPhaseForAddWatchFile() {
  5469. return {
  5470. code: Errors.INVALID_ROLLUP_PHASE,
  5471. message: `Cannot call addWatchFile after the build has finished.`
  5472. };
  5473. }
  5474. function errInvalidRollupPhaseForChunkEmission() {
  5475. return {
  5476. code: Errors.INVALID_ROLLUP_PHASE,
  5477. message: `Cannot emit chunks after module loading has finished.`
  5478. };
  5479. }
  5480. function errMixedExport(facadeModuleId, name) {
  5481. return {
  5482. code: Errors.MIXED_EXPORTS,
  5483. id: facadeModuleId,
  5484. message: `Entry module "${relativeId(facadeModuleId)}" is using named and default exports together. Consumers of your bundle will have to use \`${name ||
  5485. 'chunk'}["default"]\` to access the default export, which may not be what you want. Use \`output.exports: "named"\` to disable this warning`,
  5486. url: `https://rollupjs.org/guide/en/#output-exports`
  5487. };
  5488. }
  5489. function errNamespaceConflict(name, reexportingModule, additionalExportAllModule) {
  5490. return {
  5491. code: Errors.NAMESPACE_CONFLICT,
  5492. message: `Conflicting namespaces: ${relativeId(reexportingModule.id)} re-exports '${name}' from both ${relativeId(reexportingModule.exportsAll[name])} and ${relativeId(additionalExportAllModule.exportsAll[name])} (will be ignored)`,
  5493. name,
  5494. reexporter: reexportingModule.id,
  5495. sources: [reexportingModule.exportsAll[name], additionalExportAllModule.exportsAll[name]]
  5496. };
  5497. }
  5498. function errEntryCannotBeExternal(unresolvedId) {
  5499. return {
  5500. code: Errors.UNRESOLVED_ENTRY,
  5501. message: `Entry module cannot be external (${relativeId(unresolvedId)}).`
  5502. };
  5503. }
  5504. function errUnresolvedEntry(unresolvedId) {
  5505. return {
  5506. code: Errors.UNRESOLVED_ENTRY,
  5507. message: `Could not resolve entry module (${relativeId(unresolvedId)}).`
  5508. };
  5509. }
  5510. function errUnresolvedImport(source, importer) {
  5511. return {
  5512. code: Errors.UNRESOLVED_IMPORT,
  5513. message: `Could not resolve '${source}' from ${relativeId(importer)}`
  5514. };
  5515. }
  5516. function errUnresolvedImportTreatedAsExternal(source, importer) {
  5517. return {
  5518. code: Errors.UNRESOLVED_IMPORT,
  5519. importer: relativeId(importer),
  5520. message: `'${source}' is imported by ${relativeId(importer)}, but could not be resolved – treating it as an external dependency`,
  5521. source,
  5522. url: 'https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency'
  5523. };
  5524. }
  5525. function errExternalSyntheticExports(source, importer) {
  5526. return {
  5527. code: Errors.EXTERNAL_SYNTHETIC_EXPORTS,
  5528. importer: relativeId(importer),
  5529. message: `External '${source}' can not have 'syntheticNamedExports' enabled.`,
  5530. source
  5531. };
  5532. }
  5533. function errFailedValidation(message) {
  5534. return {
  5535. code: Errors.VALIDATION_ERROR,
  5536. message
  5537. };
  5538. }
  5539. // Generate strings which dereference dotted properties, but use array notation `['prop-deref']`
  5540. // if the property name isn't trivial
  5541. const shouldUseDot = /^[a-zA-Z$_][a-zA-Z0-9$_]*$/;
  5542. function property(prop) {
  5543. return shouldUseDot.test(prop) ? `.${prop}` : `['${prop}']`;
  5544. }
  5545. function keypath(keypath) {
  5546. return keypath
  5547. .split('.')
  5548. .map(property)
  5549. .join('');
  5550. }
  5551. function setupNamespace(name, root, globals, compact) {
  5552. const parts = name.split('.');
  5553. if (globals) {
  5554. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  5555. }
  5556. const _ = compact ? '' : ' ';
  5557. parts.pop();
  5558. let acc = root;
  5559. return (parts
  5560. .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}${compact ? '' : ';'}`))
  5561. .join(compact ? ',' : '\n') + (compact && parts.length ? ';' : '\n'));
  5562. }
  5563. function assignToDeepVariable(deepName, root, globals, compact, assignment) {
  5564. const _ = compact ? '' : ' ';
  5565. const parts = deepName.split('.');
  5566. if (globals) {
  5567. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  5568. }
  5569. const last = parts.pop();
  5570. let acc = root;
  5571. let deepAssignment = parts
  5572. .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}`))
  5573. .concat(`${acc}${property(last)}`)
  5574. .join(`,${_}`)
  5575. .concat(`${_}=${_}${assignment}`);
  5576. if (parts.length > 0) {
  5577. deepAssignment = `(${deepAssignment})`;
  5578. }
  5579. return deepAssignment;
  5580. }
  5581. function trimEmptyImports(dependencies) {
  5582. let i = dependencies.length;
  5583. while (i--) {
  5584. const dependency = dependencies[i];
  5585. if (dependency.exportsDefault || dependency.exportsNames) {
  5586. return dependencies.slice(0, i + 1);
  5587. }
  5588. }
  5589. return [];
  5590. }
  5591. const thisProp = (name) => `this${keypath(name)}`;
  5592. function iife(magicString, { dependencies, exports, hasExports, indentString: t, intro, namedExportsMode, outro, varOrConst, warn }, options) {
  5593. const _ = options.compact ? '' : ' ';
  5594. const n = options.compact ? '' : '\n';
  5595. const { extend, name } = options;
  5596. const isNamespaced = name && name.indexOf('.') !== -1;
  5597. const useVariableAssignment = !extend && !isNamespaced;
  5598. if (name && useVariableAssignment && !isLegal(name)) {
  5599. return error({
  5600. code: 'ILLEGAL_IDENTIFIER_AS_NAME',
  5601. message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".`
  5602. });
  5603. }
  5604. warnOnBuiltins(warn, dependencies);
  5605. const external = trimEmptyImports(dependencies);
  5606. const deps = external.map(dep => dep.globalName || 'null');
  5607. const args = external.map(m => m.name);
  5608. if (hasExports && !name) {
  5609. warn({
  5610. code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
  5611. message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.`
  5612. });
  5613. }
  5614. if (namedExportsMode && hasExports) {
  5615. if (extend) {
  5616. deps.unshift(`${thisProp(name)}${_}=${_}${thisProp(name)}${_}||${_}{}`);
  5617. args.unshift('exports');
  5618. }
  5619. else {
  5620. deps.unshift('{}');
  5621. args.unshift('exports');
  5622. }
  5623. }
  5624. const useStrict = options.strict !== false ? `${t}'use strict';${n}${n}` : ``;
  5625. let wrapperIntro = `(function${_}(${args.join(`,${_}`)})${_}{${n}${useStrict}`;
  5626. if (hasExports && (!extend || !namedExportsMode) && name) {
  5627. wrapperIntro =
  5628. (useVariableAssignment ? `${varOrConst} ${name}` : thisProp(name)) +
  5629. `${_}=${_}${wrapperIntro}`;
  5630. }
  5631. if (isNamespaced && hasExports) {
  5632. wrapperIntro = setupNamespace(name, 'this', options.globals, options.compact) + wrapperIntro;
  5633. }
  5634. let wrapperOutro = `${n}${n}}(${deps.join(`,${_}`)}));`;
  5635. if (!extend && namedExportsMode && hasExports) {
  5636. wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
  5637. }
  5638. // var foo__default = 'default' in foo ? foo['default'] : foo;
  5639. const interopBlock = getInteropBlock(dependencies, options, varOrConst);
  5640. if (interopBlock)
  5641. magicString.prepend(interopBlock + n + n);
  5642. if (intro)
  5643. magicString.prepend(intro);
  5644. const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t);
  5645. if (exportBlock)
  5646. magicString.append(n + n + exportBlock);
  5647. if (outro)
  5648. magicString.append(outro);
  5649. return magicString
  5650. .indent(t)
  5651. .prepend(wrapperIntro)
  5652. .append(wrapperOutro);
  5653. }
  5654. function getStarExcludes({ dependencies, exports }) {
  5655. const starExcludes = new Set(exports.map(expt => expt.exported));
  5656. if (!starExcludes.has('default'))
  5657. starExcludes.add('default');
  5658. // also include reexport names
  5659. for (const { reexports } of dependencies) {
  5660. if (reexports) {
  5661. for (const reexport of reexports) {
  5662. if (reexport.imported !== '*' && !starExcludes.has(reexport.reexported))
  5663. starExcludes.add(reexport.reexported);
  5664. }
  5665. }
  5666. }
  5667. return starExcludes;
  5668. }
  5669. const getStarExcludesBlock = (starExcludes, varOrConst, _, t, n) => starExcludes
  5670. ? `${n}${t}${varOrConst} _starExcludes${_}=${_}{${_}${Array.from(starExcludes).join(`:${_}1,${_}`)}${starExcludes.size ? `:${_}1` : ''}${_}};`
  5671. : '';
  5672. const getImportBindingsBlock = (importBindings, _, t, n) => (importBindings.length ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
  5673. function getExportsBlock(exports, _, t, n) {
  5674. if (exports.length === 0) {
  5675. return '';
  5676. }
  5677. if (exports.length === 1) {
  5678. return `${t}${t}${t}exports('${exports[0].name}',${_}${exports[0].value});${n}${n}`;
  5679. }
  5680. return (`${t}${t}${t}exports({${n}` +
  5681. exports.map(({ name, value }) => `${t}${t}${t}${t}${name}:${_}${value}`).join(`,${n}`) +
  5682. `${n}${t}${t}${t}});${n}${n}`);
  5683. }
  5684. const getHoistedExportsBlock = (exports, _, t, n) => getExportsBlock(exports
  5685. .filter(expt => expt.hoisted || expt.uninitialized)
  5686. .map(expt => ({ name: expt.exported, value: expt.uninitialized ? 'void 0' : expt.local })), _, t, n);
  5687. const getMissingExportsBlock = (exports, _, t, n) => getExportsBlock(exports
  5688. .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
  5689. .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), _, t, n);
  5690. function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, outro, usesTopLevelAwait, varOrConst }, options) {
  5691. const n = options.compact ? '' : '\n';
  5692. const _ = options.compact ? '' : ' ';
  5693. const dependencyIds = dependencies.map(m => `'${m.id}'`);
  5694. const importBindings = [];
  5695. let starExcludes;
  5696. const setters = [];
  5697. for (const { imports, reexports } of dependencies) {
  5698. const setter = [];
  5699. if (imports) {
  5700. for (const specifier of imports) {
  5701. importBindings.push(specifier.local);
  5702. if (specifier.imported === '*') {
  5703. setter.push(`${specifier.local}${_}=${_}module;`);
  5704. }
  5705. else {
  5706. setter.push(`${specifier.local}${_}=${_}module.${specifier.imported};`);
  5707. }
  5708. }
  5709. }
  5710. if (reexports) {
  5711. let createdSetter = false;
  5712. // bulk-reexport form
  5713. if (reexports.length > 1 ||
  5714. (reexports.length === 1 &&
  5715. (reexports[0].reexported === '*' || reexports[0].imported === '*'))) {
  5716. // star reexports
  5717. for (const specifier of reexports) {
  5718. if (specifier.reexported !== '*')
  5719. continue;
  5720. // need own exports list for deduping in star export case
  5721. if (!starExcludes) {
  5722. starExcludes = getStarExcludes({ dependencies, exports });
  5723. }
  5724. if (!createdSetter) {
  5725. setter.push(`${varOrConst} _setter${_}=${_}{};`);
  5726. createdSetter = true;
  5727. }
  5728. setter.push(`for${_}(var _$p${_}in${_}module)${_}{`);
  5729. setter.push(`${t}if${_}(!_starExcludes[_$p])${_}_setter[_$p]${_}=${_}module[_$p];`);
  5730. setter.push('}');
  5731. }
  5732. // star import reexport
  5733. for (const specifier of reexports) {
  5734. if (specifier.imported !== '*' || specifier.reexported === '*')
  5735. continue;
  5736. setter.push(`exports('${specifier.reexported}',${_}module);`);
  5737. }
  5738. // reexports
  5739. for (const specifier of reexports) {
  5740. if (specifier.reexported === '*' || specifier.imported === '*')
  5741. continue;
  5742. if (!createdSetter) {
  5743. setter.push(`${varOrConst} _setter${_}=${_}{};`);
  5744. createdSetter = true;
  5745. }
  5746. setter.push(`_setter.${specifier.reexported}${_}=${_}module.${specifier.imported};`);
  5747. }
  5748. if (createdSetter) {
  5749. setter.push('exports(_setter);');
  5750. }
  5751. }
  5752. else {
  5753. // single reexport
  5754. for (const specifier of reexports) {
  5755. setter.push(`exports('${specifier.reexported}',${_}module.${specifier.imported});`);
  5756. }
  5757. }
  5758. }
  5759. setters.push(setter.join(`${n}${t}${t}${t}`));
  5760. }
  5761. const registeredName = options.name ? `'${options.name}',${_}` : '';
  5762. const wrapperParams = accessedGlobals.has('module')
  5763. ? `exports,${_}module`
  5764. : hasExports
  5765. ? 'exports'
  5766. : '';
  5767. let wrapperStart = `System.register(${registeredName}[` +
  5768. dependencyIds.join(`,${_}`) +
  5769. `],${_}function${_}(${wrapperParams})${_}{${n}${t}${options.strict ? "'use strict';" : ''}` +
  5770. getStarExcludesBlock(starExcludes, varOrConst, _, t, n) +
  5771. getImportBindingsBlock(importBindings, _, t, n) +
  5772. `${n}${t}return${_}{${setters.length
  5773. ? `${n}${t}${t}setters:${_}[${setters
  5774. .map(s => s
  5775. ? `function${_}(module)${_}{${n}${t}${t}${t}${s}${n}${t}${t}}`
  5776. : `function${_}()${_}{}`)
  5777. .join(`,${_}`)}],`
  5778. : ''}${n}`;
  5779. wrapperStart +=
  5780. `${t}${t}execute:${_}${usesTopLevelAwait ? `async${_}` : ''}function${_}()${_}{${n}${n}` +
  5781. getHoistedExportsBlock(exports, _, t, n);
  5782. const wrapperEnd = `${n}${n}` +
  5783. getMissingExportsBlock(exports, _, t, n) +
  5784. `${t}${t}}${n}${t}}${options.compact ? '' : ';'}${n}});`;
  5785. if (intro)
  5786. magicString.prepend(intro);
  5787. if (outro)
  5788. magicString.append(outro);
  5789. return magicString
  5790. .indent(`${t}${t}${t}`)
  5791. .append(wrapperEnd)
  5792. .prepend(wrapperStart);
  5793. }
  5794. function globalProp(name, globalVar) {
  5795. if (!name)
  5796. return 'null';
  5797. return `${globalVar}${keypath(name)}`;
  5798. }
  5799. function safeAccess(name, globalVar, _) {
  5800. const parts = name.split('.');
  5801. let acc = globalVar;
  5802. return parts.map(part => ((acc += property(part)), acc)).join(`${_}&&${_}`);
  5803. }
  5804. function umd(magicString, { dependencies, exports, hasExports, indentString: t, intro, namedExportsMode, outro, varOrConst, warn }, options) {
  5805. const _ = options.compact ? '' : ' ';
  5806. const n = options.compact ? '' : '\n';
  5807. const factoryVar = options.compact ? 'f' : 'factory';
  5808. const globalVar = options.compact ? 'g' : 'global';
  5809. if (hasExports && !options.name) {
  5810. return error({
  5811. code: 'INVALID_OPTION',
  5812. message: 'You must supply "output.name" for UMD bundles.'
  5813. });
  5814. }
  5815. warnOnBuiltins(warn, dependencies);
  5816. const amdDeps = dependencies.map(m => `'${m.id}'`);
  5817. const cjsDeps = dependencies.map(m => `require('${m.id}')`);
  5818. const trimmedImports = trimEmptyImports(dependencies);
  5819. const globalDeps = trimmedImports.map(module => globalProp(module.globalName, globalVar));
  5820. const factoryArgs = trimmedImports.map(m => m.name);
  5821. if (namedExportsMode && (hasExports || options.noConflict === true)) {
  5822. amdDeps.unshift(`'exports'`);
  5823. cjsDeps.unshift(`exports`);
  5824. globalDeps.unshift(assignToDeepVariable(options.name, globalVar, options.globals, options.compact, `${options.extend ? `${globalProp(options.name, globalVar)}${_}||${_}` : ''}{}`));
  5825. factoryArgs.unshift('exports');
  5826. }
  5827. const amdOptions = options.amd || {};
  5828. const amdParams = (amdOptions.id ? `'${amdOptions.id}',${_}` : ``) +
  5829. (amdDeps.length ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
  5830. const define = amdOptions.define || 'define';
  5831. const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
  5832. const useStrict = options.strict !== false ? `${_}'use strict';${n}` : ``;
  5833. let iifeExport;
  5834. if (options.noConflict === true) {
  5835. const noConflictExportsVar = options.compact ? 'e' : 'exports';
  5836. let factory;
  5837. if (!namedExportsMode && hasExports) {
  5838. factory = `var ${noConflictExportsVar}${_}=${_}${assignToDeepVariable(options.name, globalVar, options.globals, options.compact, `${factoryVar}(${globalDeps.join(`,${_}`)})`)};`;
  5839. }
  5840. else if (namedExportsMode) {
  5841. const module = globalDeps.shift();
  5842. factory =
  5843. `var ${noConflictExportsVar}${_}=${_}${module};${n}` +
  5844. `${t}${t}${factoryVar}(${[noConflictExportsVar].concat(globalDeps).join(`,${_}`)});`;
  5845. }
  5846. iifeExport =
  5847. `(function${_}()${_}{${n}` +
  5848. `${t}${t}var current${_}=${_}${safeAccess(options.name, globalVar, _)};${n}` +
  5849. `${t}${t}${factory}${n}` +
  5850. `${t}${t}${noConflictExportsVar}.noConflict${_}=${_}function${_}()${_}{${_}` +
  5851. `${globalProp(options.name, globalVar)}${_}=${_}current;${_}return ${noConflictExportsVar}${options.compact ? '' : '; '}};${n}` +
  5852. `${t}}())`;
  5853. }
  5854. else {
  5855. iifeExport = `${factoryVar}(${globalDeps.join(`,${_}`)})`;
  5856. if (!namedExportsMode && hasExports) {
  5857. iifeExport = assignToDeepVariable(options.name, globalVar, options.globals, options.compact, iifeExport);
  5858. }
  5859. }
  5860. const iifeNeedsGlobal = hasExports || (options.noConflict === true && namedExportsMode) || globalDeps.length > 0;
  5861. const globalParam = iifeNeedsGlobal ? `${globalVar},${_}` : '';
  5862. const globalArg = iifeNeedsGlobal ? `this,${_}` : '';
  5863. const iifeStart = iifeNeedsGlobal ? `(${globalVar}${_}=${_}${globalVar}${_}||${_}self,${_}` : '';
  5864. const iifeEnd = iifeNeedsGlobal ? ')' : '';
  5865. const cjsIntro = iifeNeedsGlobal
  5866. ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
  5867. `${_}${cjsExport}${factoryVar}(${cjsDeps.join(`,${_}`)})${_}:${n}`
  5868. : '';
  5869. // factory function should be wrapped by parentheses to avoid lazy parsing
  5870. const wrapperIntro = `(function${_}(${globalParam}${factoryVar})${_}{${n}` +
  5871. cjsIntro +
  5872. `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParams}${factoryVar})${_}:${n}` +
  5873. `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
  5874. `}(${globalArg}(function${_}(${factoryArgs.join(', ')})${_}{${useStrict}${n}`;
  5875. const wrapperOutro = n + n + '})));';
  5876. // var foo__default = 'default' in foo ? foo['default'] : foo;
  5877. const interopBlock = getInteropBlock(dependencies, options, varOrConst);
  5878. if (interopBlock)
  5879. magicString.prepend(interopBlock + n + n);
  5880. if (intro)
  5881. magicString.prepend(intro);
  5882. const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t);
  5883. if (exportBlock)
  5884. magicString.append(n + n + exportBlock);
  5885. if (namedExportsMode && hasExports && options.esModule)
  5886. magicString.append(n + n + (options.compact ? compactEsModuleExport : esModuleExport));
  5887. if (outro)
  5888. magicString.append(outro);
  5889. return magicString
  5890. .trim()
  5891. .indent(t)
  5892. .append(wrapperOutro)
  5893. .prepend(wrapperIntro);
  5894. }
  5895. var finalisers = { system, amd, cjs, es: esm, iife, umd };
  5896. const extractors = {
  5897. ArrayPattern(names, param) {
  5898. for (const element of param.elements) {
  5899. if (element)
  5900. extractors[element.type](names, element);
  5901. }
  5902. },
  5903. AssignmentPattern(names, param) {
  5904. extractors[param.left.type](names, param.left);
  5905. },
  5906. Identifier(names, param) {
  5907. names.push(param.name);
  5908. },
  5909. MemberExpression() { },
  5910. ObjectPattern(names, param) {
  5911. for (const prop of param.properties) {
  5912. if (prop.type === 'RestElement') {
  5913. extractors.RestElement(names, prop);
  5914. }
  5915. else {
  5916. extractors[prop.value.type](names, prop.value);
  5917. }
  5918. }
  5919. },
  5920. RestElement(names, param) {
  5921. extractors[param.argument.type](names, param.argument);
  5922. }
  5923. };
  5924. const extractAssignedNames = function extractAssignedNames(param) {
  5925. const names = [];
  5926. extractors[param.type](names, param);
  5927. return names;
  5928. };
  5929. class ExportAllDeclaration extends NodeBase {
  5930. hasEffects() {
  5931. return false;
  5932. }
  5933. initialise() {
  5934. this.context.addExport(this);
  5935. }
  5936. render(code, _options, nodeRenderOptions) {
  5937. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  5938. }
  5939. }
  5940. ExportAllDeclaration.prototype.needsBoundaries = true;
  5941. class ArrayExpression extends NodeBase {
  5942. bind() {
  5943. super.bind();
  5944. for (const element of this.elements) {
  5945. if (element !== null)
  5946. element.deoptimizePath(UNKNOWN_PATH);
  5947. }
  5948. }
  5949. getReturnExpressionWhenCalledAtPath(path) {
  5950. if (path.length !== 1)
  5951. return UNKNOWN_EXPRESSION;
  5952. return getMemberReturnExpressionWhenCalled(arrayMembers, path[0]);
  5953. }
  5954. hasEffectsWhenAccessedAtPath(path) {
  5955. return path.length > 1;
  5956. }
  5957. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  5958. if (path.length === 1) {
  5959. return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, context);
  5960. }
  5961. return true;
  5962. }
  5963. }
  5964. class ArrayPattern extends NodeBase {
  5965. addExportedVariables(variables) {
  5966. for (const element of this.elements) {
  5967. if (element !== null) {
  5968. element.addExportedVariables(variables);
  5969. }
  5970. }
  5971. }
  5972. declare(kind) {
  5973. const variables = [];
  5974. for (const element of this.elements) {
  5975. if (element !== null) {
  5976. variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
  5977. }
  5978. }
  5979. return variables;
  5980. }
  5981. deoptimizePath(path) {
  5982. if (path.length === 0) {
  5983. for (const element of this.elements) {
  5984. if (element !== null) {
  5985. element.deoptimizePath(path);
  5986. }
  5987. }
  5988. }
  5989. }
  5990. hasEffectsWhenAssignedAtPath(path, context) {
  5991. if (path.length > 0)
  5992. return true;
  5993. for (const element of this.elements) {
  5994. if (element !== null && element.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))
  5995. return true;
  5996. }
  5997. return false;
  5998. }
  5999. }
  6000. class BlockScope extends ChildScope {
  6001. addDeclaration(identifier, context, init = null, isHoisted) {
  6002. if (isHoisted) {
  6003. return this.parent.addDeclaration(identifier, context, isHoisted === 'function' ? init : UNKNOWN_EXPRESSION, isHoisted);
  6004. }
  6005. else {
  6006. return super.addDeclaration(identifier, context, init, false);
  6007. }
  6008. }
  6009. }
  6010. class ExpressionStatement$1 extends NodeBase {
  6011. initialise() {
  6012. if (this.directive &&
  6013. this.directive !== 'use strict' &&
  6014. this.parent.type === Program) {
  6015. this.context.warn(
  6016. // This is necessary, because either way (deleting or not) can lead to errors.
  6017. {
  6018. code: 'MODULE_LEVEL_DIRECTIVE',
  6019. message: `Module level directives cause errors when bundled, '${this.directive}' was ignored.`
  6020. }, this.start);
  6021. }
  6022. }
  6023. render(code, options) {
  6024. super.render(code, options);
  6025. if (this.included)
  6026. this.insertSemicolon(code);
  6027. }
  6028. shouldBeIncluded(context) {
  6029. if (this.directive && this.directive !== 'use strict')
  6030. return this.parent.type !== Program;
  6031. return super.shouldBeIncluded(context);
  6032. }
  6033. }
  6034. class BlockStatement$1 extends NodeBase {
  6035. constructor() {
  6036. super(...arguments);
  6037. this.directlyIncluded = false;
  6038. }
  6039. addImplicitReturnExpressionToScope() {
  6040. const lastStatement = this.body[this.body.length - 1];
  6041. if (!lastStatement || lastStatement.type !== ReturnStatement) {
  6042. this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
  6043. }
  6044. }
  6045. createScope(parentScope) {
  6046. this.scope = this.parent.preventChildBlockScope
  6047. ? parentScope
  6048. : new BlockScope(parentScope);
  6049. }
  6050. hasEffects(context) {
  6051. if (this.deoptimizeBody)
  6052. return true;
  6053. for (const node of this.body) {
  6054. if (node.hasEffects(context))
  6055. return true;
  6056. if (context.brokenFlow)
  6057. break;
  6058. }
  6059. return false;
  6060. }
  6061. include(context, includeChildrenRecursively) {
  6062. if (!this.deoptimizeBody || !this.directlyIncluded) {
  6063. this.included = true;
  6064. this.directlyIncluded = true;
  6065. if (this.deoptimizeBody)
  6066. includeChildrenRecursively = true;
  6067. for (const node of this.body) {
  6068. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  6069. node.include(context, includeChildrenRecursively);
  6070. }
  6071. }
  6072. }
  6073. initialise() {
  6074. const firstBodyStatement = this.body[0];
  6075. this.deoptimizeBody =
  6076. firstBodyStatement instanceof ExpressionStatement$1 &&
  6077. firstBodyStatement.directive === 'use asm';
  6078. }
  6079. render(code, options) {
  6080. if (this.body.length) {
  6081. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  6082. }
  6083. else {
  6084. super.render(code, options);
  6085. }
  6086. }
  6087. }
  6088. class ArrowFunctionExpression extends NodeBase {
  6089. createScope(parentScope) {
  6090. this.scope = new ReturnValueScope(parentScope, this.context);
  6091. }
  6092. deoptimizePath(path) {
  6093. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  6094. // which means the return expression needs to be reassigned
  6095. if (path.length === 1 && path[0] === UnknownKey) {
  6096. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  6097. }
  6098. }
  6099. getReturnExpressionWhenCalledAtPath(path) {
  6100. return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION;
  6101. }
  6102. hasEffects() {
  6103. return false;
  6104. }
  6105. hasEffectsWhenAccessedAtPath(path) {
  6106. return path.length > 1;
  6107. }
  6108. hasEffectsWhenAssignedAtPath(path) {
  6109. return path.length > 1;
  6110. }
  6111. hasEffectsWhenCalledAtPath(path, _callOptions, context) {
  6112. if (path.length > 0)
  6113. return true;
  6114. for (const param of this.params) {
  6115. if (param.hasEffects(context))
  6116. return true;
  6117. }
  6118. const { ignore, brokenFlow } = context;
  6119. context.ignore = {
  6120. breaks: false,
  6121. continues: false,
  6122. labels: new Set(),
  6123. returnAwaitYield: true
  6124. };
  6125. if (this.body.hasEffects(context))
  6126. return true;
  6127. context.ignore = ignore;
  6128. context.brokenFlow = brokenFlow;
  6129. return false;
  6130. }
  6131. include(context, includeChildrenRecursively) {
  6132. this.included = true;
  6133. for (const param of this.params) {
  6134. if (!(param instanceof Identifier$1)) {
  6135. param.include(context, includeChildrenRecursively);
  6136. }
  6137. }
  6138. const { brokenFlow } = context;
  6139. context.brokenFlow = BROKEN_FLOW_NONE;
  6140. this.body.include(context, includeChildrenRecursively);
  6141. context.brokenFlow = brokenFlow;
  6142. }
  6143. includeCallArguments(context, args) {
  6144. this.scope.includeCallArguments(context, args);
  6145. }
  6146. initialise() {
  6147. this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
  6148. if (this.body instanceof BlockStatement$1) {
  6149. this.body.addImplicitReturnExpressionToScope();
  6150. }
  6151. else {
  6152. this.scope.addReturnExpression(this.body);
  6153. }
  6154. }
  6155. parseNode(esTreeNode) {
  6156. if (esTreeNode.body.type === BlockStatement) {
  6157. this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
  6158. }
  6159. super.parseNode(esTreeNode);
  6160. }
  6161. }
  6162. ArrowFunctionExpression.prototype.preventChildBlockScope = true;
  6163. function getSystemExportStatement(exportedVariables) {
  6164. if (exportedVariables.length === 1) {
  6165. return `exports('${exportedVariables[0].safeExportName ||
  6166. exportedVariables[0].exportName}', ${exportedVariables[0].getName()});`;
  6167. }
  6168. else {
  6169. return `exports({${exportedVariables
  6170. .map(variable => `${variable.safeExportName || variable.exportName}: ${variable.getName()}`)
  6171. .join(', ')}});`;
  6172. }
  6173. }
  6174. class AssignmentExpression extends NodeBase {
  6175. constructor() {
  6176. super(...arguments);
  6177. this.deoptimized = false;
  6178. }
  6179. hasEffects(context) {
  6180. if (!this.deoptimized)
  6181. this.applyDeoptimizations();
  6182. return (this.right.hasEffects(context) ||
  6183. this.left.hasEffects(context) ||
  6184. this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context));
  6185. }
  6186. hasEffectsWhenAccessedAtPath(path, context) {
  6187. return path.length > 0 && this.right.hasEffectsWhenAccessedAtPath(path, context);
  6188. }
  6189. include(context, includeChildrenRecursively) {
  6190. if (!this.deoptimized)
  6191. this.applyDeoptimizations();
  6192. this.included = true;
  6193. this.left.include(context, includeChildrenRecursively);
  6194. this.right.include(context, includeChildrenRecursively);
  6195. }
  6196. render(code, options) {
  6197. this.left.render(code, options);
  6198. this.right.render(code, options);
  6199. if (options.format === 'system') {
  6200. if (this.left.variable && this.left.variable.exportName) {
  6201. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  6202. const operation = this.operator.length > 1
  6203. ? ` ${this.left.variable.exportName} ${this.operator.slice(0, -1)}`
  6204. : '';
  6205. code.overwrite(operatorPos, operatorPos + this.operator.length, `= exports('${this.left.variable.exportName}',${operation}`);
  6206. code.appendLeft(this.right.end, `)`);
  6207. }
  6208. else if ('addExportedVariables' in this.left) {
  6209. const systemPatternExports = [];
  6210. this.left.addExportedVariables(systemPatternExports);
  6211. if (systemPatternExports.length > 0) {
  6212. code.prependRight(this.start, `function (v) {${getSystemExportStatement(systemPatternExports)} return v;} (`);
  6213. code.appendLeft(this.end, ')');
  6214. }
  6215. }
  6216. }
  6217. }
  6218. applyDeoptimizations() {
  6219. this.deoptimized = true;
  6220. this.left.deoptimizePath(EMPTY_PATH);
  6221. this.right.deoptimizePath(UNKNOWN_PATH);
  6222. }
  6223. }
  6224. class AssignmentPattern extends NodeBase {
  6225. addExportedVariables(variables) {
  6226. this.left.addExportedVariables(variables);
  6227. }
  6228. bind() {
  6229. super.bind();
  6230. this.left.deoptimizePath(EMPTY_PATH);
  6231. this.right.deoptimizePath(UNKNOWN_PATH);
  6232. }
  6233. declare(kind, init) {
  6234. return this.left.declare(kind, init);
  6235. }
  6236. deoptimizePath(path) {
  6237. path.length === 0 && this.left.deoptimizePath(path);
  6238. }
  6239. hasEffectsWhenAssignedAtPath(path, context) {
  6240. return path.length > 0 || this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context);
  6241. }
  6242. render(code, options, { isShorthandProperty } = BLANK) {
  6243. this.left.render(code, options, { isShorthandProperty });
  6244. this.right.render(code, options);
  6245. }
  6246. }
  6247. class AwaitExpression extends NodeBase {
  6248. hasEffects(context) {
  6249. return !context.ignore.returnAwaitYield || this.argument.hasEffects(context);
  6250. }
  6251. include(context, includeChildrenRecursively) {
  6252. if (!this.included) {
  6253. this.included = true;
  6254. checkTopLevelAwait: if (!this.context.usesTopLevelAwait) {
  6255. let parent = this.parent;
  6256. do {
  6257. if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
  6258. break checkTopLevelAwait;
  6259. } while ((parent = parent.parent));
  6260. this.context.usesTopLevelAwait = true;
  6261. }
  6262. }
  6263. this.argument.include(context, includeChildrenRecursively);
  6264. }
  6265. }
  6266. const binaryOperators = {
  6267. '!=': (left, right) => left != right,
  6268. '!==': (left, right) => left !== right,
  6269. '%': (left, right) => left % right,
  6270. '&': (left, right) => left & right,
  6271. '*': (left, right) => left * right,
  6272. // At the moment, "**" will be transpiled to Math.pow
  6273. '**': (left, right) => Math.pow(left, right),
  6274. '+': (left, right) => left + right,
  6275. '-': (left, right) => left - right,
  6276. '/': (left, right) => left / right,
  6277. '<': (left, right) => left < right,
  6278. '<<': (left, right) => left << right,
  6279. '<=': (left, right) => left <= right,
  6280. '==': (left, right) => left == right,
  6281. '===': (left, right) => left === right,
  6282. '>': (left, right) => left > right,
  6283. '>=': (left, right) => left >= right,
  6284. '>>': (left, right) => left >> right,
  6285. '>>>': (left, right) => left >>> right,
  6286. '^': (left, right) => left ^ right,
  6287. in: () => UnknownValue,
  6288. instanceof: () => UnknownValue,
  6289. '|': (left, right) => left | right
  6290. };
  6291. class BinaryExpression extends NodeBase {
  6292. deoptimizeCache() { }
  6293. getLiteralValueAtPath(path, recursionTracker, origin) {
  6294. if (path.length > 0)
  6295. return UnknownValue;
  6296. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  6297. if (leftValue === UnknownValue)
  6298. return UnknownValue;
  6299. const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  6300. if (rightValue === UnknownValue)
  6301. return UnknownValue;
  6302. const operatorFn = binaryOperators[this.operator];
  6303. if (!operatorFn)
  6304. return UnknownValue;
  6305. return operatorFn(leftValue, rightValue);
  6306. }
  6307. hasEffects(context) {
  6308. // support some implicit type coercion runtime errors
  6309. if (this.operator === '+' &&
  6310. this.parent instanceof ExpressionStatement$1 &&
  6311. this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '')
  6312. return true;
  6313. return super.hasEffects(context);
  6314. }
  6315. hasEffectsWhenAccessedAtPath(path) {
  6316. return path.length > 1;
  6317. }
  6318. }
  6319. class BreakStatement extends NodeBase {
  6320. hasEffects(context) {
  6321. if (this.label) {
  6322. if (!context.ignore.labels.has(this.label.name))
  6323. return true;
  6324. context.includedLabels.add(this.label.name);
  6325. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  6326. }
  6327. else {
  6328. if (!context.ignore.breaks)
  6329. return true;
  6330. context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
  6331. }
  6332. return false;
  6333. }
  6334. include(context) {
  6335. this.included = true;
  6336. if (this.label) {
  6337. this.label.include(context);
  6338. context.includedLabels.add(this.label.name);
  6339. }
  6340. context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
  6341. }
  6342. }
  6343. class Literal extends NodeBase {
  6344. getLiteralValueAtPath(path) {
  6345. if (path.length > 0 ||
  6346. // unknown literals can also be null but do not start with an "n"
  6347. (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
  6348. typeof this.value === 'bigint' ||
  6349. // to support shims for regular expressions
  6350. this.context.code.charCodeAt(this.start) === 47) {
  6351. return UnknownValue;
  6352. }
  6353. return this.value;
  6354. }
  6355. getReturnExpressionWhenCalledAtPath(path) {
  6356. if (path.length !== 1)
  6357. return UNKNOWN_EXPRESSION;
  6358. return getMemberReturnExpressionWhenCalled(this.members, path[0]);
  6359. }
  6360. hasEffectsWhenAccessedAtPath(path) {
  6361. if (this.value === null) {
  6362. return path.length > 0;
  6363. }
  6364. return path.length > 1;
  6365. }
  6366. hasEffectsWhenAssignedAtPath(path) {
  6367. return path.length > 0;
  6368. }
  6369. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6370. if (path.length === 1) {
  6371. return hasMemberEffectWhenCalled(this.members, path[0], this.included, callOptions, context);
  6372. }
  6373. return true;
  6374. }
  6375. initialise() {
  6376. this.members = getLiteralMembersForValue(this.value);
  6377. }
  6378. render(code) {
  6379. if (typeof this.value === 'string') {
  6380. code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
  6381. }
  6382. }
  6383. }
  6384. function getResolvablePropertyKey(memberExpression) {
  6385. return memberExpression.computed
  6386. ? getResolvableComputedPropertyKey(memberExpression.property)
  6387. : memberExpression.property.name;
  6388. }
  6389. function getResolvableComputedPropertyKey(propertyKey) {
  6390. if (propertyKey instanceof Literal) {
  6391. return String(propertyKey.value);
  6392. }
  6393. return null;
  6394. }
  6395. function getPathIfNotComputed(memberExpression) {
  6396. const nextPathKey = memberExpression.propertyKey;
  6397. const object = memberExpression.object;
  6398. if (typeof nextPathKey === 'string') {
  6399. if (object instanceof Identifier$1) {
  6400. return [
  6401. { key: object.name, pos: object.start },
  6402. { key: nextPathKey, pos: memberExpression.property.start }
  6403. ];
  6404. }
  6405. if (object instanceof MemberExpression) {
  6406. const parentPath = getPathIfNotComputed(object);
  6407. return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
  6408. }
  6409. }
  6410. return null;
  6411. }
  6412. function getStringFromPath(path) {
  6413. let pathString = path[0].key;
  6414. for (let index = 1; index < path.length; index++) {
  6415. pathString += '.' + path[index].key;
  6416. }
  6417. return pathString;
  6418. }
  6419. class MemberExpression extends NodeBase {
  6420. constructor() {
  6421. super(...arguments);
  6422. this.variable = null;
  6423. this.bound = false;
  6424. this.expressionsToBeDeoptimized = [];
  6425. this.replacement = null;
  6426. this.wasPathDeoptimizedWhileOptimized = false;
  6427. }
  6428. addExportedVariables() { }
  6429. bind() {
  6430. if (this.bound)
  6431. return;
  6432. this.bound = true;
  6433. const path = getPathIfNotComputed(this);
  6434. const baseVariable = path && this.scope.findVariable(path[0].key);
  6435. if (baseVariable && baseVariable.isNamespace) {
  6436. const resolvedVariable = this.resolveNamespaceVariables(baseVariable, path.slice(1));
  6437. if (!resolvedVariable) {
  6438. super.bind();
  6439. }
  6440. else if (typeof resolvedVariable === 'string') {
  6441. this.replacement = resolvedVariable;
  6442. }
  6443. else {
  6444. if (resolvedVariable instanceof ExternalVariable && resolvedVariable.module) {
  6445. resolvedVariable.module.suggestName(path[0].key);
  6446. }
  6447. this.variable = resolvedVariable;
  6448. this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
  6449. }
  6450. }
  6451. else {
  6452. super.bind();
  6453. // ensure the propertyKey is set for the tree-shaking passes
  6454. this.getPropertyKey();
  6455. }
  6456. }
  6457. deoptimizeCache() {
  6458. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  6459. this.expressionsToBeDeoptimized = [];
  6460. this.propertyKey = UnknownKey;
  6461. if (this.wasPathDeoptimizedWhileOptimized) {
  6462. this.object.deoptimizePath(UNKNOWN_PATH);
  6463. }
  6464. for (const expression of expressionsToBeDeoptimized) {
  6465. expression.deoptimizeCache();
  6466. }
  6467. }
  6468. deoptimizePath(path) {
  6469. if (!this.bound)
  6470. this.bind();
  6471. if (path.length === 0)
  6472. this.disallowNamespaceReassignment();
  6473. if (this.variable) {
  6474. this.variable.deoptimizePath(path);
  6475. }
  6476. else {
  6477. const propertyKey = this.getPropertyKey();
  6478. if (propertyKey === UnknownKey) {
  6479. this.object.deoptimizePath(UNKNOWN_PATH);
  6480. }
  6481. else {
  6482. this.wasPathDeoptimizedWhileOptimized = true;
  6483. this.object.deoptimizePath([propertyKey, ...path]);
  6484. }
  6485. }
  6486. }
  6487. getLiteralValueAtPath(path, recursionTracker, origin) {
  6488. if (!this.bound)
  6489. this.bind();
  6490. if (this.variable !== null) {
  6491. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  6492. }
  6493. this.expressionsToBeDeoptimized.push(origin);
  6494. return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
  6495. }
  6496. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  6497. if (!this.bound)
  6498. this.bind();
  6499. if (this.variable !== null) {
  6500. return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  6501. }
  6502. this.expressionsToBeDeoptimized.push(origin);
  6503. return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
  6504. }
  6505. hasEffects(context) {
  6506. return (this.property.hasEffects(context) ||
  6507. this.object.hasEffects(context) ||
  6508. (this.context.propertyReadSideEffects &&
  6509. this.object.hasEffectsWhenAccessedAtPath([this.propertyKey], context)));
  6510. }
  6511. hasEffectsWhenAccessedAtPath(path, context) {
  6512. if (path.length === 0)
  6513. return false;
  6514. if (this.variable !== null) {
  6515. return this.variable.hasEffectsWhenAccessedAtPath(path, context);
  6516. }
  6517. return this.object.hasEffectsWhenAccessedAtPath([this.propertyKey, ...path], context);
  6518. }
  6519. hasEffectsWhenAssignedAtPath(path, context) {
  6520. if (this.variable !== null) {
  6521. return this.variable.hasEffectsWhenAssignedAtPath(path, context);
  6522. }
  6523. return this.object.hasEffectsWhenAssignedAtPath([this.propertyKey, ...path], context);
  6524. }
  6525. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6526. if (this.variable !== null) {
  6527. return this.variable.hasEffectsWhenCalledAtPath(path, callOptions, context);
  6528. }
  6529. return this.object.hasEffectsWhenCalledAtPath([this.propertyKey, ...path], callOptions, context);
  6530. }
  6531. include(context, includeChildrenRecursively) {
  6532. if (!this.included) {
  6533. this.included = true;
  6534. if (this.variable !== null) {
  6535. this.context.includeVariable(context, this.variable);
  6536. }
  6537. }
  6538. this.object.include(context, includeChildrenRecursively);
  6539. this.property.include(context, includeChildrenRecursively);
  6540. }
  6541. includeCallArguments(context, args) {
  6542. if (this.variable) {
  6543. this.variable.includeCallArguments(context, args);
  6544. }
  6545. else {
  6546. super.includeCallArguments(context, args);
  6547. }
  6548. }
  6549. initialise() {
  6550. this.propertyKey = getResolvablePropertyKey(this);
  6551. }
  6552. render(code, options, { renderedParentType, isCalleeOfRenderedParent } = BLANK) {
  6553. const isCalleeOfDifferentParent = renderedParentType === CallExpression && isCalleeOfRenderedParent;
  6554. if (this.variable || this.replacement) {
  6555. let replacement = this.variable ? this.variable.getName() : this.replacement;
  6556. if (isCalleeOfDifferentParent)
  6557. replacement = '0, ' + replacement;
  6558. code.overwrite(this.start, this.end, replacement, {
  6559. contentOnly: true,
  6560. storeName: true
  6561. });
  6562. }
  6563. else {
  6564. if (isCalleeOfDifferentParent) {
  6565. code.appendRight(this.start, '0, ');
  6566. }
  6567. super.render(code, options);
  6568. }
  6569. }
  6570. disallowNamespaceReassignment() {
  6571. if (this.object instanceof Identifier$1 &&
  6572. this.scope.findVariable(this.object.name).isNamespace) {
  6573. return this.context.error({
  6574. code: 'ILLEGAL_NAMESPACE_REASSIGNMENT',
  6575. message: `Illegal reassignment to import '${this.object.name}'`
  6576. }, this.start);
  6577. }
  6578. }
  6579. getPropertyKey() {
  6580. if (this.propertyKey === null) {
  6581. this.propertyKey = UnknownKey;
  6582. const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  6583. return (this.propertyKey = value === UnknownValue ? UnknownKey : String(value));
  6584. }
  6585. return this.propertyKey;
  6586. }
  6587. resolveNamespaceVariables(baseVariable, path) {
  6588. if (path.length === 0)
  6589. return baseVariable;
  6590. if (!baseVariable.isNamespace)
  6591. return null;
  6592. const exportName = path[0].key;
  6593. const variable = baseVariable instanceof ExternalVariable
  6594. ? baseVariable.module.getVariableForExportName(exportName)
  6595. : baseVariable.context.traceExport(exportName);
  6596. if (!variable) {
  6597. const fileName = baseVariable instanceof ExternalVariable
  6598. ? baseVariable.module.id
  6599. : baseVariable.context.fileName;
  6600. this.context.warn({
  6601. code: 'MISSING_EXPORT',
  6602. exporter: relativeId(fileName),
  6603. importer: relativeId(this.context.fileName),
  6604. message: `'${exportName}' is not exported by '${relativeId(fileName)}'`,
  6605. missing: exportName,
  6606. url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
  6607. }, path[0].pos);
  6608. return 'undefined';
  6609. }
  6610. return this.resolveNamespaceVariables(variable, path.slice(1));
  6611. }
  6612. }
  6613. class CallExpression$1 extends NodeBase {
  6614. constructor() {
  6615. super(...arguments);
  6616. this.expressionsToBeDeoptimized = [];
  6617. this.returnExpression = null;
  6618. this.wasPathDeoptmizedWhileOptimized = false;
  6619. }
  6620. bind() {
  6621. super.bind();
  6622. if (this.callee instanceof Identifier$1) {
  6623. const variable = this.scope.findVariable(this.callee.name);
  6624. if (variable.isNamespace) {
  6625. return this.context.error({
  6626. code: 'CANNOT_CALL_NAMESPACE',
  6627. message: `Cannot call a namespace ('${this.callee.name}')`
  6628. }, this.start);
  6629. }
  6630. if (this.callee.name === 'eval') {
  6631. this.context.warn({
  6632. code: 'EVAL',
  6633. message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
  6634. url: 'https://rollupjs.org/guide/en/#avoiding-eval'
  6635. }, this.start);
  6636. }
  6637. }
  6638. // ensure the returnExpression is set for the tree-shaking passes
  6639. this.getReturnExpression(SHARED_RECURSION_TRACKER);
  6640. // This deoptimizes "this" for non-namespace calls until we have a better solution
  6641. if (this.callee instanceof MemberExpression && !this.callee.variable) {
  6642. this.callee.object.deoptimizePath(UNKNOWN_PATH);
  6643. }
  6644. for (const argument of this.arguments) {
  6645. // This will make sure all properties of parameters behave as "unknown"
  6646. argument.deoptimizePath(UNKNOWN_PATH);
  6647. }
  6648. }
  6649. deoptimizeCache() {
  6650. if (this.returnExpression !== UNKNOWN_EXPRESSION) {
  6651. this.returnExpression = null;
  6652. const returnExpression = this.getReturnExpression(SHARED_RECURSION_TRACKER);
  6653. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  6654. if (returnExpression !== UNKNOWN_EXPRESSION) {
  6655. // We need to replace here because is possible new expressions are added
  6656. // while we are deoptimizing the old ones
  6657. this.expressionsToBeDeoptimized = [];
  6658. if (this.wasPathDeoptmizedWhileOptimized) {
  6659. returnExpression.deoptimizePath(UNKNOWN_PATH);
  6660. this.wasPathDeoptmizedWhileOptimized = false;
  6661. }
  6662. }
  6663. for (const expression of expressionsToBeDeoptimized) {
  6664. expression.deoptimizeCache();
  6665. }
  6666. }
  6667. }
  6668. deoptimizePath(path) {
  6669. if (path.length === 0)
  6670. return;
  6671. const trackedEntities = this.context.deoptimizationTracker.getEntities(path);
  6672. if (trackedEntities.has(this))
  6673. return;
  6674. trackedEntities.add(this);
  6675. const returnExpression = this.getReturnExpression(SHARED_RECURSION_TRACKER);
  6676. if (returnExpression !== UNKNOWN_EXPRESSION) {
  6677. this.wasPathDeoptmizedWhileOptimized = true;
  6678. returnExpression.deoptimizePath(path);
  6679. }
  6680. }
  6681. getLiteralValueAtPath(path, recursionTracker, origin) {
  6682. const returnExpression = this.getReturnExpression(recursionTracker);
  6683. if (returnExpression === UNKNOWN_EXPRESSION) {
  6684. return UnknownValue;
  6685. }
  6686. const trackedEntities = recursionTracker.getEntities(path);
  6687. if (trackedEntities.has(returnExpression)) {
  6688. return UnknownValue;
  6689. }
  6690. this.expressionsToBeDeoptimized.push(origin);
  6691. trackedEntities.add(returnExpression);
  6692. const value = returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  6693. trackedEntities.delete(returnExpression);
  6694. return value;
  6695. }
  6696. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  6697. const returnExpression = this.getReturnExpression(recursionTracker);
  6698. if (this.returnExpression === UNKNOWN_EXPRESSION) {
  6699. return UNKNOWN_EXPRESSION;
  6700. }
  6701. const trackedEntities = recursionTracker.getEntities(path);
  6702. if (trackedEntities.has(returnExpression)) {
  6703. return UNKNOWN_EXPRESSION;
  6704. }
  6705. this.expressionsToBeDeoptimized.push(origin);
  6706. trackedEntities.add(returnExpression);
  6707. const value = returnExpression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  6708. trackedEntities.delete(returnExpression);
  6709. return value;
  6710. }
  6711. hasEffects(context) {
  6712. for (const argument of this.arguments) {
  6713. if (argument.hasEffects(context))
  6714. return true;
  6715. }
  6716. if (this.context.annotations && this.annotatedPure)
  6717. return false;
  6718. return (this.callee.hasEffects(context) ||
  6719. this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
  6720. }
  6721. hasEffectsWhenAccessedAtPath(path, context) {
  6722. if (path.length === 0)
  6723. return false;
  6724. const trackedExpressions = context.accessed.getEntities(path);
  6725. if (trackedExpressions.has(this))
  6726. return false;
  6727. trackedExpressions.add(this);
  6728. return this.returnExpression.hasEffectsWhenAccessedAtPath(path, context);
  6729. }
  6730. hasEffectsWhenAssignedAtPath(path, context) {
  6731. if (path.length === 0)
  6732. return true;
  6733. const trackedExpressions = context.assigned.getEntities(path);
  6734. if (trackedExpressions.has(this))
  6735. return false;
  6736. trackedExpressions.add(this);
  6737. return this.returnExpression.hasEffectsWhenAssignedAtPath(path, context);
  6738. }
  6739. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6740. const trackedExpressions = (callOptions.withNew
  6741. ? context.instantiated
  6742. : context.called).getEntities(path);
  6743. if (trackedExpressions.has(this))
  6744. return false;
  6745. trackedExpressions.add(this);
  6746. return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, context);
  6747. }
  6748. include(context, includeChildrenRecursively) {
  6749. if (includeChildrenRecursively) {
  6750. super.include(context, includeChildrenRecursively);
  6751. if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
  6752. this.callee instanceof Identifier$1 &&
  6753. this.callee.variable) {
  6754. this.callee.variable.markCalledFromTryStatement();
  6755. }
  6756. }
  6757. else {
  6758. this.included = true;
  6759. this.callee.include(context, false);
  6760. }
  6761. this.callee.includeCallArguments(context, this.arguments);
  6762. if (!this.returnExpression.included) {
  6763. this.returnExpression.include(context, false);
  6764. }
  6765. }
  6766. initialise() {
  6767. this.callOptions = {
  6768. args: this.arguments,
  6769. withNew: false
  6770. };
  6771. }
  6772. render(code, options, { renderedParentType } = BLANK) {
  6773. this.callee.render(code, options);
  6774. if (this.arguments.length > 0) {
  6775. if (this.arguments[this.arguments.length - 1].included) {
  6776. for (const arg of this.arguments) {
  6777. arg.render(code, options);
  6778. }
  6779. }
  6780. else {
  6781. let lastIncludedIndex = this.arguments.length - 2;
  6782. while (lastIncludedIndex >= 0 && !this.arguments[lastIncludedIndex].included) {
  6783. lastIncludedIndex--;
  6784. }
  6785. if (lastIncludedIndex >= 0) {
  6786. for (let index = 0; index <= lastIncludedIndex; index++) {
  6787. this.arguments[index].render(code, options);
  6788. }
  6789. code.remove(findFirstOccurrenceOutsideComment(code.original, ',', this.arguments[lastIncludedIndex].end), this.end - 1);
  6790. }
  6791. else {
  6792. code.remove(findFirstOccurrenceOutsideComment(code.original, '(', this.callee.end) + 1, this.end - 1);
  6793. }
  6794. }
  6795. }
  6796. if (renderedParentType === ExpressionStatement &&
  6797. this.callee.type === FunctionExpression) {
  6798. code.appendRight(this.start, '(');
  6799. code.prependLeft(this.end, ')');
  6800. }
  6801. }
  6802. getReturnExpression(recursionTracker) {
  6803. if (this.returnExpression === null) {
  6804. this.returnExpression = UNKNOWN_EXPRESSION;
  6805. return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, recursionTracker, this));
  6806. }
  6807. return this.returnExpression;
  6808. }
  6809. }
  6810. class CatchScope extends ParameterScope {
  6811. addDeclaration(identifier, context, init, isHoisted) {
  6812. if (isHoisted) {
  6813. return this.parent.addDeclaration(identifier, context, init, isHoisted);
  6814. }
  6815. else {
  6816. return super.addDeclaration(identifier, context, init, false);
  6817. }
  6818. }
  6819. }
  6820. class CatchClause extends NodeBase {
  6821. createScope(parentScope) {
  6822. this.scope = new CatchScope(parentScope, this.context);
  6823. }
  6824. initialise() {
  6825. if (this.param) {
  6826. this.param.declare('parameter', UNKNOWN_EXPRESSION);
  6827. }
  6828. }
  6829. parseNode(esTreeNode) {
  6830. this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope);
  6831. super.parseNode(esTreeNode);
  6832. }
  6833. }
  6834. CatchClause.prototype.preventChildBlockScope = true;
  6835. class ClassBody extends NodeBase {
  6836. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6837. if (path.length > 0)
  6838. return true;
  6839. return (this.classConstructor !== null &&
  6840. this.classConstructor.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, context));
  6841. }
  6842. initialise() {
  6843. for (const method of this.body) {
  6844. if (method.kind === 'constructor') {
  6845. this.classConstructor = method;
  6846. return;
  6847. }
  6848. }
  6849. this.classConstructor = null;
  6850. }
  6851. }
  6852. class ClassExpression extends ClassNode {
  6853. }
  6854. class MultiExpression {
  6855. constructor(expressions) {
  6856. this.included = false;
  6857. this.expressions = expressions;
  6858. }
  6859. deoptimizePath(path) {
  6860. for (const expression of this.expressions) {
  6861. expression.deoptimizePath(path);
  6862. }
  6863. }
  6864. getLiteralValueAtPath() {
  6865. return UnknownValue;
  6866. }
  6867. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  6868. return new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)));
  6869. }
  6870. hasEffectsWhenAccessedAtPath(path, context) {
  6871. for (const expression of this.expressions) {
  6872. if (expression.hasEffectsWhenAccessedAtPath(path, context))
  6873. return true;
  6874. }
  6875. return false;
  6876. }
  6877. hasEffectsWhenAssignedAtPath(path, context) {
  6878. for (const expression of this.expressions) {
  6879. if (expression.hasEffectsWhenAssignedAtPath(path, context))
  6880. return true;
  6881. }
  6882. return false;
  6883. }
  6884. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6885. for (const expression of this.expressions) {
  6886. if (expression.hasEffectsWhenCalledAtPath(path, callOptions, context))
  6887. return true;
  6888. }
  6889. return false;
  6890. }
  6891. include() { }
  6892. includeCallArguments() { }
  6893. }
  6894. class ConditionalExpression extends NodeBase {
  6895. constructor() {
  6896. super(...arguments);
  6897. this.expressionsToBeDeoptimized = [];
  6898. this.isBranchResolutionAnalysed = false;
  6899. this.usedBranch = null;
  6900. this.wasPathDeoptimizedWhileOptimized = false;
  6901. }
  6902. bind() {
  6903. super.bind();
  6904. // ensure the usedBranch is set for the tree-shaking passes
  6905. this.getUsedBranch();
  6906. }
  6907. deoptimizeCache() {
  6908. if (this.usedBranch !== null) {
  6909. const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
  6910. this.usedBranch = null;
  6911. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  6912. this.expressionsToBeDeoptimized = [];
  6913. if (this.wasPathDeoptimizedWhileOptimized) {
  6914. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  6915. }
  6916. for (const expression of expressionsToBeDeoptimized) {
  6917. expression.deoptimizeCache();
  6918. }
  6919. }
  6920. }
  6921. deoptimizePath(path) {
  6922. if (path.length > 0) {
  6923. const usedBranch = this.getUsedBranch();
  6924. if (usedBranch === null) {
  6925. this.consequent.deoptimizePath(path);
  6926. this.alternate.deoptimizePath(path);
  6927. }
  6928. else {
  6929. this.wasPathDeoptimizedWhileOptimized = true;
  6930. usedBranch.deoptimizePath(path);
  6931. }
  6932. }
  6933. }
  6934. getLiteralValueAtPath(path, recursionTracker, origin) {
  6935. const usedBranch = this.getUsedBranch();
  6936. if (usedBranch === null)
  6937. return UnknownValue;
  6938. this.expressionsToBeDeoptimized.push(origin);
  6939. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  6940. }
  6941. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  6942. const usedBranch = this.getUsedBranch();
  6943. if (usedBranch === null)
  6944. return new MultiExpression([
  6945. this.consequent.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin),
  6946. this.alternate.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)
  6947. ]);
  6948. this.expressionsToBeDeoptimized.push(origin);
  6949. return usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  6950. }
  6951. hasEffects(context) {
  6952. if (this.test.hasEffects(context))
  6953. return true;
  6954. if (this.usedBranch === null) {
  6955. return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
  6956. }
  6957. return this.usedBranch.hasEffects(context);
  6958. }
  6959. hasEffectsWhenAccessedAtPath(path, context) {
  6960. if (path.length === 0)
  6961. return false;
  6962. if (this.usedBranch === null) {
  6963. return (this.consequent.hasEffectsWhenAccessedAtPath(path, context) ||
  6964. this.alternate.hasEffectsWhenAccessedAtPath(path, context));
  6965. }
  6966. return this.usedBranch.hasEffectsWhenAccessedAtPath(path, context);
  6967. }
  6968. hasEffectsWhenAssignedAtPath(path, context) {
  6969. if (path.length === 0)
  6970. return true;
  6971. if (this.usedBranch === null) {
  6972. return (this.consequent.hasEffectsWhenAssignedAtPath(path, context) ||
  6973. this.alternate.hasEffectsWhenAssignedAtPath(path, context));
  6974. }
  6975. return this.usedBranch.hasEffectsWhenAssignedAtPath(path, context);
  6976. }
  6977. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6978. if (this.usedBranch === null) {
  6979. return (this.consequent.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
  6980. this.alternate.hasEffectsWhenCalledAtPath(path, callOptions, context));
  6981. }
  6982. return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, context);
  6983. }
  6984. include(context, includeChildrenRecursively) {
  6985. this.included = true;
  6986. if (includeChildrenRecursively ||
  6987. this.test.shouldBeIncluded(context) ||
  6988. this.usedBranch === null) {
  6989. this.test.include(context, includeChildrenRecursively);
  6990. this.consequent.include(context, includeChildrenRecursively);
  6991. this.alternate.include(context, includeChildrenRecursively);
  6992. }
  6993. else {
  6994. this.usedBranch.include(context, includeChildrenRecursively);
  6995. }
  6996. }
  6997. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  6998. if (!this.test.included) {
  6999. const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
  7000. const inclusionStart = (this.consequent.included
  7001. ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
  7002. : colonPos) + 1;
  7003. if (preventASI) {
  7004. removeLineBreaks(code, inclusionStart, this.usedBranch.start);
  7005. }
  7006. code.remove(this.start, inclusionStart);
  7007. if (this.consequent.included) {
  7008. code.remove(colonPos, this.end);
  7009. }
  7010. removeAnnotations(this, code);
  7011. this.usedBranch.render(code, options, {
  7012. isCalleeOfRenderedParent: renderedParentType
  7013. ? isCalleeOfRenderedParent
  7014. : this.parent.callee === this,
  7015. renderedParentType: renderedParentType || this.parent.type
  7016. });
  7017. }
  7018. else {
  7019. super.render(code, options);
  7020. }
  7021. }
  7022. getUsedBranch() {
  7023. if (this.isBranchResolutionAnalysed) {
  7024. return this.usedBranch;
  7025. }
  7026. this.isBranchResolutionAnalysed = true;
  7027. const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  7028. return testValue === UnknownValue
  7029. ? null
  7030. : (this.usedBranch = testValue ? this.consequent : this.alternate);
  7031. }
  7032. }
  7033. class ContinueStatement extends NodeBase {
  7034. hasEffects(context) {
  7035. if (this.label) {
  7036. if (!context.ignore.labels.has(this.label.name))
  7037. return true;
  7038. context.includedLabels.add(this.label.name);
  7039. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  7040. }
  7041. else {
  7042. if (!context.ignore.continues)
  7043. return true;
  7044. context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
  7045. }
  7046. return false;
  7047. }
  7048. include(context) {
  7049. this.included = true;
  7050. if (this.label) {
  7051. this.label.include(context);
  7052. context.includedLabels.add(this.label.name);
  7053. }
  7054. context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
  7055. }
  7056. }
  7057. class DoWhileStatement extends NodeBase {
  7058. hasEffects(context) {
  7059. if (this.test.hasEffects(context))
  7060. return true;
  7061. const { brokenFlow, ignore: { breaks, continues } } = context;
  7062. context.ignore.breaks = true;
  7063. context.ignore.continues = true;
  7064. if (this.body.hasEffects(context))
  7065. return true;
  7066. context.ignore.breaks = breaks;
  7067. context.ignore.continues = continues;
  7068. context.brokenFlow = brokenFlow;
  7069. return false;
  7070. }
  7071. include(context, includeChildrenRecursively) {
  7072. this.included = true;
  7073. this.test.include(context, includeChildrenRecursively);
  7074. const { brokenFlow } = context;
  7075. this.body.include(context, includeChildrenRecursively);
  7076. context.brokenFlow = brokenFlow;
  7077. }
  7078. }
  7079. class EmptyStatement extends NodeBase {
  7080. hasEffects() {
  7081. return false;
  7082. }
  7083. }
  7084. class ExportNamedDeclaration extends NodeBase {
  7085. bind() {
  7086. // Do not bind specifiers
  7087. if (this.declaration !== null)
  7088. this.declaration.bind();
  7089. }
  7090. hasEffects(context) {
  7091. return this.declaration !== null && this.declaration.hasEffects(context);
  7092. }
  7093. initialise() {
  7094. this.context.addExport(this);
  7095. }
  7096. render(code, options, nodeRenderOptions) {
  7097. const { start, end } = nodeRenderOptions;
  7098. if (this.declaration === null) {
  7099. code.remove(start, end);
  7100. }
  7101. else {
  7102. code.remove(this.start, this.declaration.start);
  7103. this.declaration.render(code, options, { start, end });
  7104. }
  7105. }
  7106. }
  7107. ExportNamedDeclaration.prototype.needsBoundaries = true;
  7108. class ForInStatement extends NodeBase {
  7109. bind() {
  7110. this.left.bind();
  7111. this.left.deoptimizePath(EMPTY_PATH);
  7112. this.right.bind();
  7113. this.body.bind();
  7114. }
  7115. createScope(parentScope) {
  7116. this.scope = new BlockScope(parentScope);
  7117. }
  7118. hasEffects(context) {
  7119. if ((this.left &&
  7120. (this.left.hasEffects(context) ||
  7121. this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))) ||
  7122. (this.right && this.right.hasEffects(context)))
  7123. return true;
  7124. const { brokenFlow, ignore: { breaks, continues } } = context;
  7125. context.ignore.breaks = true;
  7126. context.ignore.continues = true;
  7127. if (this.body.hasEffects(context))
  7128. return true;
  7129. context.ignore.breaks = breaks;
  7130. context.ignore.continues = continues;
  7131. context.brokenFlow = brokenFlow;
  7132. return false;
  7133. }
  7134. include(context, includeChildrenRecursively) {
  7135. this.included = true;
  7136. this.left.includeWithAllDeclaredVariables(includeChildrenRecursively, context);
  7137. this.left.deoptimizePath(EMPTY_PATH);
  7138. this.right.include(context, includeChildrenRecursively);
  7139. const { brokenFlow } = context;
  7140. this.body.include(context, includeChildrenRecursively);
  7141. context.brokenFlow = brokenFlow;
  7142. }
  7143. render(code, options) {
  7144. this.left.render(code, options, NO_SEMICOLON);
  7145. this.right.render(code, options, NO_SEMICOLON);
  7146. // handle no space between "in" and the right side
  7147. if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
  7148. code.prependLeft(this.right.start, ' ');
  7149. }
  7150. this.body.render(code, options);
  7151. }
  7152. }
  7153. class ForOfStatement extends NodeBase {
  7154. bind() {
  7155. this.left.bind();
  7156. this.left.deoptimizePath(EMPTY_PATH);
  7157. this.right.bind();
  7158. this.body.bind();
  7159. }
  7160. createScope(parentScope) {
  7161. this.scope = new BlockScope(parentScope);
  7162. }
  7163. hasEffects() {
  7164. // Placeholder until proper Symbol.Iterator support
  7165. return true;
  7166. }
  7167. include(context, includeChildrenRecursively) {
  7168. this.included = true;
  7169. this.left.includeWithAllDeclaredVariables(includeChildrenRecursively, context);
  7170. this.left.deoptimizePath(EMPTY_PATH);
  7171. this.right.include(context, includeChildrenRecursively);
  7172. const { brokenFlow } = context;
  7173. this.body.include(context, includeChildrenRecursively);
  7174. context.brokenFlow = brokenFlow;
  7175. }
  7176. render(code, options) {
  7177. this.left.render(code, options, NO_SEMICOLON);
  7178. this.right.render(code, options, NO_SEMICOLON);
  7179. // handle no space between "of" and the right side
  7180. if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
  7181. code.prependLeft(this.right.start, ' ');
  7182. }
  7183. this.body.render(code, options);
  7184. }
  7185. }
  7186. class ForStatement extends NodeBase {
  7187. createScope(parentScope) {
  7188. this.scope = new BlockScope(parentScope);
  7189. }
  7190. hasEffects(context) {
  7191. if ((this.init && this.init.hasEffects(context)) ||
  7192. (this.test && this.test.hasEffects(context)) ||
  7193. (this.update && this.update.hasEffects(context)))
  7194. return true;
  7195. const { brokenFlow, ignore: { breaks, continues } } = context;
  7196. context.ignore.breaks = true;
  7197. context.ignore.continues = true;
  7198. if (this.body.hasEffects(context))
  7199. return true;
  7200. context.ignore.breaks = breaks;
  7201. context.ignore.continues = continues;
  7202. context.brokenFlow = brokenFlow;
  7203. return false;
  7204. }
  7205. include(context, includeChildrenRecursively) {
  7206. this.included = true;
  7207. if (this.init)
  7208. this.init.include(context, includeChildrenRecursively);
  7209. if (this.test)
  7210. this.test.include(context, includeChildrenRecursively);
  7211. const { brokenFlow } = context;
  7212. if (this.update)
  7213. this.update.include(context, includeChildrenRecursively);
  7214. this.body.include(context, includeChildrenRecursively);
  7215. context.brokenFlow = brokenFlow;
  7216. }
  7217. render(code, options) {
  7218. if (this.init)
  7219. this.init.render(code, options, NO_SEMICOLON);
  7220. if (this.test)
  7221. this.test.render(code, options, NO_SEMICOLON);
  7222. if (this.update)
  7223. this.update.render(code, options, NO_SEMICOLON);
  7224. this.body.render(code, options);
  7225. }
  7226. }
  7227. class FunctionExpression$1 extends FunctionNode {
  7228. }
  7229. const unset = Symbol('unset');
  7230. class IfStatement extends NodeBase {
  7231. constructor() {
  7232. super(...arguments);
  7233. this.testValue = unset;
  7234. }
  7235. deoptimizeCache() {
  7236. this.testValue = UnknownValue;
  7237. }
  7238. hasEffects(context) {
  7239. if (this.test.hasEffects(context)) {
  7240. return true;
  7241. }
  7242. const testValue = this.getTestValue();
  7243. if (testValue === UnknownValue) {
  7244. const { brokenFlow } = context;
  7245. if (this.consequent.hasEffects(context))
  7246. return true;
  7247. const consequentBrokenFlow = context.brokenFlow;
  7248. context.brokenFlow = brokenFlow;
  7249. if (this.alternate === null)
  7250. return false;
  7251. if (this.alternate.hasEffects(context))
  7252. return true;
  7253. context.brokenFlow =
  7254. context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
  7255. return false;
  7256. }
  7257. return testValue
  7258. ? this.consequent.hasEffects(context)
  7259. : this.alternate !== null && this.alternate.hasEffects(context);
  7260. }
  7261. include(context, includeChildrenRecursively) {
  7262. this.included = true;
  7263. if (includeChildrenRecursively) {
  7264. this.includeRecursively(includeChildrenRecursively, context);
  7265. }
  7266. else {
  7267. const testValue = this.getTestValue();
  7268. if (testValue === UnknownValue) {
  7269. this.includeUnknownTest(context);
  7270. }
  7271. else {
  7272. this.includeKnownTest(context, testValue);
  7273. }
  7274. }
  7275. }
  7276. render(code, options) {
  7277. // Note that unknown test values are always included
  7278. const testValue = this.getTestValue();
  7279. if (!this.test.included &&
  7280. (testValue ? this.alternate === null || !this.alternate.included : !this.consequent.included)) {
  7281. const singleRetainedBranch = (testValue ? this.consequent : this.alternate);
  7282. code.remove(this.start, singleRetainedBranch.start);
  7283. code.remove(singleRetainedBranch.end, this.end);
  7284. removeAnnotations(this, code);
  7285. singleRetainedBranch.render(code, options);
  7286. }
  7287. else {
  7288. if (this.test.included) {
  7289. this.test.render(code, options);
  7290. }
  7291. else {
  7292. code.overwrite(this.test.start, this.test.end, testValue ? 'true' : 'false');
  7293. }
  7294. if (this.consequent.included) {
  7295. this.consequent.render(code, options);
  7296. }
  7297. else {
  7298. code.overwrite(this.consequent.start, this.consequent.end, ';');
  7299. }
  7300. if (this.alternate !== null) {
  7301. if (this.alternate.included) {
  7302. if (code.original.charCodeAt(this.alternate.start - 1) === 101 /* e */) {
  7303. code.prependLeft(this.alternate.start, ' ');
  7304. }
  7305. this.alternate.render(code, options);
  7306. }
  7307. else {
  7308. code.remove(this.consequent.end, this.alternate.end);
  7309. }
  7310. }
  7311. }
  7312. }
  7313. getTestValue() {
  7314. if (this.testValue === unset) {
  7315. return (this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  7316. }
  7317. return this.testValue;
  7318. }
  7319. includeKnownTest(context, testValue) {
  7320. if (this.test.shouldBeIncluded(context)) {
  7321. this.test.include(context, false);
  7322. }
  7323. if (testValue && this.consequent.shouldBeIncluded(context)) {
  7324. this.consequent.include(context, false);
  7325. }
  7326. if (this.alternate !== null && !testValue && this.alternate.shouldBeIncluded(context)) {
  7327. this.alternate.include(context, false);
  7328. }
  7329. }
  7330. includeRecursively(includeChildrenRecursively, context) {
  7331. this.test.include(context, includeChildrenRecursively);
  7332. this.consequent.include(context, includeChildrenRecursively);
  7333. if (this.alternate !== null) {
  7334. this.alternate.include(context, includeChildrenRecursively);
  7335. }
  7336. }
  7337. includeUnknownTest(context) {
  7338. this.test.include(context, false);
  7339. const { brokenFlow } = context;
  7340. let consequentBrokenFlow = BROKEN_FLOW_NONE;
  7341. if (this.consequent.shouldBeIncluded(context)) {
  7342. this.consequent.include(context, false);
  7343. consequentBrokenFlow = context.brokenFlow;
  7344. context.brokenFlow = brokenFlow;
  7345. }
  7346. if (this.alternate !== null && this.alternate.shouldBeIncluded(context)) {
  7347. this.alternate.include(context, false);
  7348. context.brokenFlow =
  7349. context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
  7350. }
  7351. }
  7352. }
  7353. class ImportDeclaration extends NodeBase {
  7354. bind() { }
  7355. hasEffects() {
  7356. return false;
  7357. }
  7358. initialise() {
  7359. this.context.addImport(this);
  7360. }
  7361. render(code, _options, nodeRenderOptions) {
  7362. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  7363. }
  7364. }
  7365. ImportDeclaration.prototype.needsBoundaries = true;
  7366. class Import extends NodeBase {
  7367. constructor() {
  7368. super(...arguments);
  7369. this.exportMode = 'auto';
  7370. }
  7371. hasEffects() {
  7372. return true;
  7373. }
  7374. include(context, includeChildrenRecursively) {
  7375. if (!this.included) {
  7376. this.included = true;
  7377. this.context.includeDynamicImport(this);
  7378. this.scope.addAccessedDynamicImport(this);
  7379. }
  7380. this.source.include(context, includeChildrenRecursively);
  7381. }
  7382. initialise() {
  7383. this.context.addDynamicImport(this);
  7384. }
  7385. render(code, options) {
  7386. if (this.inlineNamespace) {
  7387. const _ = options.compact ? '' : ' ';
  7388. const s = options.compact ? '' : ';';
  7389. code.overwrite(this.start, this.end, `Promise.resolve().then(function${_}()${_}{${_}return ${this.inlineNamespace.getName()}${s}${_}})`);
  7390. return;
  7391. }
  7392. const importMechanism = this.getDynamicImportMechanism(options);
  7393. if (importMechanism) {
  7394. code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, importMechanism.left);
  7395. code.overwrite(this.end - 1, this.end, importMechanism.right);
  7396. }
  7397. this.source.render(code, options);
  7398. }
  7399. renderFinalResolution(code, resolution, format) {
  7400. if (this.included) {
  7401. if (format === 'amd' && resolution.startsWith("'.") && resolution.endsWith(".js'")) {
  7402. resolution = resolution.slice(0, -4) + "'";
  7403. }
  7404. code.overwrite(this.source.start, this.source.end, resolution);
  7405. }
  7406. }
  7407. setResolution(exportMode, inlineNamespace) {
  7408. this.exportMode = exportMode;
  7409. if (inlineNamespace) {
  7410. this.inlineNamespace = inlineNamespace;
  7411. }
  7412. else {
  7413. this.scope.addAccessedGlobalsByFormat({
  7414. amd: ['require'],
  7415. cjs: ['require'],
  7416. system: ['module']
  7417. });
  7418. if (exportMode === 'auto') {
  7419. this.scope.addAccessedGlobalsByFormat({
  7420. amd: [INTEROP_NAMESPACE_VARIABLE],
  7421. cjs: [INTEROP_NAMESPACE_VARIABLE]
  7422. });
  7423. }
  7424. }
  7425. }
  7426. getDynamicImportMechanism(options) {
  7427. switch (options.format) {
  7428. case 'cjs': {
  7429. const _ = options.compact ? '' : ' ';
  7430. const resolve = options.compact ? 'c' : 'resolve';
  7431. switch (this.exportMode) {
  7432. case 'default':
  7433. return {
  7434. left: `new Promise(function${_}(${resolve})${_}{${_}${resolve}({${_}'default':${_}require(`,
  7435. right: `)${_}});${_}})`
  7436. };
  7437. case 'auto':
  7438. return {
  7439. left: `new Promise(function${_}(${resolve})${_}{${_}${resolve}(${INTEROP_NAMESPACE_VARIABLE}(require(`,
  7440. right: `)));${_}})`
  7441. };
  7442. default:
  7443. return {
  7444. left: `new Promise(function${_}(${resolve})${_}{${_}${resolve}(require(`,
  7445. right: `));${_}})`
  7446. };
  7447. }
  7448. }
  7449. case 'amd': {
  7450. const _ = options.compact ? '' : ' ';
  7451. const resolve = options.compact ? 'c' : 'resolve';
  7452. const reject = options.compact ? 'e' : 'reject';
  7453. const resolveNamespace = this.exportMode === 'default'
  7454. ? `function${_}(m)${_}{${_}${resolve}({${_}'default':${_}m${_}});${_}}`
  7455. : this.exportMode === 'auto'
  7456. ? `function${_}(m)${_}{${_}${resolve}(${INTEROP_NAMESPACE_VARIABLE}(m));${_}}`
  7457. : resolve;
  7458. return {
  7459. left: `new Promise(function${_}(${resolve},${_}${reject})${_}{${_}require([`,
  7460. right: `],${_}${resolveNamespace},${_}${reject})${_}})`
  7461. };
  7462. }
  7463. case 'system':
  7464. return {
  7465. left: 'module.import(',
  7466. right: ')'
  7467. };
  7468. case 'es':
  7469. if (options.dynamicImportFunction) {
  7470. return {
  7471. left: `${options.dynamicImportFunction}(`,
  7472. right: ')'
  7473. };
  7474. }
  7475. }
  7476. return null;
  7477. }
  7478. }
  7479. class LabeledStatement extends NodeBase {
  7480. hasEffects(context) {
  7481. const brokenFlow = context.brokenFlow;
  7482. context.ignore.labels.add(this.label.name);
  7483. if (this.body.hasEffects(context))
  7484. return true;
  7485. context.ignore.labels.delete(this.label.name);
  7486. if (context.includedLabels.has(this.label.name)) {
  7487. context.includedLabels.delete(this.label.name);
  7488. context.brokenFlow = brokenFlow;
  7489. }
  7490. return false;
  7491. }
  7492. include(context, includeChildrenRecursively) {
  7493. this.included = true;
  7494. const brokenFlow = context.brokenFlow;
  7495. this.body.include(context, includeChildrenRecursively);
  7496. if (context.includedLabels.has(this.label.name)) {
  7497. this.label.include(context);
  7498. context.includedLabels.delete(this.label.name);
  7499. context.brokenFlow = brokenFlow;
  7500. }
  7501. }
  7502. render(code, options) {
  7503. if (this.label.included) {
  7504. this.label.render(code, options);
  7505. }
  7506. else {
  7507. code.remove(this.start, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1);
  7508. }
  7509. this.body.render(code, options);
  7510. }
  7511. }
  7512. class LogicalExpression extends NodeBase {
  7513. constructor() {
  7514. super(...arguments);
  7515. // We collect deoptimization information if usedBranch !== null
  7516. this.expressionsToBeDeoptimized = [];
  7517. this.isBranchResolutionAnalysed = false;
  7518. this.unusedBranch = null;
  7519. this.usedBranch = null;
  7520. this.wasPathDeoptimizedWhileOptimized = false;
  7521. }
  7522. bind() {
  7523. super.bind();
  7524. // ensure the usedBranch is set for the tree-shaking passes
  7525. this.getUsedBranch();
  7526. }
  7527. deoptimizeCache() {
  7528. if (this.usedBranch !== null) {
  7529. this.usedBranch = null;
  7530. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  7531. this.expressionsToBeDeoptimized = [];
  7532. if (this.wasPathDeoptimizedWhileOptimized) {
  7533. this.unusedBranch.deoptimizePath(UNKNOWN_PATH);
  7534. }
  7535. for (const expression of expressionsToBeDeoptimized) {
  7536. expression.deoptimizeCache();
  7537. }
  7538. }
  7539. }
  7540. deoptimizePath(path) {
  7541. const usedBranch = this.getUsedBranch();
  7542. if (usedBranch === null) {
  7543. this.left.deoptimizePath(path);
  7544. this.right.deoptimizePath(path);
  7545. }
  7546. else {
  7547. this.wasPathDeoptimizedWhileOptimized = true;
  7548. usedBranch.deoptimizePath(path);
  7549. }
  7550. }
  7551. getLiteralValueAtPath(path, recursionTracker, origin) {
  7552. const usedBranch = this.getUsedBranch();
  7553. if (usedBranch === null)
  7554. return UnknownValue;
  7555. this.expressionsToBeDeoptimized.push(origin);
  7556. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  7557. }
  7558. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  7559. const usedBranch = this.getUsedBranch();
  7560. if (usedBranch === null)
  7561. return new MultiExpression([
  7562. this.left.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin),
  7563. this.right.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)
  7564. ]);
  7565. this.expressionsToBeDeoptimized.push(origin);
  7566. return usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  7567. }
  7568. hasEffects(context) {
  7569. if (this.usedBranch === null) {
  7570. return this.left.hasEffects(context) || this.right.hasEffects(context);
  7571. }
  7572. return this.usedBranch.hasEffects(context);
  7573. }
  7574. hasEffectsWhenAccessedAtPath(path, context) {
  7575. if (path.length === 0)
  7576. return false;
  7577. if (this.usedBranch === null) {
  7578. return (this.left.hasEffectsWhenAccessedAtPath(path, context) ||
  7579. this.right.hasEffectsWhenAccessedAtPath(path, context));
  7580. }
  7581. return this.usedBranch.hasEffectsWhenAccessedAtPath(path, context);
  7582. }
  7583. hasEffectsWhenAssignedAtPath(path, context) {
  7584. if (path.length === 0)
  7585. return true;
  7586. if (this.usedBranch === null) {
  7587. return (this.left.hasEffectsWhenAssignedAtPath(path, context) ||
  7588. this.right.hasEffectsWhenAssignedAtPath(path, context));
  7589. }
  7590. return this.usedBranch.hasEffectsWhenAssignedAtPath(path, context);
  7591. }
  7592. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  7593. if (this.usedBranch === null) {
  7594. return (this.left.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
  7595. this.right.hasEffectsWhenCalledAtPath(path, callOptions, context));
  7596. }
  7597. return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, context);
  7598. }
  7599. include(context, includeChildrenRecursively) {
  7600. this.included = true;
  7601. if (includeChildrenRecursively ||
  7602. (this.usedBranch === this.right && this.left.shouldBeIncluded(context)) ||
  7603. this.usedBranch === null) {
  7604. this.left.include(context, includeChildrenRecursively);
  7605. this.right.include(context, includeChildrenRecursively);
  7606. }
  7607. else {
  7608. this.usedBranch.include(context, includeChildrenRecursively);
  7609. }
  7610. }
  7611. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  7612. if (!this.left.included || !this.right.included) {
  7613. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  7614. if (this.right.included) {
  7615. code.remove(this.start, operatorPos + 2);
  7616. if (preventASI) {
  7617. removeLineBreaks(code, operatorPos + 2, this.right.start);
  7618. }
  7619. }
  7620. else {
  7621. code.remove(operatorPos, this.end);
  7622. }
  7623. removeAnnotations(this, code);
  7624. this.usedBranch.render(code, options, {
  7625. isCalleeOfRenderedParent: renderedParentType
  7626. ? isCalleeOfRenderedParent
  7627. : this.parent.callee === this,
  7628. renderedParentType: renderedParentType || this.parent.type
  7629. });
  7630. }
  7631. else {
  7632. super.render(code, options);
  7633. }
  7634. }
  7635. getUsedBranch() {
  7636. if (!this.isBranchResolutionAnalysed) {
  7637. this.isBranchResolutionAnalysed = true;
  7638. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  7639. if (leftValue === UnknownValue) {
  7640. return null;
  7641. }
  7642. else {
  7643. if (this.operator === '||' ? leftValue : !leftValue) {
  7644. this.usedBranch = this.left;
  7645. this.unusedBranch = this.right;
  7646. }
  7647. else {
  7648. this.usedBranch = this.right;
  7649. this.unusedBranch = this.left;
  7650. }
  7651. }
  7652. }
  7653. return this.usedBranch;
  7654. }
  7655. }
  7656. const readFile = (file) => new Promise((fulfil, reject) => fs.readFile(file, 'utf-8', (err, contents) => (err ? reject(err) : fulfil(contents))));
  7657. function mkdirpath(path$1) {
  7658. const dir = path.dirname(path$1);
  7659. try {
  7660. fs.readdirSync(dir);
  7661. }
  7662. catch (err) {
  7663. mkdirpath(dir);
  7664. try {
  7665. fs.mkdirSync(dir);
  7666. }
  7667. catch (err2) {
  7668. if (err2.code !== 'EEXIST') {
  7669. throw err2;
  7670. }
  7671. }
  7672. }
  7673. }
  7674. function writeFile(dest, data) {
  7675. return new Promise((fulfil, reject) => {
  7676. mkdirpath(dest);
  7677. fs.writeFile(dest, data, err => {
  7678. if (err) {
  7679. reject(err);
  7680. }
  7681. else {
  7682. fulfil();
  7683. }
  7684. });
  7685. });
  7686. }
  7687. function getRollupDefaultPlugin(preserveSymlinks) {
  7688. return {
  7689. name: 'Rollup Core',
  7690. resolveId: createResolveId(preserveSymlinks),
  7691. load(id) {
  7692. return readFile(id);
  7693. },
  7694. resolveFileUrl({ relativePath, format }) {
  7695. return relativeUrlMechanisms[format](relativePath);
  7696. },
  7697. resolveImportMeta(prop, { chunkId, format }) {
  7698. const mechanism = importMetaMechanisms[format] && importMetaMechanisms[format](prop, chunkId);
  7699. if (mechanism) {
  7700. return mechanism;
  7701. }
  7702. }
  7703. };
  7704. }
  7705. function findFile(file, preserveSymlinks) {
  7706. try {
  7707. const stats = fs.lstatSync(file);
  7708. if (!preserveSymlinks && stats.isSymbolicLink())
  7709. return findFile(fs.realpathSync(file), preserveSymlinks);
  7710. if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
  7711. // check case
  7712. const name = path.basename(file);
  7713. const files = fs.readdirSync(path.dirname(file));
  7714. if (files.indexOf(name) !== -1)
  7715. return file;
  7716. }
  7717. }
  7718. catch (err) {
  7719. // suppress
  7720. }
  7721. }
  7722. function addJsExtensionIfNecessary(file, preserveSymlinks) {
  7723. let found = findFile(file, preserveSymlinks);
  7724. if (found)
  7725. return found;
  7726. found = findFile(file + '.mjs', preserveSymlinks);
  7727. if (found)
  7728. return found;
  7729. found = findFile(file + '.js', preserveSymlinks);
  7730. return found;
  7731. }
  7732. function createResolveId(preserveSymlinks) {
  7733. return function (source, importer) {
  7734. if (typeof process === 'undefined') {
  7735. return error({
  7736. code: 'MISSING_PROCESS',
  7737. message: `It looks like you're using Rollup in a non-Node.js environment. This means you must supply a plugin with custom resolveId and load functions`,
  7738. url: 'https://rollupjs.org/guide/en/#a-simple-example'
  7739. });
  7740. }
  7741. // external modules (non-entry modules that start with neither '.' or '/')
  7742. // are skipped at this stage.
  7743. if (importer !== undefined && !isAbsolute(source) && source[0] !== '.')
  7744. return null;
  7745. // `resolve` processes paths from right to left, prepending them until an
  7746. // absolute path is created. Absolute importees therefore shortcircuit the
  7747. // resolve call and require no special handing on our part.
  7748. // See https://nodejs.org/api/path.html#path_path_resolve_paths
  7749. return addJsExtensionIfNecessary(path.resolve(importer ? path.dirname(importer) : path.resolve(), source), preserveSymlinks);
  7750. };
  7751. }
  7752. const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
  7753. const getUrlFromDocument = (chunkId) => `(document.currentScript && document.currentScript.src || new URL('${chunkId}', document.baseURI).href)`;
  7754. const getGenericImportMetaMechanism = (getUrl) => (prop, chunkId) => {
  7755. const urlMechanism = getUrl(chunkId);
  7756. return prop === null ? `({ url: ${urlMechanism} })` : prop === 'url' ? urlMechanism : 'undefined';
  7757. };
  7758. const importMetaMechanisms = {
  7759. amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
  7760. cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`),
  7761. iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
  7762. system: prop => (prop === null ? `module.meta` : `module.meta.${prop}`),
  7763. umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`)
  7764. };
  7765. const getRelativeUrlFromDocument = (relativePath) => getResolveUrl(`'${relativePath}', document.currentScript && document.currentScript.src || document.baseURI`);
  7766. const relativeUrlMechanisms = {
  7767. amd: relativePath => {
  7768. if (relativePath[0] !== '.')
  7769. relativePath = './' + relativePath;
  7770. return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
  7771. },
  7772. cjs: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`,
  7773. es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`),
  7774. iife: relativePath => getRelativeUrlFromDocument(relativePath),
  7775. system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`),
  7776. umd: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`
  7777. };
  7778. const accessedMetaUrlGlobals = {
  7779. amd: ['document', 'module', 'URL'],
  7780. cjs: ['document', 'require', 'URL'],
  7781. iife: ['document', 'URL'],
  7782. system: ['module'],
  7783. umd: ['document', 'require', 'URL']
  7784. };
  7785. const accessedFileUrlGlobals = {
  7786. amd: ['document', 'require', 'URL'],
  7787. cjs: ['document', 'require', 'URL'],
  7788. iife: ['document', 'URL'],
  7789. system: ['module', 'URL'],
  7790. umd: ['document', 'require', 'URL']
  7791. };
  7792. const ASSET_PREFIX = 'ROLLUP_ASSET_URL_';
  7793. const CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_';
  7794. const FILE_PREFIX = 'ROLLUP_FILE_URL_';
  7795. class MetaProperty extends NodeBase {
  7796. hasEffects() {
  7797. return false;
  7798. }
  7799. hasEffectsWhenAccessedAtPath(path) {
  7800. return path.length > 1;
  7801. }
  7802. include() {
  7803. if (!this.included) {
  7804. this.included = true;
  7805. const parent = this.parent;
  7806. const metaProperty = (this.metaProperty =
  7807. parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
  7808. ? parent.propertyKey
  7809. : null);
  7810. if (metaProperty &&
  7811. (metaProperty.startsWith(FILE_PREFIX) ||
  7812. metaProperty.startsWith(ASSET_PREFIX) ||
  7813. metaProperty.startsWith(CHUNK_PREFIX))) {
  7814. this.scope.addAccessedGlobalsByFormat(accessedFileUrlGlobals);
  7815. }
  7816. else {
  7817. this.scope.addAccessedGlobalsByFormat(accessedMetaUrlGlobals);
  7818. }
  7819. }
  7820. }
  7821. initialise() {
  7822. if (this.meta.name === 'import') {
  7823. this.context.addImportMeta(this);
  7824. }
  7825. }
  7826. renderFinalMechanism(code, chunkId, format, outputPluginDriver) {
  7827. if (!this.included)
  7828. return;
  7829. const parent = this.parent;
  7830. const metaProperty = this.metaProperty;
  7831. if (metaProperty &&
  7832. (metaProperty.startsWith(FILE_PREFIX) ||
  7833. metaProperty.startsWith(ASSET_PREFIX) ||
  7834. metaProperty.startsWith(CHUNK_PREFIX))) {
  7835. let referenceId = null;
  7836. let assetReferenceId = null;
  7837. let chunkReferenceId = null;
  7838. let fileName;
  7839. if (metaProperty.startsWith(FILE_PREFIX)) {
  7840. referenceId = metaProperty.substr(FILE_PREFIX.length);
  7841. fileName = outputPluginDriver.getFileName(referenceId);
  7842. }
  7843. else if (metaProperty.startsWith(ASSET_PREFIX)) {
  7844. this.context.warnDeprecation(`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, false);
  7845. assetReferenceId = metaProperty.substr(ASSET_PREFIX.length);
  7846. fileName = outputPluginDriver.getFileName(assetReferenceId);
  7847. }
  7848. else {
  7849. this.context.warnDeprecation(`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, false);
  7850. chunkReferenceId = metaProperty.substr(CHUNK_PREFIX.length);
  7851. fileName = outputPluginDriver.getFileName(chunkReferenceId);
  7852. }
  7853. const relativePath = normalize(path.relative(path.dirname(chunkId), fileName));
  7854. let replacement;
  7855. if (assetReferenceId !== null) {
  7856. replacement = outputPluginDriver.hookFirstSync('resolveAssetUrl', [
  7857. {
  7858. assetFileName: fileName,
  7859. chunkId,
  7860. format,
  7861. moduleId: this.context.module.id,
  7862. relativeAssetPath: relativePath
  7863. }
  7864. ]);
  7865. }
  7866. if (!replacement) {
  7867. replacement = outputPluginDriver.hookFirstSync('resolveFileUrl', [
  7868. {
  7869. assetReferenceId,
  7870. chunkId,
  7871. chunkReferenceId,
  7872. fileName,
  7873. format,
  7874. moduleId: this.context.module.id,
  7875. referenceId: referenceId || assetReferenceId || chunkReferenceId,
  7876. relativePath
  7877. }
  7878. ]);
  7879. }
  7880. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  7881. return;
  7882. }
  7883. const replacement = outputPluginDriver.hookFirstSync('resolveImportMeta', [
  7884. metaProperty,
  7885. {
  7886. chunkId,
  7887. format,
  7888. moduleId: this.context.module.id
  7889. }
  7890. ]);
  7891. if (typeof replacement === 'string') {
  7892. if (parent instanceof MemberExpression) {
  7893. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  7894. }
  7895. else {
  7896. code.overwrite(this.start, this.end, replacement, { contentOnly: true });
  7897. }
  7898. }
  7899. }
  7900. }
  7901. class MethodDefinition extends NodeBase {
  7902. hasEffects(context) {
  7903. return this.key.hasEffects(context);
  7904. }
  7905. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  7906. return (path.length > 0 || this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, context));
  7907. }
  7908. }
  7909. class NewExpression extends NodeBase {
  7910. bind() {
  7911. super.bind();
  7912. for (const argument of this.arguments) {
  7913. // This will make sure all properties of parameters behave as "unknown"
  7914. argument.deoptimizePath(UNKNOWN_PATH);
  7915. }
  7916. }
  7917. hasEffects(context) {
  7918. for (const argument of this.arguments) {
  7919. if (argument.hasEffects(context))
  7920. return true;
  7921. }
  7922. if (this.context.annotations && this.annotatedPure)
  7923. return false;
  7924. return (this.callee.hasEffects(context) ||
  7925. this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
  7926. }
  7927. hasEffectsWhenAccessedAtPath(path) {
  7928. return path.length > 1;
  7929. }
  7930. initialise() {
  7931. this.callOptions = {
  7932. args: this.arguments,
  7933. withNew: true
  7934. };
  7935. }
  7936. }
  7937. class SpreadElement extends NodeBase {
  7938. bind() {
  7939. super.bind();
  7940. // Only properties of properties of the argument could become subject to reassignment
  7941. // This will also reassign the return values of iterators
  7942. this.argument.deoptimizePath([UnknownKey, UnknownKey]);
  7943. }
  7944. }
  7945. class ObjectExpression extends NodeBase {
  7946. constructor() {
  7947. super(...arguments);
  7948. this.deoptimizedPaths = new Set();
  7949. // We collect deoptimization information if we can resolve a computed property access
  7950. this.expressionsToBeDeoptimized = new Map();
  7951. this.hasUnknownDeoptimizedProperty = false;
  7952. this.propertyMap = null;
  7953. this.unmatchablePropertiesRead = [];
  7954. this.unmatchablePropertiesWrite = [];
  7955. }
  7956. bind() {
  7957. super.bind();
  7958. // ensure the propertyMap is set for the tree-shaking passes
  7959. this.getPropertyMap();
  7960. }
  7961. // We could also track this per-property but this would quickly become much more complex
  7962. deoptimizeCache() {
  7963. if (!this.hasUnknownDeoptimizedProperty)
  7964. this.deoptimizeAllProperties();
  7965. }
  7966. deoptimizePath(path) {
  7967. if (this.hasUnknownDeoptimizedProperty)
  7968. return;
  7969. const propertyMap = this.getPropertyMap();
  7970. const key = path[0];
  7971. if (path.length === 1) {
  7972. if (typeof key !== 'string') {
  7973. this.deoptimizeAllProperties();
  7974. return;
  7975. }
  7976. if (!this.deoptimizedPaths.has(key)) {
  7977. this.deoptimizedPaths.add(key);
  7978. // we only deoptimizeCache exact matches as in all other cases,
  7979. // we do not return a literal value or return expression
  7980. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized.get(key);
  7981. if (expressionsToBeDeoptimized) {
  7982. for (const expression of expressionsToBeDeoptimized) {
  7983. expression.deoptimizeCache();
  7984. }
  7985. }
  7986. }
  7987. }
  7988. const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
  7989. for (const property of typeof key === 'string'
  7990. ? propertyMap[key]
  7991. ? propertyMap[key].propertiesRead
  7992. : []
  7993. : this.properties) {
  7994. property.deoptimizePath(subPath);
  7995. }
  7996. }
  7997. getLiteralValueAtPath(path, recursionTracker, origin) {
  7998. const propertyMap = this.getPropertyMap();
  7999. const key = path[0];
  8000. if (path.length === 0 ||
  8001. this.hasUnknownDeoptimizedProperty ||
  8002. typeof key !== 'string' ||
  8003. this.deoptimizedPaths.has(key))
  8004. return UnknownValue;
  8005. if (path.length === 1 &&
  8006. !propertyMap[key] &&
  8007. !objectMembers[key] &&
  8008. this.unmatchablePropertiesRead.length === 0) {
  8009. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized.get(key);
  8010. if (expressionsToBeDeoptimized) {
  8011. expressionsToBeDeoptimized.push(origin);
  8012. }
  8013. else {
  8014. this.expressionsToBeDeoptimized.set(key, [origin]);
  8015. }
  8016. return undefined;
  8017. }
  8018. if (!propertyMap[key] ||
  8019. propertyMap[key].exactMatchRead === null ||
  8020. propertyMap[key].propertiesRead.length > 1) {
  8021. return UnknownValue;
  8022. }
  8023. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized.get(key);
  8024. if (expressionsToBeDeoptimized) {
  8025. expressionsToBeDeoptimized.push(origin);
  8026. }
  8027. else {
  8028. this.expressionsToBeDeoptimized.set(key, [origin]);
  8029. }
  8030. return propertyMap[key].exactMatchRead.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
  8031. }
  8032. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  8033. const propertyMap = this.getPropertyMap();
  8034. const key = path[0];
  8035. if (path.length === 0 ||
  8036. this.hasUnknownDeoptimizedProperty ||
  8037. typeof key !== 'string' ||
  8038. this.deoptimizedPaths.has(key))
  8039. return UNKNOWN_EXPRESSION;
  8040. if (path.length === 1 &&
  8041. objectMembers[key] &&
  8042. this.unmatchablePropertiesRead.length === 0 &&
  8043. (!propertyMap[key] || propertyMap[key].exactMatchRead === null))
  8044. return getMemberReturnExpressionWhenCalled(objectMembers, key);
  8045. if (!propertyMap[key] ||
  8046. propertyMap[key].exactMatchRead === null ||
  8047. propertyMap[key].propertiesRead.length > 1)
  8048. return UNKNOWN_EXPRESSION;
  8049. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized.get(key);
  8050. if (expressionsToBeDeoptimized) {
  8051. expressionsToBeDeoptimized.push(origin);
  8052. }
  8053. else {
  8054. this.expressionsToBeDeoptimized.set(key, [origin]);
  8055. }
  8056. return propertyMap[key].exactMatchRead.getReturnExpressionWhenCalledAtPath(path.slice(1), recursionTracker, origin);
  8057. }
  8058. hasEffectsWhenAccessedAtPath(path, context) {
  8059. if (path.length === 0)
  8060. return false;
  8061. const key = path[0];
  8062. const propertyMap = this.propertyMap;
  8063. if (path.length > 1 &&
  8064. (this.hasUnknownDeoptimizedProperty ||
  8065. typeof key !== 'string' ||
  8066. this.deoptimizedPaths.has(key) ||
  8067. !propertyMap[key] ||
  8068. propertyMap[key].exactMatchRead === null))
  8069. return true;
  8070. const subPath = path.slice(1);
  8071. for (const property of typeof key !== 'string'
  8072. ? this.properties
  8073. : propertyMap[key]
  8074. ? propertyMap[key].propertiesRead
  8075. : []) {
  8076. if (property.hasEffectsWhenAccessedAtPath(subPath, context))
  8077. return true;
  8078. }
  8079. return false;
  8080. }
  8081. hasEffectsWhenAssignedAtPath(path, context) {
  8082. const key = path[0];
  8083. const propertyMap = this.propertyMap;
  8084. if (path.length > 1 &&
  8085. (this.hasUnknownDeoptimizedProperty ||
  8086. this.deoptimizedPaths.has(key) ||
  8087. !propertyMap[key] ||
  8088. propertyMap[key].exactMatchRead === null)) {
  8089. return true;
  8090. }
  8091. const subPath = path.slice(1);
  8092. for (const property of typeof key !== 'string'
  8093. ? this.properties
  8094. : path.length > 1
  8095. ? propertyMap[key].propertiesRead
  8096. : propertyMap[key]
  8097. ? propertyMap[key].propertiesWrite
  8098. : []) {
  8099. if (property.hasEffectsWhenAssignedAtPath(subPath, context))
  8100. return true;
  8101. }
  8102. return false;
  8103. }
  8104. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  8105. const key = path[0];
  8106. if (typeof key !== 'string' ||
  8107. this.hasUnknownDeoptimizedProperty ||
  8108. this.deoptimizedPaths.has(key) ||
  8109. (this.propertyMap[key]
  8110. ? !this.propertyMap[key].exactMatchRead
  8111. : path.length > 1 || !objectMembers[key])) {
  8112. return true;
  8113. }
  8114. const subPath = path.slice(1);
  8115. if (this.propertyMap[key]) {
  8116. for (const property of this.propertyMap[key].propertiesRead) {
  8117. if (property.hasEffectsWhenCalledAtPath(subPath, callOptions, context))
  8118. return true;
  8119. }
  8120. }
  8121. if (path.length === 1 && objectMembers[key])
  8122. return hasMemberEffectWhenCalled(objectMembers, key, this.included, callOptions, context);
  8123. return false;
  8124. }
  8125. render(code, options, { renderedParentType } = BLANK) {
  8126. super.render(code, options);
  8127. if (renderedParentType === ExpressionStatement) {
  8128. code.appendRight(this.start, '(');
  8129. code.prependLeft(this.end, ')');
  8130. }
  8131. }
  8132. deoptimizeAllProperties() {
  8133. this.hasUnknownDeoptimizedProperty = true;
  8134. for (const property of this.properties) {
  8135. property.deoptimizePath(UNKNOWN_PATH);
  8136. }
  8137. for (const expressionsToBeDeoptimized of this.expressionsToBeDeoptimized.values()) {
  8138. for (const expression of expressionsToBeDeoptimized) {
  8139. expression.deoptimizeCache();
  8140. }
  8141. }
  8142. }
  8143. getPropertyMap() {
  8144. if (this.propertyMap !== null) {
  8145. return this.propertyMap;
  8146. }
  8147. const propertyMap = (this.propertyMap = Object.create(null));
  8148. for (let index = this.properties.length - 1; index >= 0; index--) {
  8149. const property = this.properties[index];
  8150. if (property instanceof SpreadElement) {
  8151. this.unmatchablePropertiesRead.push(property);
  8152. continue;
  8153. }
  8154. const isWrite = property.kind !== 'get';
  8155. const isRead = property.kind !== 'set';
  8156. let key;
  8157. if (property.computed) {
  8158. const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  8159. if (keyValue === UnknownValue) {
  8160. if (isRead) {
  8161. this.unmatchablePropertiesRead.push(property);
  8162. }
  8163. else {
  8164. this.unmatchablePropertiesWrite.push(property);
  8165. }
  8166. continue;
  8167. }
  8168. key = String(keyValue);
  8169. }
  8170. else if (property.key instanceof Identifier$1) {
  8171. key = property.key.name;
  8172. }
  8173. else {
  8174. key = String(property.key.value);
  8175. }
  8176. const propertyMapProperty = propertyMap[key];
  8177. if (!propertyMapProperty) {
  8178. propertyMap[key] = {
  8179. exactMatchRead: isRead ? property : null,
  8180. exactMatchWrite: isWrite ? property : null,
  8181. propertiesRead: isRead ? [property, ...this.unmatchablePropertiesRead] : [],
  8182. propertiesWrite: isWrite && !isRead ? [property, ...this.unmatchablePropertiesWrite] : []
  8183. };
  8184. continue;
  8185. }
  8186. if (isRead && propertyMapProperty.exactMatchRead === null) {
  8187. propertyMapProperty.exactMatchRead = property;
  8188. propertyMapProperty.propertiesRead.push(property, ...this.unmatchablePropertiesRead);
  8189. }
  8190. if (isWrite && !isRead && propertyMapProperty.exactMatchWrite === null) {
  8191. propertyMapProperty.exactMatchWrite = property;
  8192. propertyMapProperty.propertiesWrite.push(property, ...this.unmatchablePropertiesWrite);
  8193. }
  8194. }
  8195. return propertyMap;
  8196. }
  8197. }
  8198. class ObjectPattern extends NodeBase {
  8199. addExportedVariables(variables) {
  8200. for (const property of this.properties) {
  8201. if (property.type === Property) {
  8202. property.value.addExportedVariables(variables);
  8203. }
  8204. else {
  8205. property.argument.addExportedVariables(variables);
  8206. }
  8207. }
  8208. }
  8209. declare(kind, init) {
  8210. const variables = [];
  8211. for (const property of this.properties) {
  8212. variables.push(...property.declare(kind, init));
  8213. }
  8214. return variables;
  8215. }
  8216. deoptimizePath(path) {
  8217. if (path.length === 0) {
  8218. for (const property of this.properties) {
  8219. property.deoptimizePath(path);
  8220. }
  8221. }
  8222. }
  8223. hasEffectsWhenAssignedAtPath(path, context) {
  8224. if (path.length > 0)
  8225. return true;
  8226. for (const property of this.properties) {
  8227. if (property.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))
  8228. return true;
  8229. }
  8230. return false;
  8231. }
  8232. }
  8233. class Program$1 extends NodeBase {
  8234. hasEffects(context) {
  8235. for (const node of this.body) {
  8236. if (node.hasEffects(context))
  8237. return true;
  8238. }
  8239. return false;
  8240. }
  8241. include(context, includeChildrenRecursively) {
  8242. this.included = true;
  8243. for (const node of this.body) {
  8244. if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
  8245. node.include(context, includeChildrenRecursively);
  8246. }
  8247. }
  8248. }
  8249. render(code, options) {
  8250. if (this.body.length) {
  8251. renderStatementList(this.body, code, this.start, this.end, options);
  8252. }
  8253. else {
  8254. super.render(code, options);
  8255. }
  8256. }
  8257. }
  8258. class Property$1 extends NodeBase {
  8259. constructor() {
  8260. super(...arguments);
  8261. this.declarationInit = null;
  8262. this.returnExpression = null;
  8263. }
  8264. bind() {
  8265. super.bind();
  8266. if (this.kind === 'get') {
  8267. // ensure the returnExpression is set for the tree-shaking passes
  8268. this.getReturnExpression();
  8269. }
  8270. if (this.declarationInit !== null) {
  8271. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  8272. }
  8273. }
  8274. declare(kind, init) {
  8275. this.declarationInit = init;
  8276. return this.value.declare(kind, UNKNOWN_EXPRESSION);
  8277. }
  8278. // As getter properties directly receive their values from function expressions that always
  8279. // have a fixed return value, there is no known situation where a getter is deoptimized.
  8280. deoptimizeCache() { }
  8281. deoptimizePath(path) {
  8282. if (this.kind === 'get') {
  8283. this.getReturnExpression().deoptimizePath(path);
  8284. }
  8285. else {
  8286. this.value.deoptimizePath(path);
  8287. }
  8288. }
  8289. getLiteralValueAtPath(path, recursionTracker, origin) {
  8290. if (this.kind === 'get') {
  8291. return this.getReturnExpression().getLiteralValueAtPath(path, recursionTracker, origin);
  8292. }
  8293. return this.value.getLiteralValueAtPath(path, recursionTracker, origin);
  8294. }
  8295. getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
  8296. if (this.kind === 'get') {
  8297. return this.getReturnExpression().getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  8298. }
  8299. return this.value.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
  8300. }
  8301. hasEffects(context) {
  8302. return this.key.hasEffects(context) || this.value.hasEffects(context);
  8303. }
  8304. hasEffectsWhenAccessedAtPath(path, context) {
  8305. if (this.kind === 'get') {
  8306. const trackedExpressions = context.accessed.getEntities(path);
  8307. if (trackedExpressions.has(this))
  8308. return false;
  8309. trackedExpressions.add(this);
  8310. return (this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context) ||
  8311. (path.length > 0 && this.returnExpression.hasEffectsWhenAccessedAtPath(path, context)));
  8312. }
  8313. return this.value.hasEffectsWhenAccessedAtPath(path, context);
  8314. }
  8315. hasEffectsWhenAssignedAtPath(path, context) {
  8316. if (this.kind === 'get') {
  8317. const trackedExpressions = context.assigned.getEntities(path);
  8318. if (trackedExpressions.has(this))
  8319. return false;
  8320. trackedExpressions.add(this);
  8321. return this.returnExpression.hasEffectsWhenAssignedAtPath(path, context);
  8322. }
  8323. if (this.kind === 'set') {
  8324. const trackedExpressions = context.assigned.getEntities(path);
  8325. if (trackedExpressions.has(this))
  8326. return false;
  8327. trackedExpressions.add(this);
  8328. return this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context);
  8329. }
  8330. return this.value.hasEffectsWhenAssignedAtPath(path, context);
  8331. }
  8332. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  8333. if (this.kind === 'get') {
  8334. const trackedExpressions = (callOptions.withNew
  8335. ? context.instantiated
  8336. : context.called).getEntities(path);
  8337. if (trackedExpressions.has(this))
  8338. return false;
  8339. trackedExpressions.add(this);
  8340. return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, context);
  8341. }
  8342. return this.value.hasEffectsWhenCalledAtPath(path, callOptions, context);
  8343. }
  8344. initialise() {
  8345. this.accessorCallOptions = {
  8346. args: NO_ARGS,
  8347. withNew: false
  8348. };
  8349. }
  8350. render(code, options) {
  8351. if (!this.shorthand) {
  8352. this.key.render(code, options);
  8353. }
  8354. this.value.render(code, options, { isShorthandProperty: this.shorthand });
  8355. }
  8356. getReturnExpression() {
  8357. if (this.returnExpression === null) {
  8358. this.returnExpression = UNKNOWN_EXPRESSION;
  8359. return (this.returnExpression = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  8360. }
  8361. return this.returnExpression;
  8362. }
  8363. }
  8364. class ReturnStatement$1 extends NodeBase {
  8365. hasEffects(context) {
  8366. if (!context.ignore.returnAwaitYield ||
  8367. (this.argument !== null && this.argument.hasEffects(context)))
  8368. return true;
  8369. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  8370. return false;
  8371. }
  8372. include(context, includeChildrenRecursively) {
  8373. this.included = true;
  8374. if (this.argument) {
  8375. this.argument.include(context, includeChildrenRecursively);
  8376. }
  8377. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  8378. }
  8379. initialise() {
  8380. this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
  8381. }
  8382. render(code, options) {
  8383. if (this.argument) {
  8384. this.argument.render(code, options, { preventASI: true });
  8385. if (this.argument.start === this.start + 6 /* 'return'.length */) {
  8386. code.prependLeft(this.start + 6, ' ');
  8387. }
  8388. }
  8389. }
  8390. }
  8391. class SequenceExpression extends NodeBase {
  8392. deoptimizePath(path) {
  8393. if (path.length > 0)
  8394. this.expressions[this.expressions.length - 1].deoptimizePath(path);
  8395. }
  8396. getLiteralValueAtPath(path, recursionTracker, origin) {
  8397. return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
  8398. }
  8399. hasEffects(context) {
  8400. for (const expression of this.expressions) {
  8401. if (expression.hasEffects(context))
  8402. return true;
  8403. }
  8404. return false;
  8405. }
  8406. hasEffectsWhenAccessedAtPath(path, context) {
  8407. return (path.length > 0 &&
  8408. this.expressions[this.expressions.length - 1].hasEffectsWhenAccessedAtPath(path, context));
  8409. }
  8410. hasEffectsWhenAssignedAtPath(path, context) {
  8411. return (path.length === 0 ||
  8412. this.expressions[this.expressions.length - 1].hasEffectsWhenAssignedAtPath(path, context));
  8413. }
  8414. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  8415. return this.expressions[this.expressions.length - 1].hasEffectsWhenCalledAtPath(path, callOptions, context);
  8416. }
  8417. include(context, includeChildrenRecursively) {
  8418. this.included = true;
  8419. for (let i = 0; i < this.expressions.length - 1; i++) {
  8420. const node = this.expressions[i];
  8421. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  8422. node.include(context, includeChildrenRecursively);
  8423. }
  8424. this.expressions[this.expressions.length - 1].include(context, includeChildrenRecursively);
  8425. }
  8426. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  8427. let includedNodes = 0;
  8428. for (const { node, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
  8429. if (!node.included) {
  8430. treeshakeNode(node, code, start, end);
  8431. continue;
  8432. }
  8433. includedNodes++;
  8434. if (includedNodes === 1 && preventASI) {
  8435. removeLineBreaks(code, start, node.start);
  8436. }
  8437. if (node === this.expressions[this.expressions.length - 1] && includedNodes === 1) {
  8438. node.render(code, options, {
  8439. isCalleeOfRenderedParent: renderedParentType
  8440. ? isCalleeOfRenderedParent
  8441. : this.parent.callee === this,
  8442. renderedParentType: renderedParentType || this.parent.type
  8443. });
  8444. }
  8445. else {
  8446. node.render(code, options);
  8447. }
  8448. }
  8449. }
  8450. }
  8451. class SwitchCase extends NodeBase {
  8452. hasEffects(context) {
  8453. if (this.test && this.test.hasEffects(context))
  8454. return true;
  8455. for (const node of this.consequent) {
  8456. if (context.brokenFlow)
  8457. break;
  8458. if (node.hasEffects(context))
  8459. return true;
  8460. }
  8461. return false;
  8462. }
  8463. include(context, includeChildrenRecursively) {
  8464. this.included = true;
  8465. if (this.test)
  8466. this.test.include(context, includeChildrenRecursively);
  8467. for (const node of this.consequent) {
  8468. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  8469. node.include(context, includeChildrenRecursively);
  8470. }
  8471. }
  8472. render(code, options, nodeRenderOptions) {
  8473. if (this.consequent.length) {
  8474. this.test && this.test.render(code, options);
  8475. const testEnd = this.test
  8476. ? this.test.end
  8477. : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
  8478. const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
  8479. renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
  8480. }
  8481. else {
  8482. super.render(code, options);
  8483. }
  8484. }
  8485. }
  8486. SwitchCase.prototype.needsBoundaries = true;
  8487. class SwitchStatement extends NodeBase {
  8488. createScope(parentScope) {
  8489. this.scope = new BlockScope(parentScope);
  8490. }
  8491. hasEffects(context) {
  8492. if (this.discriminant.hasEffects(context))
  8493. return true;
  8494. const { brokenFlow, ignore: { breaks } } = context;
  8495. let minBrokenFlow = Infinity;
  8496. context.ignore.breaks = true;
  8497. for (const switchCase of this.cases) {
  8498. if (switchCase.hasEffects(context))
  8499. return true;
  8500. minBrokenFlow = context.brokenFlow < minBrokenFlow ? context.brokenFlow : minBrokenFlow;
  8501. context.brokenFlow = brokenFlow;
  8502. }
  8503. if (this.defaultCase !== null && !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
  8504. context.brokenFlow = minBrokenFlow;
  8505. }
  8506. context.ignore.breaks = breaks;
  8507. return false;
  8508. }
  8509. include(context, includeChildrenRecursively) {
  8510. this.included = true;
  8511. this.discriminant.include(context, includeChildrenRecursively);
  8512. const { brokenFlow } = context;
  8513. let minBrokenFlow = Infinity;
  8514. let isCaseIncluded = includeChildrenRecursively ||
  8515. (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
  8516. for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
  8517. const switchCase = this.cases[caseIndex];
  8518. if (switchCase.included) {
  8519. isCaseIncluded = true;
  8520. }
  8521. if (!isCaseIncluded) {
  8522. const hasEffectsContext = createHasEffectsContext();
  8523. hasEffectsContext.ignore.breaks = true;
  8524. isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
  8525. }
  8526. if (isCaseIncluded) {
  8527. switchCase.include(context, includeChildrenRecursively);
  8528. minBrokenFlow = minBrokenFlow < context.brokenFlow ? minBrokenFlow : context.brokenFlow;
  8529. context.brokenFlow = brokenFlow;
  8530. }
  8531. else {
  8532. minBrokenFlow = brokenFlow;
  8533. }
  8534. }
  8535. if (isCaseIncluded &&
  8536. this.defaultCase !== null &&
  8537. !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
  8538. context.brokenFlow = minBrokenFlow;
  8539. }
  8540. }
  8541. initialise() {
  8542. for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
  8543. if (this.cases[caseIndex].test === null) {
  8544. this.defaultCase = caseIndex;
  8545. return;
  8546. }
  8547. }
  8548. this.defaultCase = null;
  8549. }
  8550. render(code, options) {
  8551. this.discriminant.render(code, options);
  8552. if (this.cases.length > 0) {
  8553. renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
  8554. }
  8555. }
  8556. }
  8557. class TaggedTemplateExpression extends NodeBase {
  8558. bind() {
  8559. super.bind();
  8560. if (this.tag.type === Identifier) {
  8561. const name = this.tag.name;
  8562. const variable = this.scope.findVariable(name);
  8563. if (variable.isNamespace) {
  8564. return this.context.error({
  8565. code: 'CANNOT_CALL_NAMESPACE',
  8566. message: `Cannot call a namespace ('${name}')`
  8567. }, this.start);
  8568. }
  8569. if (name === 'eval') {
  8570. this.context.warn({
  8571. code: 'EVAL',
  8572. message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
  8573. url: 'https://rollupjs.org/guide/en/#avoiding-eval'
  8574. }, this.start);
  8575. }
  8576. }
  8577. }
  8578. hasEffects(context) {
  8579. return (super.hasEffects(context) ||
  8580. this.tag.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
  8581. }
  8582. initialise() {
  8583. this.callOptions = {
  8584. args: NO_ARGS,
  8585. withNew: false
  8586. };
  8587. }
  8588. }
  8589. class TemplateElement extends NodeBase {
  8590. hasEffects() {
  8591. return false;
  8592. }
  8593. }
  8594. class TemplateLiteral extends NodeBase {
  8595. getLiteralValueAtPath(path) {
  8596. if (path.length > 0 || this.quasis.length !== 1) {
  8597. return UnknownValue;
  8598. }
  8599. return this.quasis[0].value.cooked;
  8600. }
  8601. render(code, options) {
  8602. code.indentExclusionRanges.push([this.start, this.end]);
  8603. super.render(code, options);
  8604. }
  8605. }
  8606. class ModuleScope extends ChildScope {
  8607. constructor(parent, context) {
  8608. super(parent);
  8609. this.context = context;
  8610. this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context));
  8611. }
  8612. addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
  8613. const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
  8614. this.variables.set('default', variable);
  8615. return variable;
  8616. }
  8617. addNamespaceMemberAccess(_name, variable) {
  8618. if (variable instanceof GlobalVariable) {
  8619. this.accessedOutsideVariables.set(variable.name, variable);
  8620. }
  8621. }
  8622. deconflict(format) {
  8623. // all module level variables are already deconflicted when deconflicting the chunk
  8624. for (const scope of this.children)
  8625. scope.deconflict(format);
  8626. }
  8627. findLexicalBoundary() {
  8628. return this;
  8629. }
  8630. findVariable(name) {
  8631. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  8632. if (knownVariable) {
  8633. return knownVariable;
  8634. }
  8635. const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
  8636. if (variable instanceof GlobalVariable) {
  8637. this.accessedOutsideVariables.set(name, variable);
  8638. }
  8639. return variable;
  8640. }
  8641. }
  8642. class ThisExpression extends NodeBase {
  8643. bind() {
  8644. super.bind();
  8645. this.variable = this.scope.findVariable('this');
  8646. }
  8647. hasEffectsWhenAccessedAtPath(path, context) {
  8648. return path.length > 0 && this.variable.hasEffectsWhenAccessedAtPath(path, context);
  8649. }
  8650. hasEffectsWhenAssignedAtPath(path, context) {
  8651. return this.variable.hasEffectsWhenAssignedAtPath(path, context);
  8652. }
  8653. initialise() {
  8654. this.alias =
  8655. this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
  8656. if (this.alias === 'undefined') {
  8657. this.context.warn({
  8658. code: 'THIS_IS_UNDEFINED',
  8659. message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`,
  8660. url: `https://rollupjs.org/guide/en/#error-this-is-undefined`
  8661. }, this.start);
  8662. }
  8663. }
  8664. render(code) {
  8665. if (this.alias !== null) {
  8666. code.overwrite(this.start, this.end, this.alias, {
  8667. contentOnly: false,
  8668. storeName: true
  8669. });
  8670. }
  8671. }
  8672. }
  8673. class ThrowStatement extends NodeBase {
  8674. hasEffects() {
  8675. return true;
  8676. }
  8677. include(context, includeChildrenRecursively) {
  8678. this.included = true;
  8679. this.argument.include(context, includeChildrenRecursively);
  8680. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  8681. }
  8682. render(code, options) {
  8683. this.argument.render(code, options, { preventASI: true });
  8684. if (this.argument.start === this.start + 5 /* 'throw'.length */) {
  8685. code.prependLeft(this.start + 5, ' ');
  8686. }
  8687. }
  8688. }
  8689. class TryStatement extends NodeBase {
  8690. constructor() {
  8691. super(...arguments);
  8692. this.directlyIncluded = false;
  8693. }
  8694. hasEffects(context) {
  8695. return ((this.context.tryCatchDeoptimization
  8696. ? this.block.body.length > 0
  8697. : this.block.hasEffects(context)) ||
  8698. (this.finalizer !== null && this.finalizer.hasEffects(context)));
  8699. }
  8700. include(context, includeChildrenRecursively) {
  8701. const { brokenFlow } = context;
  8702. if (!this.directlyIncluded || !this.context.tryCatchDeoptimization) {
  8703. this.included = true;
  8704. this.directlyIncluded = true;
  8705. this.block.include(context, this.context.tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
  8706. context.brokenFlow = brokenFlow;
  8707. }
  8708. if (this.handler !== null) {
  8709. this.handler.include(context, includeChildrenRecursively);
  8710. context.brokenFlow = brokenFlow;
  8711. }
  8712. if (this.finalizer !== null) {
  8713. this.finalizer.include(context, includeChildrenRecursively);
  8714. }
  8715. }
  8716. }
  8717. const unaryOperators = {
  8718. '!': value => !value,
  8719. '+': value => +value,
  8720. '-': value => -value,
  8721. delete: () => UnknownValue,
  8722. typeof: value => typeof value,
  8723. void: () => undefined,
  8724. '~': value => ~value
  8725. };
  8726. class UnaryExpression extends NodeBase {
  8727. bind() {
  8728. super.bind();
  8729. if (this.operator === 'delete') {
  8730. this.argument.deoptimizePath(EMPTY_PATH);
  8731. }
  8732. }
  8733. getLiteralValueAtPath(path, recursionTracker, origin) {
  8734. if (path.length > 0)
  8735. return UnknownValue;
  8736. const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  8737. if (argumentValue === UnknownValue)
  8738. return UnknownValue;
  8739. return unaryOperators[this.operator](argumentValue);
  8740. }
  8741. hasEffects(context) {
  8742. if (this.operator === 'typeof' && this.argument instanceof Identifier$1)
  8743. return false;
  8744. return (this.argument.hasEffects(context) ||
  8745. (this.operator === 'delete' &&
  8746. this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context)));
  8747. }
  8748. hasEffectsWhenAccessedAtPath(path) {
  8749. if (this.operator === 'void') {
  8750. return path.length > 0;
  8751. }
  8752. return path.length > 1;
  8753. }
  8754. }
  8755. class UnknownNode extends NodeBase {
  8756. hasEffects() {
  8757. return true;
  8758. }
  8759. include(context) {
  8760. super.include(context, true);
  8761. }
  8762. }
  8763. class UpdateExpression extends NodeBase {
  8764. bind() {
  8765. super.bind();
  8766. this.argument.deoptimizePath(EMPTY_PATH);
  8767. if (this.argument instanceof Identifier$1) {
  8768. const variable = this.scope.findVariable(this.argument.name);
  8769. variable.isReassigned = true;
  8770. }
  8771. }
  8772. hasEffects(context) {
  8773. return (this.argument.hasEffects(context) ||
  8774. this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context));
  8775. }
  8776. hasEffectsWhenAccessedAtPath(path) {
  8777. return path.length > 1;
  8778. }
  8779. render(code, options) {
  8780. this.argument.render(code, options);
  8781. const variable = this.argument.variable;
  8782. if (options.format === 'system' && variable && variable.exportName) {
  8783. const name = variable.getName();
  8784. if (this.prefix) {
  8785. code.overwrite(this.start, this.end, `exports('${variable.exportName}', ${this.operator}${name})`);
  8786. }
  8787. else {
  8788. let op;
  8789. switch (this.operator) {
  8790. case '++':
  8791. op = `${name} + 1`;
  8792. break;
  8793. case '--':
  8794. op = `${name} - 1`;
  8795. break;
  8796. }
  8797. code.overwrite(this.start, this.end, `(exports('${variable.exportName}', ${op}), ${name}${this.operator})`);
  8798. }
  8799. }
  8800. }
  8801. }
  8802. function isReassignedExportsMember(variable) {
  8803. return variable.renderBaseName !== null && variable.exportName !== null && variable.isReassigned;
  8804. }
  8805. function areAllDeclarationsIncludedAndNotExported(declarations) {
  8806. for (const declarator of declarations) {
  8807. if (!declarator.included)
  8808. return false;
  8809. if (declarator.id.type === Identifier) {
  8810. if (declarator.id.variable.exportName)
  8811. return false;
  8812. }
  8813. else {
  8814. const exportedVariables = [];
  8815. declarator.id.addExportedVariables(exportedVariables);
  8816. if (exportedVariables.length > 0)
  8817. return false;
  8818. }
  8819. }
  8820. return true;
  8821. }
  8822. class VariableDeclaration extends NodeBase {
  8823. deoptimizePath() {
  8824. for (const declarator of this.declarations) {
  8825. declarator.deoptimizePath(EMPTY_PATH);
  8826. }
  8827. }
  8828. hasEffectsWhenAssignedAtPath() {
  8829. return false;
  8830. }
  8831. include(context, includeChildrenRecursively) {
  8832. this.included = true;
  8833. for (const declarator of this.declarations) {
  8834. if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
  8835. declarator.include(context, includeChildrenRecursively);
  8836. }
  8837. }
  8838. includeWithAllDeclaredVariables(includeChildrenRecursively, context) {
  8839. this.included = true;
  8840. for (const declarator of this.declarations) {
  8841. declarator.include(context, includeChildrenRecursively);
  8842. }
  8843. }
  8844. initialise() {
  8845. for (const declarator of this.declarations) {
  8846. declarator.declareDeclarator(this.kind);
  8847. }
  8848. }
  8849. render(code, options, nodeRenderOptions = BLANK) {
  8850. if (areAllDeclarationsIncludedAndNotExported(this.declarations)) {
  8851. for (const declarator of this.declarations) {
  8852. declarator.render(code, options);
  8853. }
  8854. if (!nodeRenderOptions.isNoStatement &&
  8855. code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
  8856. code.appendLeft(this.end, ';');
  8857. }
  8858. }
  8859. else {
  8860. this.renderReplacedDeclarations(code, options, nodeRenderOptions);
  8861. }
  8862. }
  8863. renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, addSemicolon, systemPatternExports) {
  8864. if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
  8865. code.remove(this.end - 1, this.end);
  8866. }
  8867. if (addSemicolon) {
  8868. separatorString += ';';
  8869. }
  8870. if (lastSeparatorPos !== null) {
  8871. if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
  8872. (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
  8873. code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
  8874. actualContentEnd--;
  8875. if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
  8876. actualContentEnd--;
  8877. }
  8878. }
  8879. if (actualContentEnd === lastSeparatorPos + 1) {
  8880. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
  8881. }
  8882. else {
  8883. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  8884. code.remove(actualContentEnd, renderedContentEnd);
  8885. }
  8886. }
  8887. else {
  8888. code.appendLeft(renderedContentEnd, separatorString);
  8889. }
  8890. if (systemPatternExports.length > 0) {
  8891. code.appendLeft(renderedContentEnd, ' ' + getSystemExportStatement(systemPatternExports));
  8892. }
  8893. }
  8894. renderReplacedDeclarations(code, options, { start = this.start, end = this.end, isNoStatement }) {
  8895. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
  8896. let actualContentEnd, renderedContentEnd;
  8897. if (/\n\s*$/.test(code.slice(this.start, separatedNodes[0].start))) {
  8898. renderedContentEnd = this.start + this.kind.length;
  8899. }
  8900. else {
  8901. renderedContentEnd = separatedNodes[0].start;
  8902. }
  8903. let lastSeparatorPos = renderedContentEnd - 1;
  8904. code.remove(this.start, lastSeparatorPos);
  8905. let isInDeclaration = false;
  8906. let hasRenderedContent = false;
  8907. let separatorString = '', leadingString, nextSeparatorString;
  8908. const systemPatternExports = [];
  8909. for (const { node, start, separator, contentEnd, end } of separatedNodes) {
  8910. if (!node.included ||
  8911. (node.id instanceof Identifier$1 &&
  8912. isReassignedExportsMember(node.id.variable) &&
  8913. node.init === null)) {
  8914. code.remove(start, end);
  8915. continue;
  8916. }
  8917. leadingString = '';
  8918. nextSeparatorString = '';
  8919. if (node.id instanceof Identifier$1 &&
  8920. isReassignedExportsMember(node.id.variable)) {
  8921. if (hasRenderedContent) {
  8922. separatorString += ';';
  8923. }
  8924. isInDeclaration = false;
  8925. }
  8926. else {
  8927. if (options.format === 'system' && node.init !== null) {
  8928. if (node.id.type !== Identifier) {
  8929. node.id.addExportedVariables(systemPatternExports);
  8930. }
  8931. else if (node.id.variable.exportName) {
  8932. code.prependLeft(code.original.indexOf('=', node.id.end) + 1, ` exports('${node.id.variable.safeExportName || node.id.variable.exportName}',`);
  8933. nextSeparatorString += ')';
  8934. }
  8935. }
  8936. if (isInDeclaration) {
  8937. separatorString += ',';
  8938. }
  8939. else {
  8940. if (hasRenderedContent) {
  8941. separatorString += ';';
  8942. }
  8943. leadingString += `${this.kind} `;
  8944. isInDeclaration = true;
  8945. }
  8946. }
  8947. if (renderedContentEnd === lastSeparatorPos + 1) {
  8948. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
  8949. }
  8950. else {
  8951. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  8952. code.appendLeft(renderedContentEnd, leadingString);
  8953. }
  8954. node.render(code, options);
  8955. actualContentEnd = contentEnd;
  8956. renderedContentEnd = end;
  8957. hasRenderedContent = true;
  8958. lastSeparatorPos = separator;
  8959. separatorString = nextSeparatorString;
  8960. }
  8961. if (hasRenderedContent) {
  8962. this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, !isNoStatement, systemPatternExports);
  8963. }
  8964. else {
  8965. code.remove(start, end);
  8966. }
  8967. }
  8968. }
  8969. class VariableDeclarator extends NodeBase {
  8970. declareDeclarator(kind) {
  8971. this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
  8972. }
  8973. deoptimizePath(path) {
  8974. this.id.deoptimizePath(path);
  8975. }
  8976. render(code, options) {
  8977. // This can happen for hoisted variables in dead branches
  8978. if (this.init !== null && !this.init.included) {
  8979. code.remove(this.id.end, this.end);
  8980. this.id.render(code, options);
  8981. }
  8982. else {
  8983. super.render(code, options);
  8984. }
  8985. }
  8986. }
  8987. class WhileStatement extends NodeBase {
  8988. hasEffects(context) {
  8989. if (this.test.hasEffects(context))
  8990. return true;
  8991. const { brokenFlow, ignore: { breaks, continues } } = context;
  8992. context.ignore.breaks = true;
  8993. context.ignore.continues = true;
  8994. if (this.body.hasEffects(context))
  8995. return true;
  8996. context.ignore.breaks = breaks;
  8997. context.ignore.continues = continues;
  8998. context.brokenFlow = brokenFlow;
  8999. return false;
  9000. }
  9001. include(context, includeChildrenRecursively) {
  9002. this.included = true;
  9003. this.test.include(context, includeChildrenRecursively);
  9004. const { brokenFlow } = context;
  9005. this.body.include(context, includeChildrenRecursively);
  9006. context.brokenFlow = brokenFlow;
  9007. }
  9008. }
  9009. class YieldExpression extends NodeBase {
  9010. bind() {
  9011. super.bind();
  9012. if (this.argument !== null) {
  9013. this.argument.deoptimizePath(UNKNOWN_PATH);
  9014. }
  9015. }
  9016. hasEffects(context) {
  9017. return (!context.ignore.returnAwaitYield ||
  9018. (this.argument !== null && this.argument.hasEffects(context)));
  9019. }
  9020. render(code, options) {
  9021. if (this.argument) {
  9022. this.argument.render(code, options);
  9023. if (this.argument.start === this.start + 5 /* 'yield'.length */) {
  9024. code.prependLeft(this.start + 5, ' ');
  9025. }
  9026. }
  9027. }
  9028. }
  9029. const nodeConstructors = {
  9030. ArrayExpression,
  9031. ArrayPattern,
  9032. ArrowFunctionExpression,
  9033. AssignmentExpression,
  9034. AssignmentPattern,
  9035. AwaitExpression,
  9036. BinaryExpression,
  9037. BlockStatement: BlockStatement$1,
  9038. BreakStatement,
  9039. CallExpression: CallExpression$1,
  9040. CatchClause,
  9041. ClassBody,
  9042. ClassDeclaration,
  9043. ClassExpression,
  9044. ConditionalExpression,
  9045. ContinueStatement,
  9046. DoWhileStatement,
  9047. EmptyStatement,
  9048. ExportAllDeclaration,
  9049. ExportDefaultDeclaration,
  9050. ExportNamedDeclaration,
  9051. ExpressionStatement: ExpressionStatement$1,
  9052. ForInStatement,
  9053. ForOfStatement,
  9054. ForStatement,
  9055. FunctionDeclaration,
  9056. FunctionExpression: FunctionExpression$1,
  9057. Identifier: Identifier$1,
  9058. IfStatement,
  9059. ImportDeclaration,
  9060. ImportExpression: Import,
  9061. LabeledStatement,
  9062. Literal,
  9063. LogicalExpression,
  9064. MemberExpression,
  9065. MetaProperty,
  9066. MethodDefinition,
  9067. NewExpression,
  9068. ObjectExpression,
  9069. ObjectPattern,
  9070. Program: Program$1,
  9071. Property: Property$1,
  9072. RestElement,
  9073. ReturnStatement: ReturnStatement$1,
  9074. SequenceExpression,
  9075. SpreadElement,
  9076. SwitchCase,
  9077. SwitchStatement,
  9078. TaggedTemplateExpression,
  9079. TemplateElement,
  9080. TemplateLiteral,
  9081. ThisExpression,
  9082. ThrowStatement,
  9083. TryStatement,
  9084. UnaryExpression,
  9085. UnknownNode,
  9086. UpdateExpression,
  9087. VariableDeclaration,
  9088. VariableDeclarator,
  9089. WhileStatement,
  9090. YieldExpression
  9091. };
  9092. class SyntheticNamedExportVariableVariable extends Variable {
  9093. constructor(context, name, defaultVariable) {
  9094. super(name);
  9095. this.context = context;
  9096. this.module = context.module;
  9097. this.defaultVariable = defaultVariable;
  9098. this.setRenderNames(defaultVariable.getName(), name);
  9099. }
  9100. include(context) {
  9101. if (!this.included) {
  9102. this.included = true;
  9103. this.context.includeVariable(context, this.defaultVariable);
  9104. }
  9105. }
  9106. }
  9107. function getOriginalLocation(sourcemapChain, location) {
  9108. // This cast is guaranteed. If it were a missing Map, it wouldn't have a mappings.
  9109. const filteredSourcemapChain = sourcemapChain.filter(sourcemap => sourcemap.mappings);
  9110. while (filteredSourcemapChain.length > 0) {
  9111. const sourcemap = filteredSourcemapChain.pop();
  9112. const line = sourcemap.mappings[location.line - 1];
  9113. let locationFound = false;
  9114. if (line !== undefined) {
  9115. for (const segment of line) {
  9116. if (segment[0] >= location.column) {
  9117. if (segment.length === 1)
  9118. break;
  9119. location = {
  9120. column: segment[3],
  9121. line: segment[2] + 1,
  9122. name: segment.length === 5 ? sourcemap.names[segment[4]] : undefined,
  9123. source: sourcemap.sources[segment[1]]
  9124. };
  9125. locationFound = true;
  9126. break;
  9127. }
  9128. }
  9129. }
  9130. if (!locationFound) {
  9131. throw new Error("Can't resolve original location of error.");
  9132. }
  9133. }
  9134. return location;
  9135. }
  9136. // AST walker module for Mozilla Parser API compatible trees
  9137. function skipThrough(node, st, c) { c(node, st); }
  9138. function ignore(_node, _st, _c) {}
  9139. // Node walkers.
  9140. var base$1 = {};
  9141. base$1.Program = base$1.BlockStatement = function (node, st, c) {
  9142. for (var i = 0, list = node.body; i < list.length; i += 1)
  9143. {
  9144. var stmt = list[i];
  9145. c(stmt, st, "Statement");
  9146. }
  9147. };
  9148. base$1.Statement = skipThrough;
  9149. base$1.EmptyStatement = ignore;
  9150. base$1.ExpressionStatement = base$1.ParenthesizedExpression =
  9151. function (node, st, c) { return c(node.expression, st, "Expression"); };
  9152. base$1.IfStatement = function (node, st, c) {
  9153. c(node.test, st, "Expression");
  9154. c(node.consequent, st, "Statement");
  9155. if (node.alternate) { c(node.alternate, st, "Statement"); }
  9156. };
  9157. base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
  9158. base$1.BreakStatement = base$1.ContinueStatement = ignore;
  9159. base$1.WithStatement = function (node, st, c) {
  9160. c(node.object, st, "Expression");
  9161. c(node.body, st, "Statement");
  9162. };
  9163. base$1.SwitchStatement = function (node, st, c) {
  9164. c(node.discriminant, st, "Expression");
  9165. for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
  9166. var cs = list$1[i$1];
  9167. if (cs.test) { c(cs.test, st, "Expression"); }
  9168. for (var i = 0, list = cs.consequent; i < list.length; i += 1)
  9169. {
  9170. var cons = list[i];
  9171. c(cons, st, "Statement");
  9172. }
  9173. }
  9174. };
  9175. base$1.SwitchCase = function (node, st, c) {
  9176. if (node.test) { c(node.test, st, "Expression"); }
  9177. for (var i = 0, list = node.consequent; i < list.length; i += 1)
  9178. {
  9179. var cons = list[i];
  9180. c(cons, st, "Statement");
  9181. }
  9182. };
  9183. base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) {
  9184. if (node.argument) { c(node.argument, st, "Expression"); }
  9185. };
  9186. base$1.ThrowStatement = base$1.SpreadElement =
  9187. function (node, st, c) { return c(node.argument, st, "Expression"); };
  9188. base$1.TryStatement = function (node, st, c) {
  9189. c(node.block, st, "Statement");
  9190. if (node.handler) { c(node.handler, st); }
  9191. if (node.finalizer) { c(node.finalizer, st, "Statement"); }
  9192. };
  9193. base$1.CatchClause = function (node, st, c) {
  9194. if (node.param) { c(node.param, st, "Pattern"); }
  9195. c(node.body, st, "Statement");
  9196. };
  9197. base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) {
  9198. c(node.test, st, "Expression");
  9199. c(node.body, st, "Statement");
  9200. };
  9201. base$1.ForStatement = function (node, st, c) {
  9202. if (node.init) { c(node.init, st, "ForInit"); }
  9203. if (node.test) { c(node.test, st, "Expression"); }
  9204. if (node.update) { c(node.update, st, "Expression"); }
  9205. c(node.body, st, "Statement");
  9206. };
  9207. base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) {
  9208. c(node.left, st, "ForInit");
  9209. c(node.right, st, "Expression");
  9210. c(node.body, st, "Statement");
  9211. };
  9212. base$1.ForInit = function (node, st, c) {
  9213. if (node.type === "VariableDeclaration") { c(node, st); }
  9214. else { c(node, st, "Expression"); }
  9215. };
  9216. base$1.DebuggerStatement = ignore;
  9217. base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
  9218. base$1.VariableDeclaration = function (node, st, c) {
  9219. for (var i = 0, list = node.declarations; i < list.length; i += 1)
  9220. {
  9221. var decl = list[i];
  9222. c(decl, st);
  9223. }
  9224. };
  9225. base$1.VariableDeclarator = function (node, st, c) {
  9226. c(node.id, st, "Pattern");
  9227. if (node.init) { c(node.init, st, "Expression"); }
  9228. };
  9229. base$1.Function = function (node, st, c) {
  9230. if (node.id) { c(node.id, st, "Pattern"); }
  9231. for (var i = 0, list = node.params; i < list.length; i += 1)
  9232. {
  9233. var param = list[i];
  9234. c(param, st, "Pattern");
  9235. }
  9236. c(node.body, st, node.expression ? "Expression" : "Statement");
  9237. };
  9238. base$1.Pattern = function (node, st, c) {
  9239. if (node.type === "Identifier")
  9240. { c(node, st, "VariablePattern"); }
  9241. else if (node.type === "MemberExpression")
  9242. { c(node, st, "MemberPattern"); }
  9243. else
  9244. { c(node, st); }
  9245. };
  9246. base$1.VariablePattern = ignore;
  9247. base$1.MemberPattern = skipThrough;
  9248. base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
  9249. base$1.ArrayPattern = function (node, st, c) {
  9250. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  9251. var elt = list[i];
  9252. if (elt) { c(elt, st, "Pattern"); }
  9253. }
  9254. };
  9255. base$1.ObjectPattern = function (node, st, c) {
  9256. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  9257. var prop = list[i];
  9258. if (prop.type === "Property") {
  9259. if (prop.computed) { c(prop.key, st, "Expression"); }
  9260. c(prop.value, st, "Pattern");
  9261. } else if (prop.type === "RestElement") {
  9262. c(prop.argument, st, "Pattern");
  9263. }
  9264. }
  9265. };
  9266. base$1.Expression = skipThrough;
  9267. base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore;
  9268. base$1.ArrayExpression = function (node, st, c) {
  9269. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  9270. var elt = list[i];
  9271. if (elt) { c(elt, st, "Expression"); }
  9272. }
  9273. };
  9274. base$1.ObjectExpression = function (node, st, c) {
  9275. for (var i = 0, list = node.properties; i < list.length; i += 1)
  9276. {
  9277. var prop = list[i];
  9278. c(prop, st);
  9279. }
  9280. };
  9281. base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration;
  9282. base$1.SequenceExpression = function (node, st, c) {
  9283. for (var i = 0, list = node.expressions; i < list.length; i += 1)
  9284. {
  9285. var expr = list[i];
  9286. c(expr, st, "Expression");
  9287. }
  9288. };
  9289. base$1.TemplateLiteral = function (node, st, c) {
  9290. for (var i = 0, list = node.quasis; i < list.length; i += 1)
  9291. {
  9292. var quasi = list[i];
  9293. c(quasi, st);
  9294. }
  9295. for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
  9296. {
  9297. var expr = list$1[i$1];
  9298. c(expr, st, "Expression");
  9299. }
  9300. };
  9301. base$1.TemplateElement = ignore;
  9302. base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) {
  9303. c(node.argument, st, "Expression");
  9304. };
  9305. base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) {
  9306. c(node.left, st, "Expression");
  9307. c(node.right, st, "Expression");
  9308. };
  9309. base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) {
  9310. c(node.left, st, "Pattern");
  9311. c(node.right, st, "Expression");
  9312. };
  9313. base$1.ConditionalExpression = function (node, st, c) {
  9314. c(node.test, st, "Expression");
  9315. c(node.consequent, st, "Expression");
  9316. c(node.alternate, st, "Expression");
  9317. };
  9318. base$1.NewExpression = base$1.CallExpression = function (node, st, c) {
  9319. c(node.callee, st, "Expression");
  9320. if (node.arguments)
  9321. { for (var i = 0, list = node.arguments; i < list.length; i += 1)
  9322. {
  9323. var arg = list[i];
  9324. c(arg, st, "Expression");
  9325. } }
  9326. };
  9327. base$1.MemberExpression = function (node, st, c) {
  9328. c(node.object, st, "Expression");
  9329. if (node.computed) { c(node.property, st, "Expression"); }
  9330. };
  9331. base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) {
  9332. if (node.declaration)
  9333. { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
  9334. if (node.source) { c(node.source, st, "Expression"); }
  9335. };
  9336. base$1.ExportAllDeclaration = function (node, st, c) {
  9337. c(node.source, st, "Expression");
  9338. };
  9339. base$1.ImportDeclaration = function (node, st, c) {
  9340. for (var i = 0, list = node.specifiers; i < list.length; i += 1)
  9341. {
  9342. var spec = list[i];
  9343. c(spec, st);
  9344. }
  9345. c(node.source, st, "Expression");
  9346. };
  9347. base$1.ImportExpression = function (node, st, c) {
  9348. c(node.source, st, "Expression");
  9349. };
  9350. base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.Literal = ignore;
  9351. base$1.TaggedTemplateExpression = function (node, st, c) {
  9352. c(node.tag, st, "Expression");
  9353. c(node.quasi, st, "Expression");
  9354. };
  9355. base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
  9356. base$1.Class = function (node, st, c) {
  9357. if (node.id) { c(node.id, st, "Pattern"); }
  9358. if (node.superClass) { c(node.superClass, st, "Expression"); }
  9359. c(node.body, st);
  9360. };
  9361. base$1.ClassBody = function (node, st, c) {
  9362. for (var i = 0, list = node.body; i < list.length; i += 1)
  9363. {
  9364. var elt = list[i];
  9365. c(elt, st);
  9366. }
  9367. };
  9368. base$1.MethodDefinition = base$1.Property = function (node, st, c) {
  9369. if (node.computed) { c(node.key, st, "Expression"); }
  9370. c(node.value, st, "Expression");
  9371. };
  9372. // @ts-ignore
  9373. function handlePureAnnotationsOfNode(node, state, type = node.type) {
  9374. let commentNode = state.commentNodes[state.commentIndex];
  9375. while (commentNode && node.start >= commentNode.end) {
  9376. markPureNode(node, commentNode);
  9377. commentNode = state.commentNodes[++state.commentIndex];
  9378. }
  9379. if (commentNode && commentNode.end <= node.end) {
  9380. base$1[type](node, state, handlePureAnnotationsOfNode);
  9381. }
  9382. }
  9383. function markPureNode(node, comment) {
  9384. if (node.annotations) {
  9385. node.annotations.push(comment);
  9386. }
  9387. else {
  9388. node.annotations = [comment];
  9389. }
  9390. if (node.type === 'ExpressionStatement') {
  9391. node = node.expression;
  9392. }
  9393. if (node.type === 'CallExpression' || node.type === 'NewExpression') {
  9394. node.annotatedPure = true;
  9395. }
  9396. }
  9397. const pureCommentRegex = /[@#]__PURE__/;
  9398. const isPureComment = (comment) => pureCommentRegex.test(comment.text);
  9399. function markPureCallExpressions(comments, esTreeAst) {
  9400. handlePureAnnotationsOfNode(esTreeAst, {
  9401. commentIndex: 0,
  9402. commentNodes: comments.filter(isPureComment)
  9403. });
  9404. }
  9405. // this looks ridiculous, but it prevents sourcemap tooling from mistaking
  9406. // this for an actual sourceMappingURL
  9407. let SOURCEMAPPING_URL = 'sourceMa';
  9408. SOURCEMAPPING_URL += 'ppingURL';
  9409. const SOURCEMAPPING_URL_RE = new RegExp(`^#\\s+${SOURCEMAPPING_URL}=.+\\n?`);
  9410. const NOOP = () => { };
  9411. let getStartTime = () => [0, 0];
  9412. let getElapsedTime = () => 0;
  9413. let getMemory = () => 0;
  9414. let timers = {};
  9415. const normalizeHrTime = (time) => time[0] * 1e3 + time[1] / 1e6;
  9416. function setTimeHelpers() {
  9417. if (typeof process !== 'undefined' && typeof process.hrtime === 'function') {
  9418. getStartTime = process.hrtime.bind(process);
  9419. getElapsedTime = previous => normalizeHrTime(process.hrtime(previous));
  9420. }
  9421. else if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
  9422. getStartTime = () => [performance.now(), 0];
  9423. getElapsedTime = previous => performance.now() - previous[0];
  9424. }
  9425. if (typeof process !== 'undefined' && typeof process.memoryUsage === 'function') {
  9426. getMemory = () => process.memoryUsage().heapUsed;
  9427. }
  9428. }
  9429. function getPersistedLabel(label, level) {
  9430. switch (level) {
  9431. case 1:
  9432. return `# ${label}`;
  9433. case 2:
  9434. return `## ${label}`;
  9435. case 3:
  9436. return label;
  9437. default:
  9438. return `${' '.repeat(level - 4)}- ${label}`;
  9439. }
  9440. }
  9441. function timeStartImpl(label, level = 3) {
  9442. label = getPersistedLabel(label, level);
  9443. if (!timers.hasOwnProperty(label)) {
  9444. timers[label] = {
  9445. memory: 0,
  9446. startMemory: undefined,
  9447. startTime: undefined,
  9448. time: 0,
  9449. totalMemory: 0
  9450. };
  9451. }
  9452. const currentMemory = getMemory();
  9453. timers[label].startTime = getStartTime();
  9454. timers[label].startMemory = currentMemory;
  9455. }
  9456. function timeEndImpl(label, level = 3) {
  9457. label = getPersistedLabel(label, level);
  9458. if (timers.hasOwnProperty(label)) {
  9459. const currentMemory = getMemory();
  9460. timers[label].time += getElapsedTime(timers[label].startTime);
  9461. timers[label].totalMemory = Math.max(timers[label].totalMemory, currentMemory);
  9462. timers[label].memory += currentMemory - timers[label].startMemory;
  9463. }
  9464. }
  9465. function getTimings() {
  9466. const newTimings = {};
  9467. for (const label of Object.keys(timers)) {
  9468. newTimings[label] = [timers[label].time, timers[label].memory, timers[label].totalMemory];
  9469. }
  9470. return newTimings;
  9471. }
  9472. let timeStart = NOOP, timeEnd = NOOP;
  9473. const TIMED_PLUGIN_HOOKS = {
  9474. load: true,
  9475. ongenerate: true,
  9476. onwrite: true,
  9477. resolveDynamicImport: true,
  9478. resolveId: true,
  9479. transform: true,
  9480. transformBundle: true
  9481. };
  9482. function getPluginWithTimers(plugin, index) {
  9483. const timedPlugin = {};
  9484. for (const hook of Object.keys(plugin)) {
  9485. if (TIMED_PLUGIN_HOOKS[hook] === true) {
  9486. let timerLabel = `plugin ${index}`;
  9487. if (plugin.name) {
  9488. timerLabel += ` (${plugin.name})`;
  9489. }
  9490. timerLabel += ` - ${hook}`;
  9491. timedPlugin[hook] = function () {
  9492. timeStart(timerLabel, 4);
  9493. const result = plugin[hook].apply(this === timedPlugin ? plugin : this, arguments);
  9494. timeEnd(timerLabel, 4);
  9495. if (result && typeof result.then === 'function') {
  9496. timeStart(`${timerLabel} (async)`, 4);
  9497. result.then(() => timeEnd(`${timerLabel} (async)`, 4));
  9498. }
  9499. return result;
  9500. };
  9501. }
  9502. else {
  9503. timedPlugin[hook] = plugin[hook];
  9504. }
  9505. }
  9506. return timedPlugin;
  9507. }
  9508. function initialiseTimers(inputOptions) {
  9509. if (inputOptions.perf) {
  9510. timers = {};
  9511. setTimeHelpers();
  9512. timeStart = timeStartImpl;
  9513. timeEnd = timeEndImpl;
  9514. inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
  9515. }
  9516. else {
  9517. timeStart = NOOP;
  9518. timeEnd = NOOP;
  9519. }
  9520. }
  9521. const defaultAcornOptions = {
  9522. ecmaVersion: 2020,
  9523. preserveParens: false,
  9524. sourceType: 'module'
  9525. };
  9526. function tryParse(module, Parser, acornOptions) {
  9527. try {
  9528. return Parser.parse(module.code, Object.assign(Object.assign(Object.assign({}, defaultAcornOptions), acornOptions), { onComment: (block, text, start, end) => module.comments.push({ block, text, start, end }) }));
  9529. }
  9530. catch (err) {
  9531. let message = err.message.replace(/ \(\d+:\d+\)$/, '');
  9532. if (module.id.endsWith('.json')) {
  9533. message += ' (Note that you need @rollup/plugin-json to import JSON files)';
  9534. }
  9535. else if (!module.id.endsWith('.js')) {
  9536. message += ' (Note that you need plugins to import files that are not JavaScript)';
  9537. }
  9538. return module.error({
  9539. code: 'PARSE_ERROR',
  9540. message,
  9541. parserError: err
  9542. }, err.pos);
  9543. }
  9544. }
  9545. function handleMissingExport(exportName, importingModule, importedModule, importerStart) {
  9546. return importingModule.error({
  9547. code: 'MISSING_EXPORT',
  9548. message: `'${exportName}' is not exported by ${relativeId(importedModule)}, imported by ${relativeId(importingModule.id)}`,
  9549. url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
  9550. }, importerStart);
  9551. }
  9552. const MISSING_EXPORT_SHIM_DESCRIPTION = {
  9553. identifier: null,
  9554. localName: MISSING_EXPORT_SHIM_VARIABLE
  9555. };
  9556. function getVariableForExportNameRecursive(target, name, isExportAllSearch, searchedNamesAndModules = new Map()) {
  9557. const searchedModules = searchedNamesAndModules.get(name);
  9558. if (searchedModules) {
  9559. if (searchedModules.has(target)) {
  9560. return null;
  9561. }
  9562. searchedModules.add(target);
  9563. }
  9564. else {
  9565. searchedNamesAndModules.set(name, new Set([target]));
  9566. }
  9567. return target.getVariableForExportName(name, isExportAllSearch, searchedNamesAndModules);
  9568. }
  9569. class Module {
  9570. constructor(graph, id, moduleSideEffects, syntheticNamedExports, isEntry) {
  9571. this.chunk = null;
  9572. this.chunkFileNames = new Set();
  9573. this.chunkName = null;
  9574. this.comments = [];
  9575. this.dependencies = [];
  9576. this.dynamicallyImportedBy = [];
  9577. this.dynamicDependencies = [];
  9578. this.dynamicImports = [];
  9579. this.entryPointsHash = new Uint8Array(10);
  9580. this.execIndex = Infinity;
  9581. this.exportAllModules = [];
  9582. this.exportAllSources = new Set();
  9583. this.exports = Object.create(null);
  9584. this.exportsAll = Object.create(null);
  9585. this.exportShimVariable = new ExportShimVariable(this);
  9586. this.facadeChunk = null;
  9587. this.importDescriptions = Object.create(null);
  9588. this.importMetas = [];
  9589. this.imports = new Set();
  9590. this.isExecuted = false;
  9591. this.isUserDefinedEntryPoint = false;
  9592. this.manualChunkAlias = null;
  9593. this.reexportDescriptions = Object.create(null);
  9594. this.sources = new Set();
  9595. this.userChunkNames = new Set();
  9596. this.usesTopLevelAwait = false;
  9597. this.allExportNames = null;
  9598. this.defaultExport = null;
  9599. this.namespaceVariable = null;
  9600. this.syntheticExports = new Map();
  9601. this.transformDependencies = [];
  9602. this.transitiveReexports = null;
  9603. this.id = id;
  9604. this.graph = graph;
  9605. this.excludeFromSourcemap = /\0/.test(id);
  9606. this.context = graph.getModuleContext(id);
  9607. this.moduleSideEffects = moduleSideEffects;
  9608. this.syntheticNamedExports = syntheticNamedExports;
  9609. this.isEntryPoint = isEntry;
  9610. }
  9611. basename() {
  9612. const base = path.basename(this.id);
  9613. const ext = path.extname(this.id);
  9614. return makeLegal(ext ? base.slice(0, -ext.length) : base);
  9615. }
  9616. bindReferences() {
  9617. this.ast.bind();
  9618. }
  9619. error(props, pos) {
  9620. if (typeof pos === 'number') {
  9621. props.pos = pos;
  9622. let location = locate(this.code, pos, { offsetLine: 1 });
  9623. try {
  9624. location = getOriginalLocation(this.sourcemapChain, location);
  9625. }
  9626. catch (e) {
  9627. this.warn({
  9628. code: 'SOURCEMAP_ERROR',
  9629. loc: {
  9630. column: location.column,
  9631. file: this.id,
  9632. line: location.line
  9633. },
  9634. message: `Error when using sourcemap for reporting an error: ${e.message}`,
  9635. pos
  9636. });
  9637. }
  9638. props.loc = {
  9639. column: location.column,
  9640. file: this.id,
  9641. line: location.line
  9642. };
  9643. props.frame = getCodeFrame(this.originalCode, location.line, location.column);
  9644. }
  9645. return error(props);
  9646. }
  9647. getAllExportNames() {
  9648. if (this.allExportNames) {
  9649. return this.allExportNames;
  9650. }
  9651. const allExportNames = (this.allExportNames = new Set());
  9652. for (const name of Object.keys(this.exports)) {
  9653. allExportNames.add(name);
  9654. }
  9655. for (const name of Object.keys(this.reexportDescriptions)) {
  9656. allExportNames.add(name);
  9657. }
  9658. for (const module of this.exportAllModules) {
  9659. if (module instanceof ExternalModule) {
  9660. allExportNames.add(`*${module.id}`);
  9661. continue;
  9662. }
  9663. for (const name of module.getAllExportNames()) {
  9664. if (name !== 'default')
  9665. allExportNames.add(name);
  9666. }
  9667. }
  9668. return allExportNames;
  9669. }
  9670. getDefaultExport() {
  9671. if (this.defaultExport === null) {
  9672. this.defaultExport = undefined;
  9673. this.defaultExport = this.getVariableForExportName('default');
  9674. }
  9675. if (!this.defaultExport) {
  9676. return error({
  9677. code: Errors.SYNTHETIC_NAMED_EXPORTS_NEED_DEFAULT,
  9678. id: this.id,
  9679. message: `Modules with 'syntheticNamedExports' need a default export.`
  9680. });
  9681. }
  9682. return this.defaultExport;
  9683. }
  9684. getDynamicImportExpressions() {
  9685. return this.dynamicImports.map(({ node }) => {
  9686. const importArgument = node.source;
  9687. if (importArgument instanceof TemplateLiteral &&
  9688. importArgument.quasis.length === 1 &&
  9689. importArgument.quasis[0].value.cooked) {
  9690. return importArgument.quasis[0].value.cooked;
  9691. }
  9692. if (importArgument instanceof Literal && typeof importArgument.value === 'string') {
  9693. return importArgument.value;
  9694. }
  9695. return importArgument;
  9696. });
  9697. }
  9698. getExportNamesByVariable() {
  9699. const exportNamesByVariable = new Map();
  9700. for (const exportName of this.getAllExportNames()) {
  9701. const tracedVariable = this.getVariableForExportName(exportName);
  9702. if (!tracedVariable ||
  9703. !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
  9704. continue;
  9705. }
  9706. const existingExportNames = exportNamesByVariable.get(tracedVariable);
  9707. if (existingExportNames) {
  9708. existingExportNames.push(exportName);
  9709. }
  9710. else {
  9711. exportNamesByVariable.set(tracedVariable, [exportName]);
  9712. }
  9713. }
  9714. return exportNamesByVariable;
  9715. }
  9716. getExports() {
  9717. return Object.keys(this.exports);
  9718. }
  9719. getOrCreateNamespace() {
  9720. if (!this.namespaceVariable) {
  9721. this.namespaceVariable = new NamespaceVariable(this.astContext, this.syntheticNamedExports);
  9722. this.namespaceVariable.initialise();
  9723. }
  9724. return this.namespaceVariable;
  9725. }
  9726. getReexports() {
  9727. if (this.transitiveReexports) {
  9728. return this.transitiveReexports;
  9729. }
  9730. // to avoid infinite recursion when using circular `export * from X`
  9731. this.transitiveReexports = [];
  9732. const reexports = new Set();
  9733. for (const name in this.reexportDescriptions) {
  9734. reexports.add(name);
  9735. }
  9736. for (const module of this.exportAllModules) {
  9737. if (module instanceof ExternalModule) {
  9738. reexports.add(`*${module.id}`);
  9739. }
  9740. else {
  9741. for (const name of module.getExports().concat(module.getReexports())) {
  9742. if (name !== 'default')
  9743. reexports.add(name);
  9744. }
  9745. }
  9746. }
  9747. return (this.transitiveReexports = Array.from(reexports));
  9748. }
  9749. getRenderedExports() {
  9750. // only direct exports are counted here, not reexports at all
  9751. const renderedExports = [];
  9752. const removedExports = [];
  9753. for (const exportName in this.exports) {
  9754. const variable = this.getVariableForExportName(exportName);
  9755. (variable && variable.included ? renderedExports : removedExports).push(exportName);
  9756. }
  9757. return { renderedExports, removedExports };
  9758. }
  9759. getTransitiveDependencies() {
  9760. return this.dependencies.concat(this.getReexports()
  9761. .concat(this.getExports())
  9762. .map((exportName) => this.getVariableForExportName(exportName).module));
  9763. }
  9764. getVariableForExportName(name, isExportAllSearch, searchedNamesAndModules) {
  9765. if (name[0] === '*') {
  9766. if (name.length === 1) {
  9767. return this.getOrCreateNamespace();
  9768. }
  9769. else {
  9770. // export * from 'external'
  9771. const module = this.graph.moduleById.get(name.slice(1));
  9772. return module.getVariableForExportName('*');
  9773. }
  9774. }
  9775. // export { foo } from './other'
  9776. const reexportDeclaration = this.reexportDescriptions[name];
  9777. if (reexportDeclaration) {
  9778. const declaration = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, false, searchedNamesAndModules);
  9779. if (!declaration) {
  9780. return handleMissingExport(reexportDeclaration.localName, this, reexportDeclaration.module.id, reexportDeclaration.start);
  9781. }
  9782. return declaration;
  9783. }
  9784. const exportDeclaration = this.exports[name];
  9785. if (exportDeclaration) {
  9786. if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
  9787. return this.exportShimVariable;
  9788. }
  9789. const name = exportDeclaration.localName;
  9790. return this.traceVariable(name) || this.graph.scope.findVariable(name);
  9791. }
  9792. if (name !== 'default') {
  9793. for (const module of this.exportAllModules) {
  9794. const declaration = getVariableForExportNameRecursive(module, name, true, searchedNamesAndModules);
  9795. if (declaration)
  9796. return declaration;
  9797. }
  9798. }
  9799. // we don't want to create shims when we are just
  9800. // probing export * modules for exports
  9801. if (!isExportAllSearch) {
  9802. if (this.syntheticNamedExports) {
  9803. let syntheticExport = this.syntheticExports.get(name);
  9804. if (!syntheticExport) {
  9805. const defaultExport = this.getDefaultExport();
  9806. syntheticExport = new SyntheticNamedExportVariableVariable(this.astContext, name, defaultExport);
  9807. this.syntheticExports.set(name, syntheticExport);
  9808. return syntheticExport;
  9809. }
  9810. return syntheticExport;
  9811. }
  9812. if (this.graph.shimMissingExports) {
  9813. this.shimMissingExport(name);
  9814. return this.exportShimVariable;
  9815. }
  9816. }
  9817. return null;
  9818. }
  9819. include() {
  9820. const context = createInclusionContext();
  9821. if (this.ast.shouldBeIncluded(context))
  9822. this.ast.include(context, false);
  9823. }
  9824. includeAllExports() {
  9825. if (!this.isExecuted) {
  9826. this.graph.needsTreeshakingPass = true;
  9827. markModuleAndImpureDependenciesAsExecuted(this);
  9828. }
  9829. const context = createInclusionContext();
  9830. for (const exportName of this.getExports()) {
  9831. const variable = this.getVariableForExportName(exportName);
  9832. variable.deoptimizePath(UNKNOWN_PATH);
  9833. if (!variable.included) {
  9834. variable.include(context);
  9835. this.graph.needsTreeshakingPass = true;
  9836. }
  9837. }
  9838. for (const name of this.getReexports()) {
  9839. const variable = this.getVariableForExportName(name);
  9840. variable.deoptimizePath(UNKNOWN_PATH);
  9841. if (!variable.included) {
  9842. variable.include(context);
  9843. this.graph.needsTreeshakingPass = true;
  9844. }
  9845. if (variable instanceof ExternalVariable) {
  9846. variable.module.reexported = true;
  9847. }
  9848. }
  9849. }
  9850. includeAllInBundle() {
  9851. this.ast.include(createInclusionContext(), true);
  9852. }
  9853. isIncluded() {
  9854. return this.ast.included || (this.namespaceVariable && this.namespaceVariable.included);
  9855. }
  9856. linkDependencies() {
  9857. for (const source of this.sources) {
  9858. const id = this.resolvedIds[source].id;
  9859. if (id) {
  9860. const module = this.graph.moduleById.get(id);
  9861. this.dependencies.push(module);
  9862. }
  9863. }
  9864. for (const { resolution } of this.dynamicImports) {
  9865. if (resolution instanceof Module || resolution instanceof ExternalModule) {
  9866. this.dynamicDependencies.push(resolution);
  9867. }
  9868. }
  9869. this.addModulesToImportDescriptions(this.importDescriptions);
  9870. this.addModulesToImportDescriptions(this.reexportDescriptions);
  9871. const externalExportAllModules = [];
  9872. for (const source of this.exportAllSources) {
  9873. const module = this.graph.moduleById.get(this.resolvedIds[source].id);
  9874. (module instanceof ExternalModule ? externalExportAllModules : this.exportAllModules).push(module);
  9875. }
  9876. this.exportAllModules = this.exportAllModules.concat(externalExportAllModules);
  9877. }
  9878. render(options) {
  9879. const magicString = this.magicString.clone();
  9880. this.ast.render(magicString, options);
  9881. this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
  9882. return magicString;
  9883. }
  9884. setSource({ ast, code, customTransformCache, moduleSideEffects, originalCode, originalSourcemap, resolvedIds, sourcemapChain, syntheticNamedExports, transformDependencies, transformFiles }) {
  9885. this.code = code;
  9886. this.originalCode = originalCode;
  9887. this.originalSourcemap = originalSourcemap;
  9888. this.sourcemapChain = sourcemapChain;
  9889. if (transformFiles) {
  9890. this.transformFiles = transformFiles;
  9891. }
  9892. this.transformDependencies = transformDependencies;
  9893. this.customTransformCache = customTransformCache;
  9894. if (typeof moduleSideEffects === 'boolean') {
  9895. this.moduleSideEffects = moduleSideEffects;
  9896. }
  9897. if (typeof syntheticNamedExports === 'boolean') {
  9898. this.syntheticNamedExports = syntheticNamedExports;
  9899. }
  9900. timeStart('generate ast', 3);
  9901. this.esTreeAst = ast || tryParse(this, this.graph.acornParser, this.graph.acornOptions);
  9902. markPureCallExpressions(this.comments, this.esTreeAst);
  9903. timeEnd('generate ast', 3);
  9904. this.resolvedIds = resolvedIds || Object.create(null);
  9905. // By default, `id` is the file name. Custom resolvers and loaders
  9906. // can change that, but it makes sense to use it for the source file name
  9907. const fileName = this.id;
  9908. this.magicString = new MagicString(code, {
  9909. filename: (this.excludeFromSourcemap ? null : fileName),
  9910. indentExclusionRanges: []
  9911. });
  9912. this.removeExistingSourceMap();
  9913. timeStart('analyse ast', 3);
  9914. this.astContext = {
  9915. addDynamicImport: this.addDynamicImport.bind(this),
  9916. addExport: this.addExport.bind(this),
  9917. addImport: this.addImport.bind(this),
  9918. addImportMeta: this.addImportMeta.bind(this),
  9919. annotations: (this.graph.treeshakingOptions && this.graph.treeshakingOptions.annotations),
  9920. code,
  9921. deoptimizationTracker: this.graph.deoptimizationTracker,
  9922. error: this.error.bind(this),
  9923. fileName,
  9924. getExports: this.getExports.bind(this),
  9925. getModuleExecIndex: () => this.execIndex,
  9926. getModuleName: this.basename.bind(this),
  9927. getReexports: this.getReexports.bind(this),
  9928. importDescriptions: this.importDescriptions,
  9929. includeDynamicImport: this.includeDynamicImport.bind(this),
  9930. includeVariable: this.includeVariable.bind(this),
  9931. isCrossChunkImport: importDescription => importDescription.module.chunk !== this.chunk,
  9932. magicString: this.magicString,
  9933. module: this,
  9934. moduleContext: this.context,
  9935. nodeConstructors,
  9936. preserveModules: this.graph.preserveModules,
  9937. propertyReadSideEffects: (!this.graph.treeshakingOptions ||
  9938. this.graph.treeshakingOptions.propertyReadSideEffects),
  9939. traceExport: this.getVariableForExportName.bind(this),
  9940. traceVariable: this.traceVariable.bind(this),
  9941. treeshake: !!this.graph.treeshakingOptions,
  9942. tryCatchDeoptimization: (!this.graph.treeshakingOptions ||
  9943. this.graph.treeshakingOptions.tryCatchDeoptimization),
  9944. unknownGlobalSideEffects: (!this.graph.treeshakingOptions ||
  9945. this.graph.treeshakingOptions.unknownGlobalSideEffects),
  9946. usesTopLevelAwait: false,
  9947. warn: this.warn.bind(this),
  9948. warnDeprecation: this.graph.warnDeprecation.bind(this.graph)
  9949. };
  9950. this.scope = new ModuleScope(this.graph.scope, this.astContext);
  9951. this.ast = new Program$1(this.esTreeAst, { type: 'Module', context: this.astContext }, this.scope);
  9952. timeEnd('analyse ast', 3);
  9953. }
  9954. toJSON() {
  9955. return {
  9956. ast: this.esTreeAst,
  9957. code: this.code,
  9958. customTransformCache: this.customTransformCache,
  9959. dependencies: this.dependencies.map(module => module.id),
  9960. id: this.id,
  9961. moduleSideEffects: this.moduleSideEffects,
  9962. originalCode: this.originalCode,
  9963. originalSourcemap: this.originalSourcemap,
  9964. resolvedIds: this.resolvedIds,
  9965. sourcemapChain: this.sourcemapChain,
  9966. syntheticNamedExports: this.syntheticNamedExports,
  9967. transformDependencies: this.transformDependencies,
  9968. transformFiles: this.transformFiles
  9969. };
  9970. }
  9971. traceVariable(name) {
  9972. const localVariable = this.scope.variables.get(name);
  9973. if (localVariable) {
  9974. return localVariable;
  9975. }
  9976. if (name in this.importDescriptions) {
  9977. const importDeclaration = this.importDescriptions[name];
  9978. const otherModule = importDeclaration.module;
  9979. if (otherModule instanceof Module && importDeclaration.name === '*') {
  9980. return otherModule.getOrCreateNamespace();
  9981. }
  9982. const declaration = otherModule.getVariableForExportName(importDeclaration.name);
  9983. if (!declaration) {
  9984. return handleMissingExport(importDeclaration.name, this, otherModule.id, importDeclaration.start);
  9985. }
  9986. return declaration;
  9987. }
  9988. return null;
  9989. }
  9990. warn(warning, pos) {
  9991. if (typeof pos === 'number') {
  9992. warning.pos = pos;
  9993. const { line, column } = locate(this.code, pos, { offsetLine: 1 }); // TODO trace sourcemaps, cf. error()
  9994. warning.loc = { file: this.id, line, column };
  9995. warning.frame = getCodeFrame(this.code, line, column);
  9996. }
  9997. warning.id = this.id;
  9998. this.graph.warn(warning);
  9999. }
  10000. addDynamicImport(node) {
  10001. this.dynamicImports.push({ node, resolution: null });
  10002. }
  10003. addExport(node) {
  10004. if (node instanceof ExportDefaultDeclaration) {
  10005. // export default foo;
  10006. this.exports.default = {
  10007. identifier: node.variable.getAssignedVariableName(),
  10008. localName: 'default'
  10009. };
  10010. }
  10011. else if (node instanceof ExportAllDeclaration) {
  10012. // export * from './other'
  10013. const source = node.source.value;
  10014. this.sources.add(source);
  10015. this.exportAllSources.add(source);
  10016. }
  10017. else if (node.source instanceof Literal) {
  10018. // export { name } from './other'
  10019. const source = node.source.value;
  10020. this.sources.add(source);
  10021. for (const specifier of node.specifiers) {
  10022. const name = specifier.exported.name;
  10023. this.reexportDescriptions[name] = {
  10024. localName: specifier.type === ExportNamespaceSpecifier ? '*' : specifier.local.name,
  10025. module: null,
  10026. source,
  10027. start: specifier.start
  10028. };
  10029. }
  10030. }
  10031. else if (node.declaration) {
  10032. const declaration = node.declaration;
  10033. if (declaration instanceof VariableDeclaration) {
  10034. // export var { foo, bar } = ...
  10035. // export var foo = 1, bar = 2;
  10036. for (const declarator of declaration.declarations) {
  10037. for (const localName of extractAssignedNames(declarator.id)) {
  10038. this.exports[localName] = { identifier: null, localName };
  10039. }
  10040. }
  10041. }
  10042. else {
  10043. // export function foo () {}
  10044. const localName = declaration.id.name;
  10045. this.exports[localName] = { identifier: null, localName };
  10046. }
  10047. }
  10048. else {
  10049. // export { foo, bar, baz }
  10050. for (const specifier of node.specifiers) {
  10051. const localName = specifier.local.name;
  10052. const exportedName = specifier.exported.name;
  10053. this.exports[exportedName] = { identifier: null, localName };
  10054. }
  10055. }
  10056. }
  10057. addImport(node) {
  10058. const source = node.source.value;
  10059. this.sources.add(source);
  10060. for (const specifier of node.specifiers) {
  10061. const localName = specifier.local.name;
  10062. if (this.importDescriptions[localName]) {
  10063. return this.error({
  10064. code: 'DUPLICATE_IMPORT',
  10065. message: `Duplicated import '${localName}'`
  10066. }, specifier.start);
  10067. }
  10068. const isDefault = specifier.type === ImportDefaultSpecifier;
  10069. const isNamespace = specifier.type === ImportNamespaceSpecifier;
  10070. const name = isDefault
  10071. ? 'default'
  10072. : isNamespace
  10073. ? '*'
  10074. : specifier.imported.name;
  10075. this.importDescriptions[localName] = {
  10076. module: null,
  10077. name,
  10078. source,
  10079. start: specifier.start
  10080. };
  10081. }
  10082. }
  10083. addImportMeta(node) {
  10084. this.importMetas.push(node);
  10085. }
  10086. addModulesToImportDescriptions(importDescription) {
  10087. for (const name of Object.keys(importDescription)) {
  10088. const specifier = importDescription[name];
  10089. const id = this.resolvedIds[specifier.source].id;
  10090. specifier.module = this.graph.moduleById.get(id);
  10091. }
  10092. }
  10093. includeDynamicImport(node) {
  10094. const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
  10095. if (resolution instanceof Module) {
  10096. resolution.dynamicallyImportedBy.push(this);
  10097. resolution.includeAllExports();
  10098. }
  10099. }
  10100. includeVariable(context, variable) {
  10101. const variableModule = variable.module;
  10102. if (!variable.included) {
  10103. variable.include(context);
  10104. this.graph.needsTreeshakingPass = true;
  10105. }
  10106. if (variableModule && variableModule !== this) {
  10107. this.imports.add(variable);
  10108. }
  10109. }
  10110. removeExistingSourceMap() {
  10111. for (const comment of this.comments) {
  10112. if (!comment.block && SOURCEMAPPING_URL_RE.test(comment.text)) {
  10113. this.magicString.remove(comment.start, comment.end);
  10114. }
  10115. }
  10116. }
  10117. shimMissingExport(name) {
  10118. if (!this.exports[name]) {
  10119. this.graph.warn({
  10120. code: 'SHIMMED_EXPORT',
  10121. exporter: relativeId(this.id),
  10122. exportName: name,
  10123. message: `Missing export "${name}" has been shimmed in module ${relativeId(this.id)}.`
  10124. });
  10125. this.exports[name] = MISSING_EXPORT_SHIM_DESCRIPTION;
  10126. }
  10127. }
  10128. }
  10129. class Source {
  10130. constructor(filename, content) {
  10131. this.isOriginal = true;
  10132. this.filename = filename;
  10133. this.content = content;
  10134. }
  10135. traceSegment(line, column, name) {
  10136. return { line, column, name, source: this };
  10137. }
  10138. }
  10139. class Link {
  10140. constructor(map, sources) {
  10141. this.sources = sources;
  10142. this.names = map.names;
  10143. this.mappings = map.mappings;
  10144. }
  10145. traceMappings() {
  10146. const sources = [];
  10147. const sourcesContent = [];
  10148. const names = [];
  10149. const mappings = [];
  10150. for (const line of this.mappings) {
  10151. const tracedLine = [];
  10152. for (const segment of line) {
  10153. if (segment.length == 1)
  10154. continue;
  10155. const source = this.sources[segment[1]];
  10156. if (!source)
  10157. continue;
  10158. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
  10159. if (traced) {
  10160. // newer sources are more likely to be used, so search backwards.
  10161. let sourceIndex = sources.lastIndexOf(traced.source.filename);
  10162. if (sourceIndex === -1) {
  10163. sourceIndex = sources.length;
  10164. sources.push(traced.source.filename);
  10165. sourcesContent[sourceIndex] = traced.source.content;
  10166. }
  10167. else if (sourcesContent[sourceIndex] == null) {
  10168. sourcesContent[sourceIndex] = traced.source.content;
  10169. }
  10170. else if (traced.source.content != null &&
  10171. sourcesContent[sourceIndex] !== traced.source.content) {
  10172. return error({
  10173. message: `Multiple conflicting contents for sourcemap source ${traced.source.filename}`
  10174. });
  10175. }
  10176. const tracedSegment = [
  10177. segment[0],
  10178. sourceIndex,
  10179. traced.line,
  10180. traced.column
  10181. ];
  10182. if (traced.name) {
  10183. let nameIndex = names.indexOf(traced.name);
  10184. if (nameIndex === -1) {
  10185. nameIndex = names.length;
  10186. names.push(traced.name);
  10187. }
  10188. tracedSegment[4] = nameIndex;
  10189. }
  10190. tracedLine.push(tracedSegment);
  10191. }
  10192. }
  10193. mappings.push(tracedLine);
  10194. }
  10195. return { sources, sourcesContent, names, mappings };
  10196. }
  10197. traceSegment(line, column, name) {
  10198. const segments = this.mappings[line];
  10199. if (!segments)
  10200. return null;
  10201. // binary search through segments for the given column
  10202. let i = 0;
  10203. let j = segments.length - 1;
  10204. while (i <= j) {
  10205. const m = (i + j) >> 1;
  10206. const segment = segments[m];
  10207. if (segment[0] === column) {
  10208. if (segment.length == 1)
  10209. return null;
  10210. const source = this.sources[segment[1]];
  10211. if (!source)
  10212. return null;
  10213. return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
  10214. }
  10215. if (segment[0] > column) {
  10216. j = m - 1;
  10217. }
  10218. else {
  10219. i = m + 1;
  10220. }
  10221. }
  10222. return null;
  10223. }
  10224. }
  10225. function getLinkMap(graph) {
  10226. return function linkMap(source, map) {
  10227. if (map.mappings) {
  10228. return new Link(map, [source]);
  10229. }
  10230. graph.warn({
  10231. code: 'SOURCEMAP_BROKEN',
  10232. message: `Sourcemap is likely to be incorrect: a plugin (${map.plugin}) was used to transform ` +
  10233. "files, but didn't generate a sourcemap for the transformation. Consult the plugin " +
  10234. 'documentation for help',
  10235. plugin: map.plugin,
  10236. url: `https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect`
  10237. });
  10238. return new Link({
  10239. mappings: [],
  10240. names: []
  10241. }, [source]);
  10242. };
  10243. }
  10244. function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
  10245. let source;
  10246. if (!originalSourcemap) {
  10247. source = new Source(id, originalCode);
  10248. }
  10249. else {
  10250. const sources = originalSourcemap.sources;
  10251. const sourcesContent = originalSourcemap.sourcesContent || [];
  10252. // TODO indiscriminately treating IDs and sources as normal paths is probably bad.
  10253. const directory = path.dirname(id) || '.';
  10254. const sourceRoot = originalSourcemap.sourceRoot || '.';
  10255. const baseSources = sources.map((source, i) => new Source(path.resolve(directory, sourceRoot, source), sourcesContent[i]));
  10256. source = new Link(originalSourcemap, baseSources);
  10257. }
  10258. return sourcemapChain.reduce(linkMap, source);
  10259. }
  10260. function collapseSourcemaps(bundle, file, map, modules, bundleSourcemapChain, excludeContent) {
  10261. const linkMap = getLinkMap(bundle.graph);
  10262. const moduleSources = modules
  10263. .filter(module => !module.excludeFromSourcemap)
  10264. .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
  10265. // DecodedSourceMap (from magic-string) uses a number[] instead of the more
  10266. // correct SourceMapSegment tuples. Cast it here to gain type safety.
  10267. let source = new Link(map, moduleSources);
  10268. source = bundleSourcemapChain.reduce(linkMap, source);
  10269. let { sources, sourcesContent, names, mappings } = source.traceMappings();
  10270. if (file) {
  10271. const directory = path.dirname(file);
  10272. sources = sources.map((source) => path.relative(directory, source));
  10273. file = path.basename(file);
  10274. }
  10275. sourcesContent = (excludeContent ? null : sourcesContent);
  10276. return new SourceMap({ file, sources, sourcesContent, names, mappings });
  10277. }
  10278. function collapseSourcemap(graph, id, originalCode, originalSourcemap, sourcemapChain) {
  10279. if (!sourcemapChain.length) {
  10280. return originalSourcemap;
  10281. }
  10282. const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(graph));
  10283. const map = source.traceMappings();
  10284. return Object.assign({ version: 3 }, map);
  10285. }
  10286. const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
  10287. amd: deconflictImportsOther,
  10288. cjs: deconflictImportsOther,
  10289. es: deconflictImportsEsm,
  10290. iife: deconflictImportsOther,
  10291. system: deconflictImportsEsm,
  10292. umd: deconflictImportsOther
  10293. };
  10294. function deconflictChunk(modules, dependencies, imports, usedNames, format, interop, preserveModules) {
  10295. for (const module of modules) {
  10296. module.scope.addUsedOutsideNames(usedNames, format);
  10297. }
  10298. deconflictTopLevelVariables(usedNames, modules);
  10299. DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependencies, interop, preserveModules);
  10300. for (const module of modules) {
  10301. module.scope.deconflict(format);
  10302. }
  10303. }
  10304. function deconflictImportsEsm(usedNames, imports, _dependencies, interop) {
  10305. for (const variable of imports) {
  10306. const module = variable.module;
  10307. const name = variable.name;
  10308. let proposedName;
  10309. if (module instanceof ExternalModule && (name === '*' || name === 'default')) {
  10310. if (name === 'default' && interop && module.exportsNamespace) {
  10311. proposedName = module.variableName + '__default';
  10312. }
  10313. else {
  10314. proposedName = module.variableName;
  10315. }
  10316. }
  10317. else {
  10318. proposedName = name;
  10319. }
  10320. variable.setRenderNames(null, getSafeName(proposedName, usedNames));
  10321. }
  10322. }
  10323. function deconflictImportsOther(usedNames, imports, dependencies, interop, preserveModules) {
  10324. for (const chunkOrExternalModule of dependencies) {
  10325. chunkOrExternalModule.variableName = getSafeName(chunkOrExternalModule.variableName, usedNames);
  10326. }
  10327. for (const variable of imports) {
  10328. const module = variable.module;
  10329. if (module instanceof ExternalModule) {
  10330. const name = variable.name;
  10331. if (name === 'default' && interop && (module.exportsNamespace || module.exportsNames)) {
  10332. variable.setRenderNames(null, module.variableName + '__default');
  10333. }
  10334. else if (name === '*' || name === 'default') {
  10335. variable.setRenderNames(null, module.variableName);
  10336. }
  10337. else {
  10338. variable.setRenderNames(module.variableName, null);
  10339. }
  10340. }
  10341. else {
  10342. const chunk = module.chunk;
  10343. if (chunk.exportMode === 'default' || (preserveModules && variable.isNamespace)) {
  10344. variable.setRenderNames(null, chunk.variableName);
  10345. }
  10346. else {
  10347. variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
  10348. }
  10349. }
  10350. }
  10351. }
  10352. function deconflictTopLevelVariables(usedNames, modules) {
  10353. for (const module of modules) {
  10354. for (const variable of module.scope.variables.values()) {
  10355. if (variable.included &&
  10356. // this will only happen for exports in some formats
  10357. !(variable.renderBaseName ||
  10358. (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
  10359. variable.setRenderNames(null, getSafeName(variable.name, usedNames));
  10360. }
  10361. }
  10362. const namespace = module.getOrCreateNamespace();
  10363. if (namespace.included) {
  10364. namespace.setRenderNames(null, getSafeName(namespace.name, usedNames));
  10365. }
  10366. }
  10367. }
  10368. const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
  10369. function sortByExecutionOrder(units) {
  10370. units.sort(compareExecIndex);
  10371. }
  10372. function analyseModuleExecution(entryModules) {
  10373. let nextExecIndex = 0;
  10374. const cyclePaths = [];
  10375. const analysedModules = {};
  10376. const orderedModules = [];
  10377. const dynamicImports = [];
  10378. const parents = {};
  10379. const analyseModule = (module) => {
  10380. if (analysedModules[module.id])
  10381. return;
  10382. if (module instanceof ExternalModule) {
  10383. module.execIndex = nextExecIndex++;
  10384. analysedModules[module.id] = true;
  10385. return;
  10386. }
  10387. for (const dependency of module.dependencies) {
  10388. if (dependency.id in parents) {
  10389. if (!analysedModules[dependency.id]) {
  10390. cyclePaths.push(getCyclePath(dependency.id, module.id, parents));
  10391. }
  10392. continue;
  10393. }
  10394. parents[dependency.id] = module.id;
  10395. analyseModule(dependency);
  10396. }
  10397. for (const { resolution } of module.dynamicImports) {
  10398. if (resolution instanceof Module && dynamicImports.indexOf(resolution) === -1) {
  10399. dynamicImports.push(resolution);
  10400. }
  10401. }
  10402. module.execIndex = nextExecIndex++;
  10403. analysedModules[module.id] = true;
  10404. orderedModules.push(module);
  10405. };
  10406. for (const curEntry of entryModules) {
  10407. if (!parents[curEntry.id]) {
  10408. parents[curEntry.id] = null;
  10409. analyseModule(curEntry);
  10410. }
  10411. }
  10412. for (const curEntry of dynamicImports) {
  10413. if (!parents[curEntry.id]) {
  10414. parents[curEntry.id] = null;
  10415. analyseModule(curEntry);
  10416. }
  10417. }
  10418. return { orderedModules, cyclePaths };
  10419. }
  10420. function getCyclePath(id, parentId, parents) {
  10421. const path = [relativeId(id)];
  10422. let curId = parentId;
  10423. while (curId !== id) {
  10424. path.push(relativeId(curId));
  10425. curId = parents[curId];
  10426. if (!curId)
  10427. break;
  10428. }
  10429. path.push(path[0]);
  10430. path.reverse();
  10431. return path;
  10432. }
  10433. function guessIndentString(code) {
  10434. const lines = code.split('\n');
  10435. const tabbed = lines.filter(line => /^\t+/.test(line));
  10436. const spaced = lines.filter(line => /^ {2,}/.test(line));
  10437. if (tabbed.length === 0 && spaced.length === 0) {
  10438. return null;
  10439. }
  10440. // More lines tabbed than spaced? Assume tabs, and
  10441. // default to tabs in the case of a tie (or nothing
  10442. // to go on)
  10443. if (tabbed.length >= spaced.length) {
  10444. return '\t';
  10445. }
  10446. // Otherwise, we need to guess the multiple
  10447. const min = spaced.reduce((previous, current) => {
  10448. const numSpaces = /^ +/.exec(current)[0].length;
  10449. return Math.min(numSpaces, previous);
  10450. }, Infinity);
  10451. return new Array(min + 1).join(' ');
  10452. }
  10453. function getIndentString(modules, options) {
  10454. if (options.indent !== true)
  10455. return options.indent || '';
  10456. for (let i = 0; i < modules.length; i++) {
  10457. const indent = guessIndentString(modules[i].originalCode);
  10458. if (indent !== null)
  10459. return indent;
  10460. }
  10461. return '\t';
  10462. }
  10463. function decodedSourcemap(map) {
  10464. if (!map)
  10465. return null;
  10466. if (typeof map === 'string') {
  10467. map = JSON.parse(map);
  10468. }
  10469. if (map.mappings === '') {
  10470. return {
  10471. mappings: [],
  10472. names: [],
  10473. sources: [],
  10474. version: 3
  10475. };
  10476. }
  10477. let mappings;
  10478. if (typeof map.mappings === 'string') {
  10479. mappings = decode(map.mappings);
  10480. }
  10481. else {
  10482. mappings = map.mappings;
  10483. }
  10484. return Object.assign(Object.assign({}, map), { mappings });
  10485. }
  10486. function renderChunk({ chunk, code, options, outputPluginDriver, renderChunk, sourcemapChain }) {
  10487. const renderChunkReducer = (code, result, plugin) => {
  10488. if (result == null)
  10489. return code;
  10490. if (typeof result === 'string')
  10491. result = {
  10492. code: result,
  10493. map: undefined
  10494. };
  10495. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  10496. if (result.map !== null) {
  10497. const map = decodedSourcemap(result.map);
  10498. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  10499. }
  10500. return result.code;
  10501. };
  10502. let inTransformBundle = false;
  10503. let inRenderChunk = true;
  10504. return outputPluginDriver
  10505. .hookReduceArg0('renderChunk', [code, renderChunk, options], renderChunkReducer)
  10506. .then(code => {
  10507. inRenderChunk = false;
  10508. return outputPluginDriver.hookReduceArg0('transformChunk', [code, options, chunk], renderChunkReducer);
  10509. })
  10510. .then(code => {
  10511. inTransformBundle = true;
  10512. return outputPluginDriver.hookReduceArg0('transformBundle', [code, options, chunk], renderChunkReducer);
  10513. })
  10514. .catch(err => {
  10515. if (inRenderChunk)
  10516. throw err;
  10517. return error(err, {
  10518. code: inTransformBundle ? 'BAD_BUNDLE_TRANSFORMER' : 'BAD_CHUNK_TRANSFORMER',
  10519. message: `Error transforming ${(inTransformBundle ? 'bundle' : 'chunk') +
  10520. (err.plugin ? ` with '${err.plugin}' plugin` : '')}: ${err.message}`,
  10521. plugin: err.plugin
  10522. });
  10523. });
  10524. }
  10525. function renderNamePattern(pattern, patternName, replacements) {
  10526. if (!isPlainPathFragment(pattern))
  10527. return error(errFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths and must not contain invalid characters.`));
  10528. return pattern.replace(/\[(\w+)\]/g, (_match, type) => {
  10529. if (!replacements.hasOwnProperty(type)) {
  10530. return error(errFailedValidation(`"[${type}]" is not a valid placeholder in "${patternName}" pattern.`));
  10531. }
  10532. const replacement = replacements[type]();
  10533. if (!isPlainPathFragment(replacement))
  10534. return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
  10535. return replacement;
  10536. });
  10537. }
  10538. function makeUnique(name, existingNames) {
  10539. const existingNamesLowercase = new Set(Object.keys(existingNames).map(key => key.toLowerCase()));
  10540. if (!existingNamesLowercase.has(name.toLocaleLowerCase()))
  10541. return name;
  10542. const ext = path.extname(name);
  10543. name = name.substr(0, name.length - ext.length);
  10544. let uniqueName, uniqueIndex = 1;
  10545. while (existingNamesLowercase.has((uniqueName = name + ++uniqueIndex + ext).toLowerCase()))
  10546. ;
  10547. return uniqueName;
  10548. }
  10549. const NON_ASSET_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx'];
  10550. function getGlobalName(module, globals, graph, hasExports) {
  10551. let globalName;
  10552. if (typeof globals === 'function') {
  10553. globalName = globals(module.id);
  10554. }
  10555. else if (globals) {
  10556. globalName = globals[module.id];
  10557. }
  10558. if (globalName) {
  10559. return globalName;
  10560. }
  10561. if (hasExports) {
  10562. graph.warn({
  10563. code: 'MISSING_GLOBAL_NAME',
  10564. guess: module.variableName,
  10565. message: `No name was provided for external module '${module.id}' in output.globals – guessing '${module.variableName}'`,
  10566. source: module.id
  10567. });
  10568. return module.variableName;
  10569. }
  10570. }
  10571. function isChunkRendered(chunk) {
  10572. return !chunk.isEmpty || chunk.entryModules.length > 0 || chunk.manualChunkAlias !== null;
  10573. }
  10574. class Chunk$1 {
  10575. constructor(graph, orderedModules) {
  10576. this.entryModules = [];
  10577. this.exportMode = 'named';
  10578. this.facadeModule = null;
  10579. this.id = null;
  10580. this.indentString = undefined;
  10581. this.manualChunkAlias = null;
  10582. this.usedModules = undefined;
  10583. this.variableName = 'chunk';
  10584. this.dependencies = undefined;
  10585. this.dynamicDependencies = undefined;
  10586. this.exportNames = Object.create(null);
  10587. this.exports = new Set();
  10588. this.fileName = null;
  10589. this.imports = new Set();
  10590. this.name = null;
  10591. this.needsExportsShim = false;
  10592. this.renderedDeclarations = undefined;
  10593. this.renderedHash = undefined;
  10594. this.renderedModuleSources = new Map();
  10595. this.renderedSource = null;
  10596. this.renderedSourceLength = undefined;
  10597. this.sortedExportNames = null;
  10598. this.graph = graph;
  10599. this.orderedModules = orderedModules;
  10600. this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
  10601. this.isEmpty = true;
  10602. for (const module of orderedModules) {
  10603. if (this.isEmpty && module.isIncluded()) {
  10604. this.isEmpty = false;
  10605. }
  10606. if (module.manualChunkAlias) {
  10607. this.manualChunkAlias = module.manualChunkAlias;
  10608. }
  10609. module.chunk = this;
  10610. if (module.isEntryPoint ||
  10611. module.dynamicallyImportedBy.some(module => orderedModules.indexOf(module) === -1)) {
  10612. this.entryModules.push(module);
  10613. }
  10614. }
  10615. const moduleForNaming = this.entryModules[0] || this.orderedModules[this.orderedModules.length - 1];
  10616. if (moduleForNaming) {
  10617. this.variableName = makeLegal(path.basename(moduleForNaming.chunkName ||
  10618. moduleForNaming.manualChunkAlias ||
  10619. getAliasName(moduleForNaming.id)));
  10620. }
  10621. }
  10622. static generateFacade(graph, facadedModule, facadeName) {
  10623. const chunk = new Chunk$1(graph, []);
  10624. chunk.assignFacadeName(facadeName, facadedModule);
  10625. if (!facadedModule.facadeChunk) {
  10626. facadedModule.facadeChunk = chunk;
  10627. }
  10628. chunk.dependencies = [facadedModule.chunk];
  10629. chunk.dynamicDependencies = [];
  10630. chunk.facadeModule = facadedModule;
  10631. for (const exportName of facadedModule.getAllExportNames()) {
  10632. const tracedVariable = facadedModule.getVariableForExportName(exportName);
  10633. chunk.exports.add(tracedVariable);
  10634. chunk.exportNames[exportName] = tracedVariable;
  10635. }
  10636. return chunk;
  10637. }
  10638. canModuleBeFacade(moduleExportNamesByVariable) {
  10639. for (const exposedVariable of this.exports) {
  10640. if (!moduleExportNamesByVariable.has(exposedVariable)) {
  10641. return false;
  10642. }
  10643. }
  10644. return true;
  10645. }
  10646. generateFacades() {
  10647. const facades = [];
  10648. for (const module of this.entryModules) {
  10649. const requiredFacades = Array.from(module.userChunkNames).map(name => ({
  10650. name
  10651. }));
  10652. if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
  10653. requiredFacades.push({});
  10654. }
  10655. requiredFacades.push(...Array.from(module.chunkFileNames).map(fileName => ({ fileName })));
  10656. if (requiredFacades.length === 0) {
  10657. requiredFacades.push({});
  10658. }
  10659. if (!this.facadeModule) {
  10660. const exportNamesByVariable = module.getExportNamesByVariable();
  10661. if (this.graph.preserveModules || this.canModuleBeFacade(exportNamesByVariable)) {
  10662. this.facadeModule = module;
  10663. module.facadeChunk = this;
  10664. for (const [variable, exportNames] of exportNamesByVariable) {
  10665. for (const exportName of exportNames) {
  10666. this.exportNames[exportName] = variable;
  10667. }
  10668. }
  10669. this.assignFacadeName(requiredFacades.shift(), module);
  10670. }
  10671. }
  10672. for (const facadeName of requiredFacades) {
  10673. facades.push(Chunk$1.generateFacade(this.graph, module, facadeName));
  10674. }
  10675. }
  10676. return facades;
  10677. }
  10678. generateId(addons, options, existingNames, includeHash, outputPluginDriver) {
  10679. if (this.fileName !== null) {
  10680. return this.fileName;
  10681. }
  10682. const [pattern, patternName] = this.facadeModule && this.facadeModule.isUserDefinedEntryPoint
  10683. ? [options.entryFileNames || '[name].js', 'output.entryFileNames']
  10684. : [options.chunkFileNames || '[name]-[hash].js', 'output.chunkFileNames'];
  10685. return makeUnique(renderNamePattern(pattern, patternName, {
  10686. format: () => (options.format === 'es' ? 'esm' : options.format),
  10687. hash: () => includeHash
  10688. ? this.computeContentHashWithDependencies(addons, options, existingNames, outputPluginDriver)
  10689. : '[hash]',
  10690. name: () => this.getChunkName()
  10691. }), existingNames);
  10692. }
  10693. generateIdPreserveModules(preserveModulesRelativeDir, options, existingNames) {
  10694. const id = this.orderedModules[0].id;
  10695. const sanitizedId = sanitizeFileName(id);
  10696. let path$1;
  10697. if (isAbsolute(id)) {
  10698. const extension = path.extname(id);
  10699. const name = renderNamePattern(options.entryFileNames ||
  10700. (NON_ASSET_EXTENSIONS.includes(extension) ? '[name].js' : '[name][extname].js'), 'output.entryFileNames', {
  10701. ext: () => extension.substr(1),
  10702. extname: () => extension,
  10703. format: () => (options.format === 'es' ? 'esm' : options.format),
  10704. name: () => this.getChunkName()
  10705. });
  10706. path$1 = relative(preserveModulesRelativeDir, `${path.dirname(sanitizedId)}/${name}`);
  10707. }
  10708. else {
  10709. path$1 = `_virtual/${path.basename(sanitizedId)}`;
  10710. }
  10711. return makeUnique(normalize(path$1), existingNames);
  10712. }
  10713. generateInternalExports(options) {
  10714. if (this.facadeModule !== null)
  10715. return;
  10716. const mangle = options.format === 'system' || options.format === 'es' || options.compact;
  10717. let i = 0, safeExportName;
  10718. this.exportNames = Object.create(null);
  10719. this.sortedExportNames = null;
  10720. if (mangle) {
  10721. for (const variable of this.exports) {
  10722. const suggestedName = variable.name[0];
  10723. if (!this.exportNames[suggestedName]) {
  10724. this.exportNames[suggestedName] = variable;
  10725. }
  10726. else {
  10727. do {
  10728. safeExportName = toBase64(++i);
  10729. // skip past leading number identifiers
  10730. if (safeExportName.charCodeAt(0) === 49 /* '1' */) {
  10731. i += 9 * Math.pow(64, (safeExportName.length - 1));
  10732. safeExportName = toBase64(i);
  10733. }
  10734. } while (RESERVED_NAMES[safeExportName] || this.exportNames[safeExportName]);
  10735. this.exportNames[safeExportName] = variable;
  10736. }
  10737. }
  10738. }
  10739. else {
  10740. for (const variable of this.exports) {
  10741. i = 0;
  10742. safeExportName = variable.name;
  10743. while (this.exportNames[safeExportName]) {
  10744. safeExportName = variable.name + '$' + ++i;
  10745. }
  10746. this.exportNames[safeExportName] = variable;
  10747. }
  10748. }
  10749. }
  10750. getChunkName() {
  10751. return this.name || (this.name = sanitizeFileName(this.getFallbackChunkName()));
  10752. }
  10753. getDynamicImportIds() {
  10754. return this.dynamicDependencies.map(chunk => chunk.id).filter(Boolean);
  10755. }
  10756. getExportNames() {
  10757. return (this.sortedExportNames || (this.sortedExportNames = Object.keys(this.exportNames).sort()));
  10758. }
  10759. getImportIds() {
  10760. return this.dependencies.map(chunk => chunk.id).filter(Boolean);
  10761. }
  10762. getRenderedHash(outputPluginDriver) {
  10763. if (this.renderedHash)
  10764. return this.renderedHash;
  10765. if (!this.renderedSource)
  10766. return '';
  10767. const hash = createHash();
  10768. const hashAugmentation = this.calculateHashAugmentation(outputPluginDriver);
  10769. hash.update(hashAugmentation);
  10770. hash.update(this.renderedSource.toString());
  10771. hash.update(this.getExportNames()
  10772. .map(exportName => {
  10773. const variable = this.exportNames[exportName];
  10774. return `${relativeId(variable.module.id).replace(/\\/g, '/')}:${variable.name}:${exportName}`;
  10775. })
  10776. .join(','));
  10777. return (this.renderedHash = hash.digest('hex'));
  10778. }
  10779. getRenderedSourceLength() {
  10780. if (this.renderedSourceLength !== undefined)
  10781. return this.renderedSourceLength;
  10782. return (this.renderedSourceLength = this.renderedSource.length());
  10783. }
  10784. getVariableExportName(variable) {
  10785. if (this.graph.preserveModules && variable instanceof NamespaceVariable) {
  10786. return '*';
  10787. }
  10788. for (const exportName of Object.keys(this.exportNames)) {
  10789. if (this.exportNames[exportName] === variable)
  10790. return exportName;
  10791. }
  10792. throw new Error(`Internal Error: Could not find export name for variable ${variable.name}.`);
  10793. }
  10794. link() {
  10795. const dependencies = new Set();
  10796. const dynamicDependencies = new Set();
  10797. for (const module of this.orderedModules) {
  10798. this.addDependenciesToChunk(module.getTransitiveDependencies(), dependencies);
  10799. this.addDependenciesToChunk(module.dynamicDependencies, dynamicDependencies);
  10800. this.setUpChunkImportsAndExportsForModule(module);
  10801. }
  10802. this.dependencies = Array.from(dependencies);
  10803. this.dynamicDependencies = Array.from(dynamicDependencies);
  10804. }
  10805. /*
  10806. * Performs a full merge of another chunk into this chunk
  10807. * chunkList allows updating references in other chunks for the merged chunk to this chunk
  10808. * A new facade will be added to chunkList if tainting exports of either as an entry point
  10809. */
  10810. merge(chunk, chunkList, options, inputBase) {
  10811. if (this.facadeModule !== null || chunk.facadeModule !== null)
  10812. throw new Error('Internal error: Code splitting chunk merges not supported for facades');
  10813. for (const module of chunk.orderedModules) {
  10814. module.chunk = this;
  10815. this.orderedModules.push(module);
  10816. }
  10817. for (const variable of chunk.imports) {
  10818. if (!this.imports.has(variable) && variable.module.chunk !== this) {
  10819. this.imports.add(variable);
  10820. }
  10821. }
  10822. // NB detect when exported variables are orphaned by the merge itself
  10823. // (involves reverse tracing dependents)
  10824. for (const variable of chunk.exports) {
  10825. if (!this.exports.has(variable)) {
  10826. this.exports.add(variable);
  10827. }
  10828. }
  10829. const thisOldExportNames = this.exportNames;
  10830. // regenerate internal names
  10831. this.generateInternalExports(options);
  10832. const updateRenderedDeclaration = (dep, oldExportNames) => {
  10833. if (dep.imports) {
  10834. for (const impt of dep.imports) {
  10835. impt.imported = this.getVariableExportName(oldExportNames[impt.imported]);
  10836. }
  10837. }
  10838. if (dep.reexports) {
  10839. for (const reexport of dep.reexports) {
  10840. reexport.imported = this.getVariableExportName(oldExportNames[reexport.imported]);
  10841. }
  10842. }
  10843. };
  10844. const mergeRenderedDeclaration = (into, from) => {
  10845. if (from.imports) {
  10846. if (!into.imports) {
  10847. into.imports = from.imports;
  10848. }
  10849. else {
  10850. into.imports = into.imports.concat(from.imports);
  10851. }
  10852. }
  10853. if (from.reexports) {
  10854. if (!into.reexports) {
  10855. into.reexports = from.reexports;
  10856. }
  10857. else {
  10858. into.reexports = into.reexports.concat(from.reexports);
  10859. }
  10860. }
  10861. if (!into.exportsNames && from.exportsNames) {
  10862. into.exportsNames = true;
  10863. }
  10864. if (!into.exportsDefault && from.exportsDefault) {
  10865. into.exportsDefault = true;
  10866. }
  10867. into.name = this.variableName;
  10868. };
  10869. // go through the other chunks and update their dependencies
  10870. // also update their import and reexport names in the process
  10871. for (const c of chunkList) {
  10872. let includedDeclaration = undefined;
  10873. for (let i = 0; i < c.dependencies.length; i++) {
  10874. const dep = c.dependencies[i];
  10875. if ((dep === chunk || dep === this) && includedDeclaration) {
  10876. const duplicateDeclaration = c.renderedDeclarations.dependencies[i];
  10877. updateRenderedDeclaration(duplicateDeclaration, dep === chunk ? chunk.exportNames : thisOldExportNames);
  10878. mergeRenderedDeclaration(includedDeclaration, duplicateDeclaration);
  10879. c.renderedDeclarations.dependencies.splice(i, 1);
  10880. c.dependencies.splice(i--, 1);
  10881. }
  10882. else if (dep === chunk) {
  10883. c.dependencies[i] = this;
  10884. includedDeclaration = c.renderedDeclarations.dependencies[i];
  10885. updateRenderedDeclaration(includedDeclaration, chunk.exportNames);
  10886. }
  10887. else if (dep === this) {
  10888. includedDeclaration = c.renderedDeclarations.dependencies[i];
  10889. updateRenderedDeclaration(includedDeclaration, thisOldExportNames);
  10890. }
  10891. }
  10892. }
  10893. // re-render the merged chunk
  10894. this.preRender(options, inputBase);
  10895. }
  10896. // prerender allows chunk hashes and names to be generated before finalizing
  10897. preRender(options, inputBase) {
  10898. timeStart('render modules', 3);
  10899. const magicString = new Bundle({ separator: options.compact ? '' : '\n\n' });
  10900. this.usedModules = [];
  10901. this.indentString = options.compact ? '' : getIndentString(this.orderedModules, options);
  10902. const n = options.compact ? '' : '\n';
  10903. const _ = options.compact ? '' : ' ';
  10904. const renderOptions = {
  10905. compact: options.compact,
  10906. dynamicImportFunction: options.dynamicImportFunction,
  10907. format: options.format,
  10908. freeze: options.freeze !== false,
  10909. indent: this.indentString,
  10910. namespaceToStringTag: options.namespaceToStringTag === true,
  10911. varOrConst: options.preferConst ? 'const' : 'var'
  10912. };
  10913. // Make sure the direct dependencies of a chunk are present to maintain execution order
  10914. for (const { module } of this.imports) {
  10915. const chunkOrExternal = (module instanceof Module ? module.chunk : module);
  10916. if (this.dependencies.indexOf(chunkOrExternal) === -1) {
  10917. this.dependencies.push(chunkOrExternal);
  10918. }
  10919. }
  10920. // for static and dynamic entry points, inline the execution list to avoid loading latency
  10921. if (options.hoistTransitiveImports !== false &&
  10922. !this.graph.preserveModules &&
  10923. this.facadeModule !== null) {
  10924. for (const dep of this.dependencies) {
  10925. if (dep instanceof Chunk$1)
  10926. this.inlineChunkDependencies(dep, true);
  10927. }
  10928. }
  10929. // prune empty dependency chunks, inlining their side-effect dependencies
  10930. for (let i = 0; i < this.dependencies.length; i++) {
  10931. const dep = this.dependencies[i];
  10932. if (dep instanceof Chunk$1 && dep.isEmpty) {
  10933. this.dependencies.splice(i--, 1);
  10934. this.inlineChunkDependencies(dep, false);
  10935. }
  10936. }
  10937. sortByExecutionOrder(this.dependencies);
  10938. this.prepareDynamicImports();
  10939. this.setIdentifierRenderResolutions(options);
  10940. let hoistedSource = '';
  10941. const renderedModules = (this.renderedModules = Object.create(null));
  10942. for (const module of this.orderedModules) {
  10943. let renderedLength = 0;
  10944. if (module.isIncluded()) {
  10945. const source = module.render(renderOptions).trim();
  10946. if (options.compact && source.lastLine().indexOf('//') !== -1)
  10947. source.append('\n');
  10948. const namespace = module.getOrCreateNamespace();
  10949. if (namespace.included || source.length() > 0) {
  10950. renderedLength = source.length();
  10951. this.renderedModuleSources.set(module, source);
  10952. magicString.addSource(source);
  10953. this.usedModules.push(module);
  10954. if (namespace.included && !this.graph.preserveModules) {
  10955. const rendered = namespace.renderBlock(renderOptions);
  10956. if (namespace.renderFirst())
  10957. hoistedSource += n + rendered;
  10958. else
  10959. magicString.addSource(new MagicString(rendered));
  10960. }
  10961. }
  10962. }
  10963. const { renderedExports, removedExports } = module.getRenderedExports();
  10964. renderedModules[module.id] = {
  10965. originalLength: module.originalCode.length,
  10966. removedExports,
  10967. renderedExports,
  10968. renderedLength
  10969. };
  10970. }
  10971. if (hoistedSource)
  10972. magicString.prepend(hoistedSource + n + n);
  10973. if (this.needsExportsShim) {
  10974. magicString.prepend(`${n}${renderOptions.varOrConst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
  10975. }
  10976. if (options.compact) {
  10977. this.renderedSource = magicString;
  10978. }
  10979. else {
  10980. this.renderedSource = magicString.trim();
  10981. }
  10982. this.renderedSourceLength = undefined;
  10983. this.renderedHash = undefined;
  10984. if (this.isEmpty && this.getExportNames().length === 0 && this.dependencies.length === 0) {
  10985. const chunkName = this.getChunkName();
  10986. this.graph.warn({
  10987. chunkName,
  10988. code: 'EMPTY_BUNDLE',
  10989. message: `Generated an empty chunk: "${chunkName}"`
  10990. });
  10991. }
  10992. this.setExternalRenderPaths(options, inputBase);
  10993. this.renderedDeclarations = {
  10994. dependencies: this.getChunkDependencyDeclarations(options),
  10995. exports: this.exportMode === 'none' ? [] : this.getChunkExportDeclarations()
  10996. };
  10997. timeEnd('render modules', 3);
  10998. }
  10999. render(options, addons, outputChunk, outputPluginDriver) {
  11000. timeStart('render format', 3);
  11001. const format = options.format;
  11002. const finalise = finalisers[format];
  11003. if (options.dynamicImportFunction && format !== 'es') {
  11004. this.graph.warn({
  11005. code: 'INVALID_OPTION',
  11006. message: '"output.dynamicImportFunction" is ignored for formats other than "esm".'
  11007. });
  11008. }
  11009. // populate ids in the rendered declarations only here
  11010. // as chunk ids known only after prerender
  11011. for (let i = 0; i < this.dependencies.length; i++) {
  11012. const dep = this.dependencies[i];
  11013. if (dep instanceof ExternalModule && !dep.renormalizeRenderPath)
  11014. continue;
  11015. const renderedDependency = this.renderedDeclarations.dependencies[i];
  11016. const depId = dep instanceof ExternalModule ? renderedDependency.id : dep.id;
  11017. if (dep instanceof Chunk$1)
  11018. renderedDependency.namedExportsMode = dep.exportMode !== 'default';
  11019. renderedDependency.id = this.getRelativePath(depId);
  11020. }
  11021. this.finaliseDynamicImports(format);
  11022. this.finaliseImportMetas(format, outputPluginDriver);
  11023. const hasExports = this.renderedDeclarations.exports.length !== 0 ||
  11024. this.renderedDeclarations.dependencies.some(dep => (dep.reexports && dep.reexports.length !== 0));
  11025. let usesTopLevelAwait = false;
  11026. const accessedGlobals = new Set();
  11027. for (const module of this.orderedModules) {
  11028. if (module.usesTopLevelAwait) {
  11029. usesTopLevelAwait = true;
  11030. }
  11031. const accessedGlobalVariablesByFormat = module.scope.accessedGlobalVariablesByFormat;
  11032. const accessedGlobalVariables = accessedGlobalVariablesByFormat && accessedGlobalVariablesByFormat.get(format);
  11033. if (accessedGlobalVariables) {
  11034. for (const name of accessedGlobalVariables) {
  11035. accessedGlobals.add(name);
  11036. }
  11037. }
  11038. }
  11039. if (usesTopLevelAwait && format !== 'es' && format !== 'system') {
  11040. return error({
  11041. code: 'INVALID_TLA_FORMAT',
  11042. message: `Module format ${format} does not support top-level await. Use the "es" or "system" output formats rather.`
  11043. });
  11044. }
  11045. const magicString = finalise(this.renderedSource, {
  11046. accessedGlobals,
  11047. dependencies: this.renderedDeclarations.dependencies,
  11048. exports: this.renderedDeclarations.exports,
  11049. hasExports,
  11050. indentString: this.indentString,
  11051. intro: addons.intro,
  11052. isEntryModuleFacade: this.graph.preserveModules ||
  11053. (this.facadeModule !== null && this.facadeModule.isEntryPoint),
  11054. namedExportsMode: this.exportMode !== 'default',
  11055. outro: addons.outro,
  11056. usesTopLevelAwait,
  11057. varOrConst: options.preferConst ? 'const' : 'var',
  11058. warn: this.graph.warn.bind(this.graph)
  11059. }, options);
  11060. if (addons.banner)
  11061. magicString.prepend(addons.banner);
  11062. if (addons.footer)
  11063. magicString.append(addons.footer);
  11064. const prevCode = magicString.toString();
  11065. timeEnd('render format', 3);
  11066. let map = null;
  11067. const chunkSourcemapChain = [];
  11068. return renderChunk({
  11069. chunk: this,
  11070. code: prevCode,
  11071. options,
  11072. outputPluginDriver,
  11073. renderChunk: outputChunk,
  11074. sourcemapChain: chunkSourcemapChain
  11075. }).then((code) => {
  11076. if (options.sourcemap) {
  11077. timeStart('sourcemap', 3);
  11078. let file;
  11079. if (options.file)
  11080. file = path.resolve(options.sourcemapFile || options.file);
  11081. else if (options.dir)
  11082. file = path.resolve(options.dir, this.id);
  11083. else
  11084. file = path.resolve(this.id);
  11085. const decodedMap = magicString.generateDecodedMap({});
  11086. map = collapseSourcemaps(this, file, decodedMap, this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources);
  11087. map.sources = map.sources.map(sourcePath => normalize(options.sourcemapPathTransform ? options.sourcemapPathTransform(sourcePath) : sourcePath));
  11088. timeEnd('sourcemap', 3);
  11089. }
  11090. if (options.compact !== true && code[code.length - 1] !== '\n')
  11091. code += '\n';
  11092. return { code, map };
  11093. });
  11094. }
  11095. visitDependencies(handleDependency) {
  11096. const toBeVisited = [this];
  11097. const visited = new Set();
  11098. for (const current of toBeVisited) {
  11099. handleDependency(current);
  11100. if (current instanceof ExternalModule)
  11101. continue;
  11102. for (const dependency of current.dependencies.concat(current.dynamicDependencies)) {
  11103. if (!visited.has(dependency)) {
  11104. visited.add(dependency);
  11105. toBeVisited.push(dependency);
  11106. }
  11107. }
  11108. }
  11109. }
  11110. visitStaticDependenciesUntilCondition(isConditionSatisfied) {
  11111. const seen = new Set();
  11112. function visitDep(dep) {
  11113. if (seen.has(dep))
  11114. return undefined;
  11115. seen.add(dep);
  11116. if (dep instanceof Chunk$1) {
  11117. for (const subDep of dep.dependencies) {
  11118. if (visitDep(subDep))
  11119. return true;
  11120. }
  11121. }
  11122. return isConditionSatisfied(dep) === true;
  11123. }
  11124. return visitDep(this);
  11125. }
  11126. addDependenciesToChunk(moduleDependencies, chunkDependencies) {
  11127. for (const depModule of moduleDependencies) {
  11128. if (depModule.chunk === this) {
  11129. continue;
  11130. }
  11131. let dependency;
  11132. if (depModule instanceof Module) {
  11133. dependency = depModule.chunk;
  11134. }
  11135. else {
  11136. if (!(depModule.used || depModule.moduleSideEffects)) {
  11137. continue;
  11138. }
  11139. dependency = depModule;
  11140. }
  11141. chunkDependencies.add(dependency);
  11142. }
  11143. }
  11144. assignFacadeName({ fileName, name }, facadedModule) {
  11145. if (fileName) {
  11146. this.fileName = fileName;
  11147. }
  11148. else {
  11149. this.name = sanitizeFileName(name || facadedModule.chunkName || getAliasName(facadedModule.id));
  11150. }
  11151. }
  11152. calculateHashAugmentation(outputPluginDriver) {
  11153. const facadeModule = this.facadeModule;
  11154. const getChunkName = this.getChunkName.bind(this);
  11155. const preRenderedChunk = {
  11156. dynamicImports: this.getDynamicImportIds(),
  11157. exports: this.getExportNames(),
  11158. facadeModuleId: facadeModule && facadeModule.id,
  11159. imports: this.getImportIds(),
  11160. isDynamicEntry: facadeModule !== null && facadeModule.dynamicallyImportedBy.length > 0,
  11161. isEntry: facadeModule !== null && facadeModule.isEntryPoint,
  11162. modules: this.renderedModules,
  11163. get name() {
  11164. return getChunkName();
  11165. }
  11166. };
  11167. return outputPluginDriver.hookReduceValueSync('augmentChunkHash', '', [preRenderedChunk], (hashAugmentation, pluginHash) => {
  11168. if (pluginHash) {
  11169. hashAugmentation += pluginHash;
  11170. }
  11171. return hashAugmentation;
  11172. });
  11173. }
  11174. computeContentHashWithDependencies(addons, options, existingNames, outputPluginDriver) {
  11175. const hash = createHash();
  11176. hash.update([addons.intro, addons.outro, addons.banner, addons.footer].map(addon => addon || '').join(':'));
  11177. hash.update(options.format);
  11178. this.visitDependencies(dep => {
  11179. if (dep instanceof ExternalModule) {
  11180. hash.update(':' + dep.renderPath);
  11181. }
  11182. else {
  11183. hash.update(dep.getRenderedHash(outputPluginDriver));
  11184. hash.update(dep.generateId(addons, options, existingNames, false, outputPluginDriver));
  11185. }
  11186. });
  11187. return hash.digest('hex').substr(0, 8);
  11188. }
  11189. finaliseDynamicImports(format) {
  11190. for (const [module, code] of this.renderedModuleSources) {
  11191. for (const { node, resolution } of module.dynamicImports) {
  11192. if (!resolution)
  11193. continue;
  11194. if (resolution instanceof Module) {
  11195. if (resolution.chunk !== this && isChunkRendered(resolution.chunk)) {
  11196. const resolutionChunk = resolution.facadeChunk || resolution.chunk;
  11197. node.renderFinalResolution(code, `'${this.getRelativePath(resolutionChunk.id)}'`, format);
  11198. }
  11199. }
  11200. else {
  11201. node.renderFinalResolution(code, resolution instanceof ExternalModule
  11202. ? `'${resolution.renormalizeRenderPath
  11203. ? this.getRelativePath(resolution.renderPath)
  11204. : resolution.id}'`
  11205. : resolution, format);
  11206. }
  11207. }
  11208. }
  11209. }
  11210. finaliseImportMetas(format, outputPluginDriver) {
  11211. for (const [module, code] of this.renderedModuleSources) {
  11212. for (const importMeta of module.importMetas) {
  11213. importMeta.renderFinalMechanism(code, this.id, format, outputPluginDriver);
  11214. }
  11215. }
  11216. }
  11217. getChunkDependencyDeclarations(options) {
  11218. const reexportDeclarations = new Map();
  11219. for (let exportName of this.getExportNames()) {
  11220. let exportChunk;
  11221. let importName;
  11222. let needsLiveBinding = false;
  11223. if (exportName[0] === '*') {
  11224. needsLiveBinding = options.externalLiveBindings !== false;
  11225. exportChunk = this.graph.moduleById.get(exportName.substr(1));
  11226. importName = exportName = '*';
  11227. }
  11228. else {
  11229. const variable = this.exportNames[exportName];
  11230. const module = variable.module;
  11231. // skip local exports
  11232. if (!module || module.chunk === this)
  11233. continue;
  11234. if (module instanceof Module) {
  11235. exportChunk = module.chunk;
  11236. importName = exportChunk.getVariableExportName(variable);
  11237. needsLiveBinding = variable.isReassigned;
  11238. }
  11239. else {
  11240. exportChunk = module;
  11241. importName = variable.name;
  11242. needsLiveBinding = options.externalLiveBindings !== false;
  11243. }
  11244. }
  11245. let reexportDeclaration = reexportDeclarations.get(exportChunk);
  11246. if (!reexportDeclaration)
  11247. reexportDeclarations.set(exportChunk, (reexportDeclaration = []));
  11248. reexportDeclaration.push({ imported: importName, reexported: exportName, needsLiveBinding });
  11249. }
  11250. const renderedImports = new Set();
  11251. const dependencies = [];
  11252. for (const dep of this.dependencies) {
  11253. const imports = [];
  11254. for (const variable of this.imports) {
  11255. const renderedVariable = variable instanceof ExportDefaultVariable ? variable.getOriginalVariable() : variable;
  11256. if ((variable.module instanceof Module
  11257. ? variable.module.chunk === dep
  11258. : variable.module === dep) &&
  11259. !renderedImports.has(renderedVariable)) {
  11260. renderedImports.add(renderedVariable);
  11261. imports.push({
  11262. imported: variable.module instanceof ExternalModule
  11263. ? variable.name
  11264. : variable.module.chunk.getVariableExportName(variable),
  11265. local: variable.getName()
  11266. });
  11267. }
  11268. }
  11269. const reexports = reexportDeclarations.get(dep);
  11270. let exportsNames, exportsDefault;
  11271. let namedExportsMode = true;
  11272. if (dep instanceof ExternalModule) {
  11273. exportsNames = dep.exportsNames || dep.exportsNamespace;
  11274. exportsDefault = 'default' in dep.declarations;
  11275. }
  11276. else {
  11277. exportsNames = true;
  11278. // we don't want any interop patterns to trigger
  11279. exportsDefault = false;
  11280. namedExportsMode = dep.exportMode !== 'default';
  11281. }
  11282. let id = undefined;
  11283. let globalName = undefined;
  11284. if (dep instanceof ExternalModule) {
  11285. id = dep.renderPath;
  11286. if (options.format === 'umd' || options.format === 'iife') {
  11287. globalName = getGlobalName(dep, options.globals, this.graph, exportsNames || exportsDefault);
  11288. }
  11289. }
  11290. dependencies.push({
  11291. exportsDefault,
  11292. exportsNames,
  11293. globalName,
  11294. id,
  11295. imports: imports.length > 0 ? imports : null,
  11296. isChunk: dep instanceof Chunk$1,
  11297. name: dep.variableName,
  11298. namedExportsMode,
  11299. reexports
  11300. });
  11301. }
  11302. return dependencies;
  11303. }
  11304. getChunkExportDeclarations() {
  11305. const exports = [];
  11306. for (const exportName of this.getExportNames()) {
  11307. if (exportName[0] === '*')
  11308. continue;
  11309. const variable = this.exportNames[exportName];
  11310. const module = variable.module;
  11311. if (module && module.chunk !== this)
  11312. continue;
  11313. let hoisted = false;
  11314. let uninitialized = false;
  11315. if (variable instanceof LocalVariable) {
  11316. if (variable.init === UNDEFINED_EXPRESSION) {
  11317. uninitialized = true;
  11318. }
  11319. for (const declaration of variable.declarations) {
  11320. if (declaration.parent instanceof FunctionDeclaration ||
  11321. (declaration instanceof ExportDefaultDeclaration &&
  11322. declaration.declaration instanceof FunctionDeclaration)) {
  11323. hoisted = true;
  11324. break;
  11325. }
  11326. }
  11327. }
  11328. else if (variable instanceof GlobalVariable) {
  11329. hoisted = true;
  11330. }
  11331. const localName = variable.getName();
  11332. exports.push({
  11333. exported: exportName === '*' ? localName : exportName,
  11334. hoisted,
  11335. local: localName,
  11336. uninitialized
  11337. });
  11338. }
  11339. return exports;
  11340. }
  11341. getFallbackChunkName() {
  11342. if (this.manualChunkAlias) {
  11343. return this.manualChunkAlias;
  11344. }
  11345. if (this.fileName) {
  11346. return getAliasName(this.fileName);
  11347. }
  11348. return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
  11349. }
  11350. getRelativePath(targetPath) {
  11351. const relativePath = normalize(relative(path.dirname(this.id), targetPath));
  11352. return relativePath.startsWith('../') ? relativePath : './' + relativePath;
  11353. }
  11354. inlineChunkDependencies(chunk, deep) {
  11355. for (const dep of chunk.dependencies) {
  11356. if (dep instanceof ExternalModule) {
  11357. if (this.dependencies.indexOf(dep) === -1)
  11358. this.dependencies.push(dep);
  11359. }
  11360. else {
  11361. if (dep === this || this.dependencies.indexOf(dep) !== -1)
  11362. continue;
  11363. if (!dep.isEmpty)
  11364. this.dependencies.push(dep);
  11365. if (deep)
  11366. this.inlineChunkDependencies(dep, true);
  11367. }
  11368. }
  11369. }
  11370. prepareDynamicImports() {
  11371. for (const module of this.orderedModules) {
  11372. for (const { node, resolution } of module.dynamicImports) {
  11373. if (!node.included)
  11374. continue;
  11375. if (resolution instanceof Module) {
  11376. if (resolution.chunk === this) {
  11377. const namespace = resolution.getOrCreateNamespace();
  11378. node.setResolution('named', namespace);
  11379. }
  11380. else {
  11381. node.setResolution(resolution.chunk.exportMode);
  11382. }
  11383. }
  11384. else {
  11385. node.setResolution('auto');
  11386. }
  11387. }
  11388. }
  11389. }
  11390. setExternalRenderPaths(options, inputBase) {
  11391. for (const dependency of this.dependencies.concat(this.dynamicDependencies)) {
  11392. if (dependency instanceof ExternalModule) {
  11393. dependency.setRenderPath(options, inputBase);
  11394. }
  11395. }
  11396. }
  11397. setIdentifierRenderResolutions(options) {
  11398. for (const exportName of this.getExportNames()) {
  11399. const exportVariable = this.exportNames[exportName];
  11400. if (exportVariable) {
  11401. if (exportVariable instanceof ExportShimVariable) {
  11402. this.needsExportsShim = true;
  11403. }
  11404. exportVariable.exportName = exportName;
  11405. if (options.format !== 'es' &&
  11406. options.format !== 'system' &&
  11407. exportVariable.isReassigned &&
  11408. !exportVariable.isId &&
  11409. !(exportVariable instanceof ExportDefaultVariable && exportVariable.hasId)) {
  11410. exportVariable.setRenderNames('exports', exportName);
  11411. }
  11412. else {
  11413. exportVariable.setRenderNames(null, null);
  11414. }
  11415. }
  11416. }
  11417. const usedNames = new Set();
  11418. if (this.needsExportsShim) {
  11419. usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
  11420. }
  11421. if (options.format !== 'es') {
  11422. usedNames.add('exports');
  11423. if (options.format === 'cjs') {
  11424. usedNames
  11425. .add(INTEROP_DEFAULT_VARIABLE)
  11426. .add('require')
  11427. .add('module')
  11428. .add('__filename')
  11429. .add('__dirname');
  11430. }
  11431. }
  11432. deconflictChunk(this.orderedModules, this.dependencies, this.imports, usedNames, options.format, options.interop !== false, this.graph.preserveModules);
  11433. }
  11434. setUpChunkImportsAndExportsForModule(module) {
  11435. for (const variable of module.imports) {
  11436. if (variable.module.chunk !== this) {
  11437. this.imports.add(variable);
  11438. if (variable.module instanceof Module) {
  11439. variable.module.chunk.exports.add(variable);
  11440. }
  11441. }
  11442. }
  11443. if (module.isEntryPoint ||
  11444. module.dynamicallyImportedBy.some(importer => importer.chunk !== this)) {
  11445. const map = module.getExportNamesByVariable();
  11446. for (const exportedVariable of map.keys()) {
  11447. this.exports.add(exportedVariable);
  11448. const exportingModule = exportedVariable.module;
  11449. if (exportingModule && exportingModule.chunk && exportingModule.chunk !== this) {
  11450. exportingModule.chunk.exports.add(exportedVariable);
  11451. }
  11452. }
  11453. }
  11454. if (module.getOrCreateNamespace().included) {
  11455. for (const reexportName of Object.keys(module.reexportDescriptions)) {
  11456. const reexport = module.reexportDescriptions[reexportName];
  11457. const variable = reexport.module.getVariableForExportName(reexport.localName);
  11458. if (variable.module.chunk !== this) {
  11459. this.imports.add(variable);
  11460. if (variable.module instanceof Module) {
  11461. variable.module.chunk.exports.add(variable);
  11462. }
  11463. }
  11464. }
  11465. }
  11466. const context = createInclusionContext();
  11467. for (const { node, resolution } of module.dynamicImports) {
  11468. if (node.included && resolution instanceof Module && resolution.chunk === this)
  11469. resolution.getOrCreateNamespace().include(context);
  11470. }
  11471. }
  11472. }
  11473. /*
  11474. * Given a chunk list, perform optimizations on that chunk list
  11475. * to reduce the mumber of chunks. Mutates the chunks array.
  11476. *
  11477. * Manual chunks (with chunk.chunkAlias already set) are preserved
  11478. * Entry points are carefully preserved as well
  11479. *
  11480. */
  11481. function optimizeChunks(chunks, options, CHUNK_GROUPING_SIZE, inputBase) {
  11482. for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {
  11483. const mainChunk = chunks[chunkIndex];
  11484. const execGroup = [];
  11485. mainChunk.visitStaticDependenciesUntilCondition(dep => {
  11486. if (dep instanceof Chunk$1) {
  11487. execGroup.push(dep);
  11488. }
  11489. });
  11490. if (execGroup.length < 2) {
  11491. continue;
  11492. }
  11493. let execGroupIndex = 1;
  11494. let seekingFirstMergeCandidate = true;
  11495. let lastChunk = undefined, chunk = execGroup[0], nextChunk = execGroup[1];
  11496. const isMergeCandidate = (chunk) => {
  11497. if (chunk.facadeModule !== null || chunk.manualChunkAlias !== null) {
  11498. return false;
  11499. }
  11500. if (!nextChunk || nextChunk.facadeModule !== null) {
  11501. return false;
  11502. }
  11503. if (chunk.getRenderedSourceLength() > CHUNK_GROUPING_SIZE) {
  11504. return false;
  11505. }
  11506. // if (!chunk.isPure()) continue;
  11507. return true;
  11508. };
  11509. do {
  11510. if (seekingFirstMergeCandidate) {
  11511. if (isMergeCandidate(chunk)) {
  11512. seekingFirstMergeCandidate = false;
  11513. }
  11514. continue;
  11515. }
  11516. let remainingSize = CHUNK_GROUPING_SIZE - lastChunk.getRenderedSourceLength() - chunk.getRenderedSourceLength();
  11517. if (remainingSize <= 0) {
  11518. if (!isMergeCandidate(chunk)) {
  11519. seekingFirstMergeCandidate = true;
  11520. }
  11521. continue;
  11522. }
  11523. // if (!chunk.isPure()) continue;
  11524. const chunkDependencies = new Set();
  11525. chunk.visitStaticDependenciesUntilCondition(dep => chunkDependencies.add(dep));
  11526. const ignoreSizeChunks = new Set([chunk, lastChunk]);
  11527. if (lastChunk.visitStaticDependenciesUntilCondition(dep => {
  11528. if (dep === chunk || dep === lastChunk) {
  11529. return false;
  11530. }
  11531. if (chunkDependencies.has(dep)) {
  11532. return false;
  11533. }
  11534. if (dep instanceof ExternalModule) {
  11535. return true;
  11536. }
  11537. remainingSize -= dep.getRenderedSourceLength();
  11538. if (remainingSize <= 0) {
  11539. return true;
  11540. }
  11541. ignoreSizeChunks.add(dep);
  11542. })) {
  11543. if (!isMergeCandidate(chunk)) {
  11544. seekingFirstMergeCandidate = true;
  11545. }
  11546. continue;
  11547. }
  11548. if (chunk.visitStaticDependenciesUntilCondition(dep => {
  11549. if (ignoreSizeChunks.has(dep)) {
  11550. return false;
  11551. }
  11552. if (dep instanceof ExternalModule) {
  11553. return true;
  11554. }
  11555. remainingSize -= dep.getRenderedSourceLength();
  11556. if (remainingSize <= 0) {
  11557. return true;
  11558. }
  11559. })) {
  11560. if (!isMergeCandidate(chunk)) {
  11561. seekingFirstMergeCandidate = true;
  11562. }
  11563. continue;
  11564. }
  11565. // within the size limit -> merge!
  11566. const optimizedChunkIndex = chunks.indexOf(chunk);
  11567. if (optimizedChunkIndex <= chunkIndex)
  11568. chunkIndex--;
  11569. chunks.splice(optimizedChunkIndex, 1);
  11570. lastChunk.merge(chunk, chunks, options, inputBase);
  11571. execGroup.splice(--execGroupIndex, 1);
  11572. chunk = lastChunk;
  11573. // keep going to see if we can merge this with the next again
  11574. if (nextChunk && !isMergeCandidate(nextChunk)) {
  11575. seekingFirstMergeCandidate = true;
  11576. }
  11577. } while (((lastChunk = chunk), (chunk = nextChunk), (nextChunk = execGroup[++execGroupIndex]), chunk));
  11578. }
  11579. return chunks;
  11580. }
  11581. const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  11582. const tt = acorn.tokTypes;
  11583. var acornExportNsFrom = function (Parser) {
  11584. return class extends Parser {
  11585. parseExport(node, exports) {
  11586. skipWhiteSpace.lastIndex = this.pos;
  11587. const skip = skipWhiteSpace.exec(this.input);
  11588. const next = this.input.charAt(this.pos + skip[0].length);
  11589. if (next !== "*")
  11590. return super.parseExport(node, exports);
  11591. this.next();
  11592. const specifier = this.startNode();
  11593. this.expect(tt.star);
  11594. if (this.eatContextual("as")) {
  11595. node.declaration = null;
  11596. specifier.exported = this.parseIdent(true);
  11597. this.checkExport(exports, specifier.exported.name, this.lastTokStart);
  11598. node.specifiers = [this.finishNode(specifier, "ExportNamespaceSpecifier")];
  11599. }
  11600. this.expectContextual("from");
  11601. if (this.type !== tt.string)
  11602. this.unexpected();
  11603. node.source = this.parseExprAtom();
  11604. this.semicolon();
  11605. return this.finishNode(node, node.specifiers ? "ExportNamedDeclaration" : "ExportAllDeclaration");
  11606. }
  11607. };
  11608. };
  11609. const tt$1 = acorn.tokTypes;
  11610. const skipWhiteSpace$1 = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  11611. const nextTokenIsDot = parser => {
  11612. skipWhiteSpace$1.lastIndex = parser.pos;
  11613. let skip = skipWhiteSpace$1.exec(parser.input);
  11614. let next = parser.pos + skip[0].length;
  11615. return parser.input.slice(next, next + 1) === ".";
  11616. };
  11617. var acornImportMeta = function (Parser) {
  11618. return class extends Parser {
  11619. parseExprAtom(refDestructuringErrors) {
  11620. if (this.type !== tt$1._import || !nextTokenIsDot(this))
  11621. return super.parseExprAtom(refDestructuringErrors);
  11622. if (!this.options.allowImportExportEverywhere && !this.inModule) {
  11623. this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'");
  11624. }
  11625. let node = this.startNode();
  11626. node.meta = this.parseIdent(true);
  11627. this.expect(tt$1.dot);
  11628. node.property = this.parseIdent(true);
  11629. if (node.property.name !== "meta") {
  11630. this.raiseRecoverable(node.property.start, "The only valid meta property for import is import.meta");
  11631. }
  11632. if (this.containsEsc) {
  11633. this.raiseRecoverable(node.property.start, "\"meta\" in import.meta must not contain escape sequences");
  11634. }
  11635. return this.finishNode(node, "MetaProperty");
  11636. }
  11637. parseStatement(context, topLevel, exports) {
  11638. if (this.type !== tt$1._import || !nextTokenIsDot(this)) {
  11639. return super.parseStatement(context, topLevel, exports);
  11640. }
  11641. let node = this.startNode();
  11642. let expr = this.parseExpression();
  11643. return this.parseExpressionStatement(node, expr);
  11644. }
  11645. };
  11646. };
  11647. class UndefinedVariable extends Variable {
  11648. constructor() {
  11649. super('undefined');
  11650. }
  11651. getLiteralValueAtPath() {
  11652. return undefined;
  11653. }
  11654. }
  11655. class GlobalScope extends Scope {
  11656. constructor() {
  11657. super();
  11658. this.variables.set('undefined', new UndefinedVariable());
  11659. }
  11660. findVariable(name) {
  11661. let variable = this.variables.get(name);
  11662. if (!variable) {
  11663. variable = new GlobalVariable(name);
  11664. this.variables.set(name, variable);
  11665. }
  11666. return variable;
  11667. }
  11668. }
  11669. const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
  11670. const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
  11671. function throwPluginError(err, plugin, { hook, id } = {}) {
  11672. if (typeof err === 'string')
  11673. err = { message: err };
  11674. if (err.code && err.code !== Errors.PLUGIN_ERROR) {
  11675. err.pluginCode = err.code;
  11676. }
  11677. err.code = Errors.PLUGIN_ERROR;
  11678. err.plugin = plugin;
  11679. if (hook) {
  11680. err.hook = hook;
  11681. }
  11682. if (id) {
  11683. err.id = id;
  11684. }
  11685. return error(err);
  11686. }
  11687. const deprecatedHooks = [
  11688. { active: true, deprecated: 'ongenerate', replacement: 'generateBundle' },
  11689. { active: true, deprecated: 'onwrite', replacement: 'generateBundle/writeBundle' },
  11690. { active: true, deprecated: 'transformBundle', replacement: 'renderChunk' },
  11691. { active: true, deprecated: 'transformChunk', replacement: 'renderChunk' },
  11692. { active: false, deprecated: 'resolveAssetUrl', replacement: 'resolveFileUrl' }
  11693. ];
  11694. function warnDeprecatedHooks(plugins, graph) {
  11695. for (const { active, deprecated, replacement } of deprecatedHooks) {
  11696. for (const plugin of plugins) {
  11697. if (deprecated in plugin) {
  11698. graph.warnDeprecation({
  11699. message: `The "${deprecated}" hook used by plugin ${plugin.name} is deprecated. The "${replacement}" hook should be used instead.`,
  11700. plugin: plugin.name
  11701. }, active);
  11702. }
  11703. }
  11704. }
  11705. }
  11706. function createPluginCache(cache) {
  11707. return {
  11708. has(id) {
  11709. const item = cache[id];
  11710. if (!item)
  11711. return false;
  11712. item[0] = 0;
  11713. return true;
  11714. },
  11715. get(id) {
  11716. const item = cache[id];
  11717. if (!item)
  11718. return undefined;
  11719. item[0] = 0;
  11720. return item[1];
  11721. },
  11722. set(id, value) {
  11723. cache[id] = [0, value];
  11724. },
  11725. delete(id) {
  11726. return delete cache[id];
  11727. }
  11728. };
  11729. }
  11730. function getTrackedPluginCache(pluginCache) {
  11731. const trackedCache = {
  11732. cache: {
  11733. has(id) {
  11734. trackedCache.used = true;
  11735. return pluginCache.has(id);
  11736. },
  11737. get(id) {
  11738. trackedCache.used = true;
  11739. return pluginCache.get(id);
  11740. },
  11741. set(id, value) {
  11742. trackedCache.used = true;
  11743. return pluginCache.set(id, value);
  11744. },
  11745. delete(id) {
  11746. trackedCache.used = true;
  11747. return pluginCache.delete(id);
  11748. }
  11749. },
  11750. used: false
  11751. };
  11752. return trackedCache;
  11753. }
  11754. const NO_CACHE = {
  11755. has() {
  11756. return false;
  11757. },
  11758. get() {
  11759. return undefined;
  11760. },
  11761. set() { },
  11762. delete() {
  11763. return false;
  11764. }
  11765. };
  11766. function uncacheablePluginError(pluginName) {
  11767. if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  11768. pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
  11769. return error({
  11770. code: 'ANONYMOUS_PLUGIN_CACHE',
  11771. message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
  11772. });
  11773. }
  11774. return error({
  11775. code: 'DUPLICATE_PLUGIN_NAME',
  11776. 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).`
  11777. });
  11778. }
  11779. function getCacheForUncacheablePlugin(pluginName) {
  11780. return {
  11781. has() {
  11782. return uncacheablePluginError(pluginName);
  11783. },
  11784. get() {
  11785. return uncacheablePluginError(pluginName);
  11786. },
  11787. set() {
  11788. return uncacheablePluginError(pluginName);
  11789. },
  11790. delete() {
  11791. return uncacheablePluginError(pluginName);
  11792. }
  11793. };
  11794. }
  11795. function transform(graph, source, module) {
  11796. const id = module.id;
  11797. const sourcemapChain = [];
  11798. let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
  11799. const originalCode = source.code;
  11800. let ast = source.ast;
  11801. const transformDependencies = [];
  11802. const emittedFiles = [];
  11803. let customTransformCache = false;
  11804. let moduleSideEffects = null;
  11805. let syntheticNamedExports = null;
  11806. let trackedPluginCache;
  11807. let curPlugin;
  11808. const curSource = source.code;
  11809. function transformReducer(code, result, plugin) {
  11810. // track which plugins use the custom this.cache to opt-out of transform caching
  11811. if (!customTransformCache && trackedPluginCache.used)
  11812. customTransformCache = true;
  11813. if (customTransformCache) {
  11814. if (result && typeof result === 'object' && Array.isArray(result.dependencies)) {
  11815. for (const dep of result.dependencies) {
  11816. graph.watchFiles[path.resolve(path.dirname(id), dep)] = true;
  11817. }
  11818. }
  11819. }
  11820. else {
  11821. // files emitted by a transform hook need to be emitted again if the hook is skipped
  11822. if (emittedFiles.length)
  11823. module.transformFiles = emittedFiles;
  11824. if (result && typeof result === 'object' && Array.isArray(result.dependencies)) {
  11825. // not great, but a useful way to track this without assuming WeakMap
  11826. if (!curPlugin.warnedTransformDependencies)
  11827. graph.warnDeprecation(`Returning "dependencies" from the "transform" hook as done by plugin ${plugin.name} is deprecated. The "this.addWatchFile" plugin context function should be used instead.`, true);
  11828. curPlugin.warnedTransformDependencies = true;
  11829. for (const dep of result.dependencies)
  11830. transformDependencies.push(path.resolve(path.dirname(id), dep));
  11831. }
  11832. }
  11833. if (typeof result === 'string') {
  11834. result = {
  11835. ast: undefined,
  11836. code: result,
  11837. map: undefined
  11838. };
  11839. }
  11840. else if (result && typeof result === 'object') {
  11841. if (typeof result.map === 'string') {
  11842. result.map = JSON.parse(result.map);
  11843. }
  11844. if (typeof result.moduleSideEffects === 'boolean') {
  11845. moduleSideEffects = result.moduleSideEffects;
  11846. }
  11847. if (typeof result.syntheticNamedExports === 'boolean') {
  11848. syntheticNamedExports = result.syntheticNamedExports;
  11849. }
  11850. }
  11851. else {
  11852. return code;
  11853. }
  11854. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  11855. if (result.map !== null) {
  11856. const map = decodedSourcemap(result.map);
  11857. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  11858. }
  11859. ast = result.ast;
  11860. return result.code;
  11861. }
  11862. let setAssetSourceErr;
  11863. return graph.pluginDriver
  11864. .hookReduceArg0('transform', [curSource, id], transformReducer, (pluginContext, plugin) => {
  11865. curPlugin = plugin;
  11866. if (curPlugin.cacheKey)
  11867. customTransformCache = true;
  11868. else
  11869. trackedPluginCache = getTrackedPluginCache(pluginContext.cache);
  11870. return Object.assign(Object.assign({}, pluginContext), { cache: trackedPluginCache ? trackedPluginCache.cache : pluginContext.cache, warn(warning, pos) {
  11871. if (typeof warning === 'string')
  11872. warning = { message: warning };
  11873. if (pos)
  11874. augmentCodeLocation(warning, pos, curSource, id);
  11875. warning.id = id;
  11876. warning.hook = 'transform';
  11877. pluginContext.warn(warning);
  11878. },
  11879. error(err, pos) {
  11880. if (typeof err === 'string')
  11881. err = { message: err };
  11882. if (pos)
  11883. augmentCodeLocation(err, pos, curSource, id);
  11884. err.id = id;
  11885. err.hook = 'transform';
  11886. return pluginContext.error(err);
  11887. },
  11888. emitAsset(name, source) {
  11889. const emittedFile = { type: 'asset', name, source };
  11890. emittedFiles.push(Object.assign({}, emittedFile));
  11891. return graph.pluginDriver.emitFile(emittedFile);
  11892. },
  11893. emitChunk(id, options) {
  11894. const emittedFile = { type: 'chunk', id, name: options && options.name };
  11895. emittedFiles.push(Object.assign({}, emittedFile));
  11896. return graph.pluginDriver.emitFile(emittedFile);
  11897. },
  11898. emitFile(emittedFile) {
  11899. emittedFiles.push(emittedFile);
  11900. return graph.pluginDriver.emitFile(emittedFile);
  11901. },
  11902. addWatchFile(id) {
  11903. transformDependencies.push(id);
  11904. pluginContext.addWatchFile(id);
  11905. },
  11906. setAssetSource(assetReferenceId, source) {
  11907. pluginContext.setAssetSource(assetReferenceId, source);
  11908. if (!customTransformCache && !setAssetSourceErr) {
  11909. try {
  11910. return this.error({
  11911. code: 'INVALID_SETASSETSOURCE',
  11912. message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
  11913. });
  11914. }
  11915. catch (err) {
  11916. setAssetSourceErr = err;
  11917. }
  11918. }
  11919. },
  11920. getCombinedSourcemap() {
  11921. const combinedMap = collapseSourcemap(graph, id, originalCode, originalSourcemap, sourcemapChain);
  11922. if (!combinedMap) {
  11923. const magicString = new MagicString(originalCode);
  11924. return magicString.generateMap({ includeContent: true, hires: true, source: id });
  11925. }
  11926. if (originalSourcemap !== combinedMap) {
  11927. originalSourcemap = combinedMap;
  11928. sourcemapChain.length = 0;
  11929. }
  11930. return new SourceMap(Object.assign(Object.assign({}, combinedMap), { file: null, sourcesContent: combinedMap.sourcesContent }));
  11931. } });
  11932. })
  11933. .catch(err => throwPluginError(err, curPlugin.name, { hook: 'transform', id }))
  11934. .then(code => {
  11935. if (!customTransformCache && setAssetSourceErr)
  11936. throw setAssetSourceErr;
  11937. return {
  11938. ast: ast,
  11939. code,
  11940. customTransformCache,
  11941. moduleSideEffects,
  11942. originalCode,
  11943. originalSourcemap,
  11944. sourcemapChain,
  11945. syntheticNamedExports,
  11946. transformDependencies
  11947. };
  11948. });
  11949. }
  11950. function normalizeRelativeExternalId(importer, source) {
  11951. return isRelative(source) ? path.resolve(importer, '..', source) : source;
  11952. }
  11953. function getIdMatcher(option) {
  11954. if (option === true) {
  11955. return () => true;
  11956. }
  11957. if (typeof option === 'function') {
  11958. return (id, ...args) => (!id.startsWith('\0') && option(id, ...args)) || false;
  11959. }
  11960. if (option) {
  11961. const ids = new Set(Array.isArray(option) ? option : option ? [option] : []);
  11962. return (id => ids.has(id));
  11963. }
  11964. return () => false;
  11965. }
  11966. function getHasModuleSideEffects(moduleSideEffectsOption, pureExternalModules, graph) {
  11967. if (typeof moduleSideEffectsOption === 'boolean') {
  11968. return () => moduleSideEffectsOption;
  11969. }
  11970. if (moduleSideEffectsOption === 'no-external') {
  11971. return (_id, external) => !external;
  11972. }
  11973. if (typeof moduleSideEffectsOption === 'function') {
  11974. return (id, external) => !id.startsWith('\0') ? moduleSideEffectsOption(id, external) !== false : true;
  11975. }
  11976. if (Array.isArray(moduleSideEffectsOption)) {
  11977. const ids = new Set(moduleSideEffectsOption);
  11978. return id => ids.has(id);
  11979. }
  11980. if (moduleSideEffectsOption) {
  11981. graph.warn(errInvalidOption('treeshake.moduleSideEffects', 'please use one of false, "no-external", a function or an array'));
  11982. }
  11983. const isPureExternalModule = getIdMatcher(pureExternalModules);
  11984. return (id, external) => !(external && isPureExternalModule(id));
  11985. }
  11986. class ModuleLoader {
  11987. constructor(graph, modulesById, pluginDriver, external, getManualChunk, moduleSideEffects, pureExternalModules) {
  11988. this.indexedEntryModules = [];
  11989. this.latestLoadModulesPromise = Promise.resolve();
  11990. this.manualChunkModules = {};
  11991. this.nextEntryModuleIndex = 0;
  11992. this.loadEntryModule = (unresolvedId, isEntry) => this.pluginDriver.hookFirst('resolveId', [unresolvedId, undefined]).then(resolveIdResult => {
  11993. if (resolveIdResult === false ||
  11994. (resolveIdResult && typeof resolveIdResult === 'object' && resolveIdResult.external)) {
  11995. return error(errEntryCannotBeExternal(unresolvedId));
  11996. }
  11997. const id = resolveIdResult && typeof resolveIdResult === 'object'
  11998. ? resolveIdResult.id
  11999. : resolveIdResult;
  12000. if (typeof id === 'string') {
  12001. return this.fetchModule(id, undefined, true, false, isEntry);
  12002. }
  12003. return error(errUnresolvedEntry(unresolvedId));
  12004. });
  12005. this.graph = graph;
  12006. this.modulesById = modulesById;
  12007. this.pluginDriver = pluginDriver;
  12008. this.isExternal = getIdMatcher(external);
  12009. this.hasModuleSideEffects = getHasModuleSideEffects(moduleSideEffects, pureExternalModules, graph);
  12010. this.getManualChunk = typeof getManualChunk === 'function' ? getManualChunk : () => null;
  12011. }
  12012. addEntryModules(unresolvedEntryModules, isUserDefined) {
  12013. const firstEntryModuleIndex = this.nextEntryModuleIndex;
  12014. this.nextEntryModuleIndex += unresolvedEntryModules.length;
  12015. const loadNewEntryModulesPromise = Promise.all(unresolvedEntryModules.map(({ fileName, id, name }) => this.loadEntryModule(id, true).then(module => {
  12016. if (fileName !== null) {
  12017. module.chunkFileNames.add(fileName);
  12018. }
  12019. else if (name !== null) {
  12020. if (module.chunkName === null) {
  12021. module.chunkName = name;
  12022. }
  12023. if (isUserDefined) {
  12024. module.userChunkNames.add(name);
  12025. }
  12026. }
  12027. return module;
  12028. }))).then(entryModules => {
  12029. let moduleIndex = firstEntryModuleIndex;
  12030. for (const entryModule of entryModules) {
  12031. entryModule.isUserDefinedEntryPoint = entryModule.isUserDefinedEntryPoint || isUserDefined;
  12032. const existingIndexModule = this.indexedEntryModules.find(indexedModule => indexedModule.module.id === entryModule.id);
  12033. if (!existingIndexModule) {
  12034. this.indexedEntryModules.push({ module: entryModule, index: moduleIndex });
  12035. }
  12036. else {
  12037. existingIndexModule.index = Math.min(existingIndexModule.index, moduleIndex);
  12038. }
  12039. moduleIndex++;
  12040. }
  12041. this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
  12042. return entryModules;
  12043. });
  12044. return this.awaitLoadModulesPromise(loadNewEntryModulesPromise).then(newEntryModules => ({
  12045. entryModules: this.indexedEntryModules.map(({ module }) => module),
  12046. manualChunkModulesByAlias: this.manualChunkModules,
  12047. newEntryModules
  12048. }));
  12049. }
  12050. addManualChunks(manualChunks) {
  12051. const unresolvedManualChunks = [];
  12052. for (const alias of Object.keys(manualChunks)) {
  12053. const manualChunkIds = manualChunks[alias];
  12054. for (const id of manualChunkIds) {
  12055. unresolvedManualChunks.push({ id, alias });
  12056. }
  12057. }
  12058. const loadNewManualChunkModulesPromise = Promise.all(unresolvedManualChunks.map(({ id }) => this.loadEntryModule(id, false))).then(manualChunkModules => {
  12059. for (let index = 0; index < manualChunkModules.length; index++) {
  12060. this.addModuleToManualChunk(unresolvedManualChunks[index].alias, manualChunkModules[index]);
  12061. }
  12062. });
  12063. return this.awaitLoadModulesPromise(loadNewManualChunkModulesPromise);
  12064. }
  12065. resolveId(source, importer, skip) {
  12066. return __awaiter(this, void 0, void 0, function* () {
  12067. return this.normalizeResolveIdResult(this.isExternal(source, importer, false)
  12068. ? false
  12069. : yield this.pluginDriver.hookFirst('resolveId', [source, importer], null, skip), importer, source);
  12070. });
  12071. }
  12072. addModuleToManualChunk(alias, module) {
  12073. if (module.manualChunkAlias !== null && module.manualChunkAlias !== alias) {
  12074. return error(errCannotAssignModuleToChunk(module.id, alias, module.manualChunkAlias));
  12075. }
  12076. module.manualChunkAlias = alias;
  12077. if (!this.manualChunkModules[alias]) {
  12078. this.manualChunkModules[alias] = [];
  12079. }
  12080. this.manualChunkModules[alias].push(module);
  12081. }
  12082. awaitLoadModulesPromise(loadNewModulesPromise) {
  12083. this.latestLoadModulesPromise = Promise.all([
  12084. loadNewModulesPromise,
  12085. this.latestLoadModulesPromise
  12086. ]);
  12087. const getCombinedPromise = () => {
  12088. const startingPromise = this.latestLoadModulesPromise;
  12089. return startingPromise.then(() => {
  12090. if (this.latestLoadModulesPromise !== startingPromise) {
  12091. return getCombinedPromise();
  12092. }
  12093. });
  12094. };
  12095. return getCombinedPromise().then(() => loadNewModulesPromise);
  12096. }
  12097. fetchAllDependencies(module) {
  12098. return Promise.all([
  12099. ...Array.from(module.sources).map((source) => __awaiter(this, void 0, void 0, function* () {
  12100. return this.fetchResolvedDependency(source, module.id, (module.resolvedIds[source] =
  12101. module.resolvedIds[source] ||
  12102. this.handleResolveId(yield this.resolveId(source, module.id), source, module.id)));
  12103. })),
  12104. ...module.getDynamicImportExpressions().map((specifier, index) => this.resolveDynamicImport(module, specifier, module.id).then(resolvedId => {
  12105. if (resolvedId === null)
  12106. return;
  12107. const dynamicImport = module.dynamicImports[index];
  12108. if (typeof resolvedId === 'string') {
  12109. dynamicImport.resolution = resolvedId;
  12110. return;
  12111. }
  12112. return this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId).then(module => {
  12113. dynamicImport.resolution = module;
  12114. });
  12115. }))
  12116. ]);
  12117. }
  12118. fetchModule(id, importer, moduleSideEffects, syntheticNamedExports, isEntry) {
  12119. const existingModule = this.modulesById.get(id);
  12120. if (existingModule instanceof Module) {
  12121. existingModule.isEntryPoint = existingModule.isEntryPoint || isEntry;
  12122. return Promise.resolve(existingModule);
  12123. }
  12124. const module = new Module(this.graph, id, moduleSideEffects, syntheticNamedExports, isEntry);
  12125. this.modulesById.set(id, module);
  12126. this.graph.watchFiles[id] = true;
  12127. const manualChunkAlias = this.getManualChunk(id);
  12128. if (typeof manualChunkAlias === 'string') {
  12129. this.addModuleToManualChunk(manualChunkAlias, module);
  12130. }
  12131. timeStart('load modules', 3);
  12132. return Promise.resolve(this.pluginDriver.hookFirst('load', [id]))
  12133. .catch((err) => {
  12134. timeEnd('load modules', 3);
  12135. let msg = `Could not load ${id}`;
  12136. if (importer)
  12137. msg += ` (imported by ${importer})`;
  12138. msg += `: ${err.message}`;
  12139. err.message = msg;
  12140. throw err;
  12141. })
  12142. .then(source => {
  12143. timeEnd('load modules', 3);
  12144. if (typeof source === 'string')
  12145. return { code: source };
  12146. if (source && typeof source === 'object' && typeof source.code === 'string')
  12147. return source;
  12148. return error(errBadLoader(id));
  12149. })
  12150. .then(sourceDescription => {
  12151. const cachedModule = this.graph.cachedModules.get(id);
  12152. if (cachedModule &&
  12153. !cachedModule.customTransformCache &&
  12154. cachedModule.originalCode === sourceDescription.code) {
  12155. if (cachedModule.transformFiles) {
  12156. for (const emittedFile of cachedModule.transformFiles)
  12157. this.pluginDriver.emitFile(emittedFile);
  12158. }
  12159. return cachedModule;
  12160. }
  12161. if (typeof sourceDescription.moduleSideEffects === 'boolean') {
  12162. module.moduleSideEffects = sourceDescription.moduleSideEffects;
  12163. }
  12164. if (typeof sourceDescription.syntheticNamedExports === 'boolean') {
  12165. module.syntheticNamedExports = sourceDescription.syntheticNamedExports;
  12166. }
  12167. return transform(this.graph, sourceDescription, module);
  12168. })
  12169. .then((source) => {
  12170. module.setSource(source);
  12171. this.modulesById.set(id, module);
  12172. return this.fetchAllDependencies(module).then(() => {
  12173. for (const name in module.exports) {
  12174. if (name !== 'default') {
  12175. module.exportsAll[name] = module.id;
  12176. }
  12177. }
  12178. for (const source of module.exportAllSources) {
  12179. const id = module.resolvedIds[source].id;
  12180. const exportAllModule = this.modulesById.get(id);
  12181. if (exportAllModule instanceof ExternalModule)
  12182. continue;
  12183. for (const name in exportAllModule.exportsAll) {
  12184. if (name in module.exportsAll) {
  12185. this.graph.warn(errNamespaceConflict(name, module, exportAllModule));
  12186. }
  12187. else {
  12188. module.exportsAll[name] = exportAllModule.exportsAll[name];
  12189. }
  12190. }
  12191. }
  12192. return module;
  12193. });
  12194. });
  12195. }
  12196. fetchResolvedDependency(source, importer, resolvedId) {
  12197. if (resolvedId.external) {
  12198. if (!this.modulesById.has(resolvedId.id)) {
  12199. this.modulesById.set(resolvedId.id, new ExternalModule(this.graph, resolvedId.id, resolvedId.moduleSideEffects));
  12200. }
  12201. const externalModule = this.modulesById.get(resolvedId.id);
  12202. if (!(externalModule instanceof ExternalModule)) {
  12203. return error(errInternalIdCannotBeExternal(source, importer));
  12204. }
  12205. return Promise.resolve(externalModule);
  12206. }
  12207. else {
  12208. return this.fetchModule(resolvedId.id, importer, resolvedId.moduleSideEffects, resolvedId.syntheticNamedExports, false);
  12209. }
  12210. }
  12211. handleResolveId(resolvedId, source, importer) {
  12212. if (resolvedId === null) {
  12213. if (isRelative(source)) {
  12214. return error(errUnresolvedImport(source, importer));
  12215. }
  12216. this.graph.warn(errUnresolvedImportTreatedAsExternal(source, importer));
  12217. return {
  12218. external: true,
  12219. id: source,
  12220. moduleSideEffects: this.hasModuleSideEffects(source, true),
  12221. syntheticNamedExports: false
  12222. };
  12223. }
  12224. else {
  12225. if (resolvedId.external && resolvedId.syntheticNamedExports) {
  12226. this.graph.warn(errExternalSyntheticExports(source, importer));
  12227. }
  12228. }
  12229. return resolvedId;
  12230. }
  12231. normalizeResolveIdResult(resolveIdResult, importer, source) {
  12232. let id = '';
  12233. let external = false;
  12234. let moduleSideEffects = null;
  12235. let syntheticNamedExports = false;
  12236. if (resolveIdResult) {
  12237. if (typeof resolveIdResult === 'object') {
  12238. id = resolveIdResult.id;
  12239. if (resolveIdResult.external) {
  12240. external = true;
  12241. }
  12242. if (typeof resolveIdResult.moduleSideEffects === 'boolean') {
  12243. moduleSideEffects = resolveIdResult.moduleSideEffects;
  12244. }
  12245. if (typeof resolveIdResult.syntheticNamedExports === 'boolean') {
  12246. syntheticNamedExports = resolveIdResult.syntheticNamedExports;
  12247. }
  12248. }
  12249. else {
  12250. if (this.isExternal(resolveIdResult, importer, true)) {
  12251. external = true;
  12252. }
  12253. id = external ? normalizeRelativeExternalId(importer, resolveIdResult) : resolveIdResult;
  12254. }
  12255. }
  12256. else {
  12257. id = normalizeRelativeExternalId(importer, source);
  12258. if (resolveIdResult !== false && !this.isExternal(id, importer, true)) {
  12259. return null;
  12260. }
  12261. external = true;
  12262. }
  12263. return {
  12264. external,
  12265. id,
  12266. moduleSideEffects: typeof moduleSideEffects === 'boolean'
  12267. ? moduleSideEffects
  12268. : this.hasModuleSideEffects(id, external),
  12269. syntheticNamedExports
  12270. };
  12271. }
  12272. resolveDynamicImport(module, specifier, importer) {
  12273. return __awaiter(this, void 0, void 0, function* () {
  12274. // TODO we only should expose the acorn AST here
  12275. const resolution = yield this.pluginDriver.hookFirst('resolveDynamicImport', [
  12276. specifier,
  12277. importer
  12278. ]);
  12279. if (typeof specifier !== 'string') {
  12280. if (typeof resolution === 'string') {
  12281. return resolution;
  12282. }
  12283. if (!resolution) {
  12284. return null;
  12285. }
  12286. return Object.assign({ external: false, moduleSideEffects: true }, resolution);
  12287. }
  12288. if (resolution == null) {
  12289. return (module.resolvedIds[specifier] =
  12290. module.resolvedIds[specifier] ||
  12291. this.handleResolveId(yield this.resolveId(specifier, module.id), specifier, module.id));
  12292. }
  12293. return this.handleResolveId(this.normalizeResolveIdResult(resolution, importer, specifier), specifier, importer);
  12294. });
  12295. }
  12296. }
  12297. var BuildPhase;
  12298. (function (BuildPhase) {
  12299. BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
  12300. BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
  12301. BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
  12302. })(BuildPhase || (BuildPhase = {}));
  12303. const CHAR_CODE_A = 97;
  12304. const CHAR_CODE_0 = 48;
  12305. function intToHex(num) {
  12306. if (num < 10)
  12307. return String.fromCharCode(CHAR_CODE_0 + num);
  12308. else
  12309. return String.fromCharCode(CHAR_CODE_A + (num - 10));
  12310. }
  12311. function Uint8ArrayToHexString(buffer) {
  12312. let str = '';
  12313. // hex conversion - 2 chars per 8 bit component
  12314. for (let i = 0; i < buffer.length; i++) {
  12315. const num = buffer[i];
  12316. // big endian conversion, but whatever
  12317. str += intToHex(num >> 4);
  12318. str += intToHex(num & 0xf);
  12319. }
  12320. return str;
  12321. }
  12322. function randomUint8Array(len) {
  12323. const buffer = new Uint8Array(len);
  12324. for (let i = 0; i < buffer.length; i++)
  12325. buffer[i] = Math.random() * (2 << 8);
  12326. return buffer;
  12327. }
  12328. function Uint8ArrayXor(to, from) {
  12329. for (let i = 0; i < to.length; i++)
  12330. to[i] = to[i] ^ from[i];
  12331. return to;
  12332. }
  12333. function assignChunkColouringHashes(entryModules, manualChunkModules) {
  12334. const { dependentEntryPointsByModule, dynamicImportersByModule } = analyzeModuleGraph(entryModules);
  12335. const dynamicDependentEntryPointsByDynamicEntry = getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicImportersByModule);
  12336. const staticEntries = new Set(entryModules);
  12337. function addColourToModuleDependencies(entry, colour, dynamicDependentEntryPoints) {
  12338. const manualChunkAlias = entry.manualChunkAlias;
  12339. const modulesToHandle = new Set([entry]);
  12340. for (const module of modulesToHandle) {
  12341. if (manualChunkAlias) {
  12342. module.manualChunkAlias = manualChunkAlias;
  12343. module.entryPointsHash = colour;
  12344. }
  12345. else if (dynamicDependentEntryPoints &&
  12346. areEntryPointsContainedOrDynamicallyDependent(dynamicDependentEntryPoints, dependentEntryPointsByModule.get(module))) {
  12347. continue;
  12348. }
  12349. else {
  12350. Uint8ArrayXor(module.entryPointsHash, colour);
  12351. }
  12352. for (const dependency of module.dependencies) {
  12353. if (!(dependency instanceof ExternalModule || dependency.manualChunkAlias)) {
  12354. modulesToHandle.add(dependency);
  12355. }
  12356. }
  12357. }
  12358. }
  12359. function areEntryPointsContainedOrDynamicallyDependent(entryPoints, superSet) {
  12360. const entriesToCheck = new Set(entryPoints);
  12361. for (const entry of entriesToCheck) {
  12362. if (!superSet.has(entry)) {
  12363. if (staticEntries.has(entry))
  12364. return false;
  12365. const dynamicDependentEntryPoints = dynamicDependentEntryPointsByDynamicEntry.get(entry);
  12366. for (const dependentEntry of dynamicDependentEntryPoints) {
  12367. entriesToCheck.add(dependentEntry);
  12368. }
  12369. }
  12370. }
  12371. return true;
  12372. }
  12373. if (manualChunkModules) {
  12374. for (const chunkName of Object.keys(manualChunkModules)) {
  12375. const entryHash = randomUint8Array(10);
  12376. for (const entry of manualChunkModules[chunkName]) {
  12377. addColourToModuleDependencies(entry, entryHash, null);
  12378. }
  12379. }
  12380. }
  12381. for (const entry of entryModules) {
  12382. if (!entry.manualChunkAlias) {
  12383. const entryHash = randomUint8Array(10);
  12384. addColourToModuleDependencies(entry, entryHash, null);
  12385. }
  12386. }
  12387. for (const entry of dynamicImportersByModule.keys()) {
  12388. if (!entry.manualChunkAlias) {
  12389. const entryHash = randomUint8Array(10);
  12390. addColourToModuleDependencies(entry, entryHash, dynamicDependentEntryPointsByDynamicEntry.get(entry));
  12391. }
  12392. }
  12393. }
  12394. function analyzeModuleGraph(entryModules) {
  12395. const dynamicImportersByModule = new Map();
  12396. const dependentEntryPointsByModule = new Map();
  12397. const entriesToHandle = new Set(entryModules);
  12398. for (const currentEntry of entriesToHandle) {
  12399. const modulesToHandle = new Set([currentEntry]);
  12400. for (const module of modulesToHandle) {
  12401. getDependentModules(dependentEntryPointsByModule, module).add(currentEntry);
  12402. for (const dependency of module.dependencies) {
  12403. if (!(dependency instanceof ExternalModule)) {
  12404. modulesToHandle.add(dependency);
  12405. }
  12406. }
  12407. for (const { resolution } of module.dynamicImports) {
  12408. if (resolution instanceof Module &&
  12409. resolution.dynamicallyImportedBy.length > 0 &&
  12410. !resolution.manualChunkAlias) {
  12411. getDependentModules(dynamicImportersByModule, resolution).add(module);
  12412. entriesToHandle.add(resolution);
  12413. }
  12414. }
  12415. }
  12416. }
  12417. return { dependentEntryPointsByModule, dynamicImportersByModule };
  12418. }
  12419. function getDependentModules(moduleMap, module) {
  12420. const dependentModules = moduleMap.get(module) || new Set();
  12421. moduleMap.set(module, dependentModules);
  12422. return dependentModules;
  12423. }
  12424. function getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicImportersByModule) {
  12425. const dynamicDependentEntryPointsByDynamicEntry = new Map();
  12426. for (const [dynamicEntry, importers] of dynamicImportersByModule.entries()) {
  12427. const dynamicDependentEntryPoints = getDependentModules(dynamicDependentEntryPointsByDynamicEntry, dynamicEntry);
  12428. for (const importer of importers) {
  12429. for (const entryPoint of dependentEntryPointsByModule.get(importer)) {
  12430. dynamicDependentEntryPoints.add(entryPoint);
  12431. }
  12432. }
  12433. }
  12434. return dynamicDependentEntryPointsByDynamicEntry;
  12435. }
  12436. const createHash$1 = () => crypto.createHash('sha256');
  12437. function generateAssetFileName(name, source, output) {
  12438. const emittedName = name || 'asset';
  12439. return makeUnique(renderNamePattern(output.assetFileNames, 'output.assetFileNames', {
  12440. hash() {
  12441. const hash = createHash$1();
  12442. hash.update(emittedName);
  12443. hash.update(':');
  12444. hash.update(source);
  12445. return hash.digest('hex').substr(0, 8);
  12446. },
  12447. ext: () => path.extname(emittedName).substr(1),
  12448. extname: () => path.extname(emittedName),
  12449. name: () => emittedName.substr(0, emittedName.length - path.extname(emittedName).length)
  12450. }), output.bundle);
  12451. }
  12452. function reserveFileNameInBundle(fileName, bundle, graph) {
  12453. if (fileName in bundle) {
  12454. graph.warn(errFileNameConflict(fileName));
  12455. }
  12456. bundle[fileName] = FILE_PLACEHOLDER;
  12457. }
  12458. const FILE_PLACEHOLDER = {
  12459. type: 'placeholder'
  12460. };
  12461. function hasValidType(emittedFile) {
  12462. return (emittedFile &&
  12463. (emittedFile.type === 'asset' ||
  12464. emittedFile.type === 'chunk'));
  12465. }
  12466. function hasValidName(emittedFile) {
  12467. const validatedName = emittedFile.fileName || emittedFile.name;
  12468. return (!validatedName || (typeof validatedName === 'string' && isPlainPathFragment(validatedName)));
  12469. }
  12470. function getValidSource(source, emittedFile, fileReferenceId) {
  12471. if (typeof source !== 'string' && !Buffer.isBuffer(source)) {
  12472. const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
  12473. return error(errFailedValidation(`Could not set source for ${typeof assetName === 'string' ? `asset "${assetName}"` : 'unnamed asset'}, asset source needs to be a string of Buffer.`));
  12474. }
  12475. return source;
  12476. }
  12477. function getAssetFileName(file, referenceId) {
  12478. if (typeof file.fileName !== 'string') {
  12479. return error(errAssetNotFinalisedForFileName(file.name || referenceId));
  12480. }
  12481. return file.fileName;
  12482. }
  12483. function getChunkFileName(file) {
  12484. const fileName = file.fileName || (file.module && file.module.facadeChunk.id);
  12485. if (!fileName)
  12486. return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
  12487. return fileName;
  12488. }
  12489. class FileEmitter {
  12490. constructor(graph, baseFileEmitter) {
  12491. this.output = null;
  12492. this.assertAssetsFinalized = () => {
  12493. for (const [referenceId, emittedFile] of this.filesByReferenceId.entries()) {
  12494. if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
  12495. return error(errNoAssetSourceSet(emittedFile.name || referenceId));
  12496. }
  12497. };
  12498. this.emitFile = (emittedFile) => {
  12499. if (!hasValidType(emittedFile)) {
  12500. return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile &&
  12501. emittedFile.type}".`));
  12502. }
  12503. if (!hasValidName(emittedFile)) {
  12504. 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 ||
  12505. emittedFile.name}".`));
  12506. }
  12507. if (emittedFile.type === 'chunk') {
  12508. return this.emitChunk(emittedFile);
  12509. }
  12510. else {
  12511. return this.emitAsset(emittedFile);
  12512. }
  12513. };
  12514. this.getFileName = (fileReferenceId) => {
  12515. const emittedFile = this.filesByReferenceId.get(fileReferenceId);
  12516. if (!emittedFile)
  12517. return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
  12518. if (emittedFile.type === 'chunk') {
  12519. return getChunkFileName(emittedFile);
  12520. }
  12521. else {
  12522. return getAssetFileName(emittedFile, fileReferenceId);
  12523. }
  12524. };
  12525. this.setAssetSource = (referenceId, requestedSource) => {
  12526. const consumedFile = this.filesByReferenceId.get(referenceId);
  12527. if (!consumedFile)
  12528. return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
  12529. if (consumedFile.type !== 'asset') {
  12530. return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
  12531. }
  12532. if (consumedFile.source !== undefined) {
  12533. return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
  12534. }
  12535. const source = getValidSource(requestedSource, consumedFile, referenceId);
  12536. if (this.output) {
  12537. this.finalizeAsset(consumedFile, source, referenceId, this.output);
  12538. }
  12539. else {
  12540. consumedFile.source = source;
  12541. }
  12542. };
  12543. this.setOutputBundle = (outputBundle, assetFileNames) => {
  12544. this.output = {
  12545. assetFileNames,
  12546. bundle: outputBundle
  12547. };
  12548. for (const emittedFile of this.filesByReferenceId.values()) {
  12549. if (emittedFile.fileName) {
  12550. reserveFileNameInBundle(emittedFile.fileName, this.output.bundle, this.graph);
  12551. }
  12552. }
  12553. for (const [referenceId, consumedFile] of this.filesByReferenceId.entries()) {
  12554. if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
  12555. this.finalizeAsset(consumedFile, consumedFile.source, referenceId, this.output);
  12556. }
  12557. }
  12558. };
  12559. this.graph = graph;
  12560. this.filesByReferenceId = baseFileEmitter
  12561. ? new Map(baseFileEmitter.filesByReferenceId)
  12562. : new Map();
  12563. }
  12564. assignReferenceId(file, idBase) {
  12565. let referenceId;
  12566. do {
  12567. const hash = createHash$1();
  12568. if (referenceId) {
  12569. hash.update(referenceId);
  12570. }
  12571. else {
  12572. hash.update(idBase);
  12573. }
  12574. referenceId = hash.digest('hex').substr(0, 8);
  12575. } while (this.filesByReferenceId.has(referenceId));
  12576. this.filesByReferenceId.set(referenceId, file);
  12577. return referenceId;
  12578. }
  12579. emitAsset(emittedAsset) {
  12580. const source = typeof emittedAsset.source !== 'undefined'
  12581. ? getValidSource(emittedAsset.source, emittedAsset, null)
  12582. : undefined;
  12583. const consumedAsset = {
  12584. fileName: emittedAsset.fileName,
  12585. name: emittedAsset.name,
  12586. source,
  12587. type: 'asset'
  12588. };
  12589. const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type);
  12590. if (this.output) {
  12591. if (emittedAsset.fileName) {
  12592. reserveFileNameInBundle(emittedAsset.fileName, this.output.bundle, this.graph);
  12593. }
  12594. if (source !== undefined) {
  12595. this.finalizeAsset(consumedAsset, source, referenceId, this.output);
  12596. }
  12597. }
  12598. return referenceId;
  12599. }
  12600. emitChunk(emittedChunk) {
  12601. if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
  12602. return error(errInvalidRollupPhaseForChunkEmission());
  12603. }
  12604. if (typeof emittedChunk.id !== 'string') {
  12605. return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
  12606. }
  12607. const consumedChunk = {
  12608. fileName: emittedChunk.fileName,
  12609. module: null,
  12610. name: emittedChunk.name || emittedChunk.id,
  12611. type: 'chunk'
  12612. };
  12613. this.graph.moduleLoader
  12614. .addEntryModules([
  12615. {
  12616. fileName: emittedChunk.fileName || null,
  12617. id: emittedChunk.id,
  12618. name: emittedChunk.name || null
  12619. }
  12620. ], false)
  12621. .then(({ newEntryModules: [module] }) => {
  12622. consumedChunk.module = module;
  12623. })
  12624. .catch(() => {
  12625. // Avoid unhandled Promise rejection as the error will be thrown later
  12626. // once module loading has finished
  12627. });
  12628. return this.assignReferenceId(consumedChunk, emittedChunk.id);
  12629. }
  12630. finalizeAsset(consumedFile, source, referenceId, output) {
  12631. const fileName = consumedFile.fileName ||
  12632. this.findExistingAssetFileNameWithSource(output.bundle, source) ||
  12633. generateAssetFileName(consumedFile.name, source, output);
  12634. // We must not modify the original assets to avoid interaction between outputs
  12635. const assetWithFileName = Object.assign(Object.assign({}, consumedFile), { source, fileName });
  12636. this.filesByReferenceId.set(referenceId, assetWithFileName);
  12637. const graph = this.graph;
  12638. output.bundle[fileName] = {
  12639. fileName,
  12640. get isAsset() {
  12641. graph.warnDeprecation('Accessing "isAsset" on files in the bundle is deprecated, please use "type === \'asset\'" instead', false);
  12642. return true;
  12643. },
  12644. source,
  12645. type: 'asset'
  12646. };
  12647. }
  12648. findExistingAssetFileNameWithSource(bundle, source) {
  12649. for (const fileName of Object.keys(bundle)) {
  12650. const outputFile = bundle[fileName];
  12651. if (outputFile.type === 'asset' &&
  12652. (Buffer.isBuffer(source) && Buffer.isBuffer(outputFile.source)
  12653. ? source.equals(outputFile.source)
  12654. : source === outputFile.source))
  12655. return fileName;
  12656. }
  12657. return null;
  12658. }
  12659. }
  12660. function getDeprecatedContextHandler(handler, handlerName, newHandlerName, pluginName, activeDeprecation, graph) {
  12661. let deprecationWarningShown = false;
  12662. return ((...args) => {
  12663. if (!deprecationWarningShown) {
  12664. deprecationWarningShown = true;
  12665. graph.warnDeprecation({
  12666. message: `The "this.${handlerName}" plugin context function used by plugin ${pluginName} is deprecated. The "this.${newHandlerName}" plugin context function should be used instead.`,
  12667. plugin: pluginName
  12668. }, activeDeprecation);
  12669. }
  12670. return handler(...args);
  12671. });
  12672. }
  12673. function getPluginContexts(pluginCache, graph, fileEmitter, watcher) {
  12674. const existingPluginNames = new Set();
  12675. return (plugin, pidx) => {
  12676. let cacheable = true;
  12677. if (typeof plugin.cacheKey !== 'string') {
  12678. if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  12679. plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
  12680. existingPluginNames.has(plugin.name)) {
  12681. cacheable = false;
  12682. }
  12683. else {
  12684. existingPluginNames.add(plugin.name);
  12685. }
  12686. }
  12687. let cacheInstance;
  12688. if (!pluginCache) {
  12689. cacheInstance = NO_CACHE;
  12690. }
  12691. else if (cacheable) {
  12692. const cacheKey = plugin.cacheKey || plugin.name;
  12693. cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
  12694. }
  12695. else {
  12696. cacheInstance = getCacheForUncacheablePlugin(plugin.name);
  12697. }
  12698. const context = {
  12699. addWatchFile(id) {
  12700. if (graph.phase >= BuildPhase.GENERATE) {
  12701. return this.error(errInvalidRollupPhaseForAddWatchFile());
  12702. }
  12703. graph.watchFiles[id] = true;
  12704. },
  12705. cache: cacheInstance,
  12706. emitAsset: getDeprecatedContextHandler((name, source) => fileEmitter.emitFile({ type: 'asset', name, source }), 'emitAsset', 'emitFile', plugin.name, false, graph),
  12707. emitChunk: getDeprecatedContextHandler((id, options) => fileEmitter.emitFile({ type: 'chunk', id, name: options && options.name }), 'emitChunk', 'emitFile', plugin.name, false, graph),
  12708. emitFile: fileEmitter.emitFile,
  12709. error(err) {
  12710. return throwPluginError(err, plugin.name);
  12711. },
  12712. getAssetFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getAssetFileName', 'getFileName', plugin.name, false, graph),
  12713. getChunkFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getChunkFileName', 'getFileName', plugin.name, false, graph),
  12714. getFileName: fileEmitter.getFileName,
  12715. getModuleInfo(moduleId) {
  12716. const foundModule = graph.moduleById.get(moduleId);
  12717. if (foundModule == null) {
  12718. throw new Error(`Unable to find module ${moduleId}`);
  12719. }
  12720. return {
  12721. hasModuleSideEffects: foundModule.moduleSideEffects,
  12722. id: foundModule.id,
  12723. importedIds: foundModule instanceof ExternalModule
  12724. ? []
  12725. : Array.from(foundModule.sources).map(id => foundModule.resolvedIds[id].id),
  12726. isEntry: foundModule instanceof Module && foundModule.isEntryPoint,
  12727. isExternal: foundModule instanceof ExternalModule
  12728. };
  12729. },
  12730. isExternal: getDeprecatedContextHandler((id, parentId, isResolved = false) => graph.moduleLoader.isExternal(id, parentId, isResolved), 'isExternal', 'resolve', plugin.name, false, graph),
  12731. meta: {
  12732. rollupVersion: version
  12733. },
  12734. get moduleIds() {
  12735. return graph.moduleById.keys();
  12736. },
  12737. parse: graph.contextParse,
  12738. resolve(source, importer, options) {
  12739. return graph.moduleLoader.resolveId(source, importer, options && options.skipSelf ? pidx : null);
  12740. },
  12741. resolveId: getDeprecatedContextHandler((source, importer) => graph.moduleLoader
  12742. .resolveId(source, importer)
  12743. .then(resolveId => resolveId && resolveId.id), 'resolveId', 'resolve', plugin.name, false, graph),
  12744. setAssetSource: fileEmitter.setAssetSource,
  12745. warn(warning) {
  12746. if (typeof warning === 'string')
  12747. warning = { message: warning };
  12748. if (warning.code)
  12749. warning.pluginCode = warning.code;
  12750. warning.code = 'PLUGIN_WARNING';
  12751. warning.plugin = plugin.name;
  12752. graph.warn(warning);
  12753. },
  12754. watcher: watcher
  12755. ? (() => {
  12756. let deprecationWarningShown = false;
  12757. function deprecatedWatchListener(event, handler) {
  12758. if (!deprecationWarningShown) {
  12759. context.warn({
  12760. code: 'PLUGIN_WATCHER_DEPRECATED',
  12761. message: `this.watcher usage is deprecated in plugins. Use the watchChange plugin hook and this.addWatchFile() instead.`
  12762. });
  12763. deprecationWarningShown = true;
  12764. }
  12765. return watcher.on(event, handler);
  12766. }
  12767. return Object.assign(Object.assign({}, watcher), { addListener: deprecatedWatchListener, on: deprecatedWatchListener });
  12768. })()
  12769. : undefined
  12770. };
  12771. return context;
  12772. };
  12773. }
  12774. class PluginDriver {
  12775. constructor(graph, userPlugins, pluginCache, preserveSymlinks, watcher, basePluginDriver) {
  12776. this.previousHooks = new Set(['options']);
  12777. warnDeprecatedHooks(userPlugins, graph);
  12778. this.graph = graph;
  12779. this.pluginCache = pluginCache;
  12780. this.preserveSymlinks = preserveSymlinks;
  12781. this.watcher = watcher;
  12782. this.fileEmitter = new FileEmitter(graph, basePluginDriver && basePluginDriver.fileEmitter);
  12783. this.emitFile = this.fileEmitter.emitFile;
  12784. this.getFileName = this.fileEmitter.getFileName;
  12785. this.finaliseAssets = this.fileEmitter.assertAssetsFinalized;
  12786. this.setOutputBundle = this.fileEmitter.setOutputBundle;
  12787. this.plugins = userPlugins.concat(basePluginDriver ? basePluginDriver.plugins : [getRollupDefaultPlugin(preserveSymlinks)]);
  12788. this.pluginContexts = this.plugins.map(getPluginContexts(pluginCache, graph, this.fileEmitter, watcher));
  12789. if (basePluginDriver) {
  12790. for (const plugin of userPlugins) {
  12791. for (const hook of basePluginDriver.previousHooks) {
  12792. if (hook in plugin) {
  12793. graph.warn(errInputHookInOutputPlugin(plugin.name, hook));
  12794. }
  12795. }
  12796. }
  12797. }
  12798. }
  12799. createOutputPluginDriver(plugins) {
  12800. return new PluginDriver(this.graph, plugins, this.pluginCache, this.preserveSymlinks, this.watcher, this);
  12801. }
  12802. // chains, first non-null result stops and returns
  12803. hookFirst(hookName, args, replaceContext, skip) {
  12804. let promise = Promise.resolve();
  12805. for (let i = 0; i < this.plugins.length; i++) {
  12806. if (skip === i)
  12807. continue;
  12808. promise = promise.then((result) => {
  12809. if (result != null)
  12810. return result;
  12811. return this.runHook(hookName, args, i, false, replaceContext);
  12812. });
  12813. }
  12814. return promise;
  12815. }
  12816. // chains synchronously, first non-null result stops and returns
  12817. hookFirstSync(hookName, args, replaceContext) {
  12818. for (let i = 0; i < this.plugins.length; i++) {
  12819. const result = this.runHookSync(hookName, args, i, replaceContext);
  12820. if (result != null)
  12821. return result;
  12822. }
  12823. return null;
  12824. }
  12825. // parallel, ignores returns
  12826. hookParallel(hookName, args, replaceContext) {
  12827. const promises = [];
  12828. for (let i = 0; i < this.plugins.length; i++) {
  12829. const hookPromise = this.runHook(hookName, args, i, false, replaceContext);
  12830. if (!hookPromise)
  12831. continue;
  12832. promises.push(hookPromise);
  12833. }
  12834. return Promise.all(promises).then(() => { });
  12835. }
  12836. // chains, reduces returns of type R, to type T, handling the reduced value as the first hook argument
  12837. hookReduceArg0(hookName, [arg0, ...args], reduce, replaceContext) {
  12838. let promise = Promise.resolve(arg0);
  12839. for (let i = 0; i < this.plugins.length; i++) {
  12840. promise = promise.then(arg0 => {
  12841. const hookPromise = this.runHook(hookName, [arg0, ...args], i, false, replaceContext);
  12842. if (!hookPromise)
  12843. return arg0;
  12844. return hookPromise.then((result) => reduce.call(this.pluginContexts[i], arg0, result, this.plugins[i]));
  12845. });
  12846. }
  12847. return promise;
  12848. }
  12849. // chains synchronously, reduces returns of type R, to type T, handling the reduced value as the first hook argument
  12850. hookReduceArg0Sync(hookName, [arg0, ...args], reduce, replaceContext) {
  12851. for (let i = 0; i < this.plugins.length; i++) {
  12852. const result = this.runHookSync(hookName, [arg0, ...args], i, replaceContext);
  12853. arg0 = reduce.call(this.pluginContexts[i], arg0, result, this.plugins[i]);
  12854. }
  12855. return arg0;
  12856. }
  12857. // chains, reduces returns of type R, to type T, handling the reduced value separately. permits hooks as values.
  12858. hookReduceValue(hookName, initialValue, args, reduce, replaceContext) {
  12859. let promise = Promise.resolve(initialValue);
  12860. for (let i = 0; i < this.plugins.length; i++) {
  12861. promise = promise.then(value => {
  12862. const hookPromise = this.runHook(hookName, args, i, true, replaceContext);
  12863. if (!hookPromise)
  12864. return value;
  12865. return hookPromise.then((result) => reduce.call(this.pluginContexts[i], value, result, this.plugins[i]));
  12866. });
  12867. }
  12868. return promise;
  12869. }
  12870. // chains, reduces returns of type R, to type T, handling the reduced value separately. permits hooks as values.
  12871. hookReduceValueSync(hookName, initialValue, args, reduce, replaceContext) {
  12872. let acc = initialValue;
  12873. for (let i = 0; i < this.plugins.length; i++) {
  12874. const result = this.runHookSync(hookName, args, i, replaceContext);
  12875. acc = reduce.call(this.pluginContexts[i], acc, result, this.plugins[i]);
  12876. }
  12877. return acc;
  12878. }
  12879. // chains, ignores returns
  12880. hookSeq(hookName, args, replaceContext) {
  12881. return __awaiter(this, void 0, void 0, function* () {
  12882. let promise = Promise.resolve();
  12883. for (let i = 0; i < this.plugins.length; i++)
  12884. promise = promise.then(() => this.runHook(hookName, args, i, false, replaceContext));
  12885. return promise;
  12886. });
  12887. }
  12888. // chains, ignores returns
  12889. hookSeqSync(hookName, args, replaceContext) {
  12890. for (let i = 0; i < this.plugins.length; i++)
  12891. this.runHookSync(hookName, args, i, replaceContext);
  12892. }
  12893. runHook(hookName, args, pluginIndex, permitValues, hookContext) {
  12894. this.previousHooks.add(hookName);
  12895. const plugin = this.plugins[pluginIndex];
  12896. const hook = plugin[hookName];
  12897. if (!hook)
  12898. return undefined;
  12899. let context = this.pluginContexts[pluginIndex];
  12900. if (hookContext) {
  12901. context = hookContext(context, plugin);
  12902. }
  12903. return Promise.resolve()
  12904. .then(() => {
  12905. // permit values allows values to be returned instead of a functional hook
  12906. if (typeof hook !== 'function') {
  12907. if (permitValues)
  12908. return hook;
  12909. return error({
  12910. code: 'INVALID_PLUGIN_HOOK',
  12911. message: `Error running plugin hook ${hookName} for ${plugin.name}, expected a function hook.`
  12912. });
  12913. }
  12914. return hook.apply(context, args);
  12915. })
  12916. .catch(err => throwPluginError(err, plugin.name, { hook: hookName }));
  12917. }
  12918. runHookSync(hookName, args, pluginIndex, hookContext) {
  12919. this.previousHooks.add(hookName);
  12920. const plugin = this.plugins[pluginIndex];
  12921. let context = this.pluginContexts[pluginIndex];
  12922. const hook = plugin[hookName];
  12923. if (!hook)
  12924. return undefined;
  12925. if (hookContext) {
  12926. context = hookContext(context, plugin);
  12927. }
  12928. try {
  12929. // permit values allows values to be returned instead of a functional hook
  12930. if (typeof hook !== 'function') {
  12931. return error({
  12932. code: 'INVALID_PLUGIN_HOOK',
  12933. message: `Error running plugin hook ${hookName} for ${plugin.name}, expected a function hook.`
  12934. });
  12935. }
  12936. return hook.apply(context, args);
  12937. }
  12938. catch (err) {
  12939. return throwPluginError(err, plugin.name, { hook: hookName });
  12940. }
  12941. }
  12942. }
  12943. function makeOnwarn() {
  12944. const warned = Object.create(null);
  12945. return (warning) => {
  12946. const str = warning.toString();
  12947. if (str in warned)
  12948. return;
  12949. console.error(str);
  12950. warned[str] = true;
  12951. };
  12952. }
  12953. function normalizeEntryModules(entryModules) {
  12954. if (typeof entryModules === 'string') {
  12955. return [{ fileName: null, name: null, id: entryModules }];
  12956. }
  12957. if (Array.isArray(entryModules)) {
  12958. return entryModules.map(id => ({ fileName: null, name: null, id }));
  12959. }
  12960. return Object.keys(entryModules).map(name => ({
  12961. fileName: null,
  12962. id: entryModules[name],
  12963. name
  12964. }));
  12965. }
  12966. class Graph {
  12967. constructor(options, watcher) {
  12968. this.moduleById = new Map();
  12969. this.needsTreeshakingPass = false;
  12970. this.phase = BuildPhase.LOAD_AND_PARSE;
  12971. this.watchFiles = Object.create(null);
  12972. this.externalModules = [];
  12973. this.modules = [];
  12974. this.onwarn = options.onwarn || makeOnwarn();
  12975. this.deoptimizationTracker = new PathTracker();
  12976. this.cachedModules = new Map();
  12977. if (options.cache) {
  12978. if (options.cache.modules)
  12979. for (const module of options.cache.modules)
  12980. this.cachedModules.set(module.id, module);
  12981. }
  12982. if (options.cache !== false) {
  12983. this.pluginCache = (options.cache && options.cache.plugins) || Object.create(null);
  12984. // increment access counter
  12985. for (const name in this.pluginCache) {
  12986. const cache = this.pluginCache[name];
  12987. for (const key of Object.keys(cache))
  12988. cache[key][0]++;
  12989. }
  12990. }
  12991. this.preserveModules = options.preserveModules;
  12992. this.strictDeprecations = options.strictDeprecations;
  12993. this.cacheExpiry = options.experimentalCacheExpiry;
  12994. if (options.treeshake !== false) {
  12995. this.treeshakingOptions =
  12996. options.treeshake && options.treeshake !== true
  12997. ? {
  12998. annotations: options.treeshake.annotations !== false,
  12999. moduleSideEffects: options.treeshake.moduleSideEffects,
  13000. propertyReadSideEffects: options.treeshake.propertyReadSideEffects !== false,
  13001. pureExternalModules: options.treeshake.pureExternalModules,
  13002. tryCatchDeoptimization: options.treeshake.tryCatchDeoptimization !== false,
  13003. unknownGlobalSideEffects: options.treeshake.unknownGlobalSideEffects !== false
  13004. }
  13005. : {
  13006. annotations: true,
  13007. moduleSideEffects: true,
  13008. propertyReadSideEffects: true,
  13009. tryCatchDeoptimization: true,
  13010. unknownGlobalSideEffects: true
  13011. };
  13012. if (typeof this.treeshakingOptions.pureExternalModules !== 'undefined') {
  13013. this.warnDeprecation(`The "treeshake.pureExternalModules" option is deprecated. The "treeshake.moduleSideEffects" option should be used instead. "treeshake.pureExternalModules: true" is equivalent to "treeshake.moduleSideEffects: 'no-external'"`, false);
  13014. }
  13015. }
  13016. this.contextParse = (code, options = {}) => this.acornParser.parse(code, Object.assign(Object.assign(Object.assign({}, defaultAcornOptions), options), this.acornOptions));
  13017. this.pluginDriver = new PluginDriver(this, options.plugins, this.pluginCache, options.preserveSymlinks === true, watcher);
  13018. if (watcher) {
  13019. const handleChange = (id) => this.pluginDriver.hookSeqSync('watchChange', [id]);
  13020. watcher.on('change', handleChange);
  13021. watcher.once('restart', () => {
  13022. watcher.removeListener('change', handleChange);
  13023. });
  13024. }
  13025. this.shimMissingExports = options.shimMissingExports;
  13026. this.scope = new GlobalScope();
  13027. this.context = String(options.context);
  13028. const optionsModuleContext = options.moduleContext;
  13029. if (typeof optionsModuleContext === 'function') {
  13030. this.getModuleContext = id => optionsModuleContext(id) || this.context;
  13031. }
  13032. else if (typeof optionsModuleContext === 'object') {
  13033. const moduleContext = new Map();
  13034. for (const key in optionsModuleContext) {
  13035. moduleContext.set(path.resolve(key), optionsModuleContext[key]);
  13036. }
  13037. this.getModuleContext = id => moduleContext.get(id) || this.context;
  13038. }
  13039. else {
  13040. this.getModuleContext = () => this.context;
  13041. }
  13042. this.acornOptions = options.acorn ? Object.assign({}, options.acorn) : {};
  13043. const acornPluginsToInject = [];
  13044. acornPluginsToInject.push(acornImportMeta, acornExportNsFrom);
  13045. this.acornOptions.allowAwaitOutsideFunction = true;
  13046. const acornInjectPlugins = options.acornInjectPlugins;
  13047. acornPluginsToInject.push(...(Array.isArray(acornInjectPlugins)
  13048. ? acornInjectPlugins
  13049. : acornInjectPlugins
  13050. ? [acornInjectPlugins]
  13051. : []));
  13052. this.acornParser = acorn.Parser.extend(...acornPluginsToInject);
  13053. this.moduleLoader = new ModuleLoader(this, this.moduleById, this.pluginDriver, options.external, (typeof options.manualChunks === 'function' && options.manualChunks), (this.treeshakingOptions ? this.treeshakingOptions.moduleSideEffects : null), (this.treeshakingOptions ? this.treeshakingOptions.pureExternalModules : false));
  13054. }
  13055. build(entryModules, manualChunks, inlineDynamicImports) {
  13056. // Phase 1 – discovery. We load the entry module and find which
  13057. // modules it imports, and import those, until we have all
  13058. // of the entry module's dependencies
  13059. timeStart('parse modules', 2);
  13060. return Promise.all([
  13061. this.moduleLoader.addEntryModules(normalizeEntryModules(entryModules), true),
  13062. (manualChunks &&
  13063. typeof manualChunks === 'object' &&
  13064. this.moduleLoader.addManualChunks(manualChunks))
  13065. ]).then(([{ entryModules, manualChunkModulesByAlias }]) => {
  13066. if (entryModules.length === 0) {
  13067. throw new Error('You must supply options.input to rollup');
  13068. }
  13069. for (const module of this.moduleById.values()) {
  13070. if (module instanceof Module) {
  13071. this.modules.push(module);
  13072. }
  13073. else {
  13074. this.externalModules.push(module);
  13075. }
  13076. }
  13077. timeEnd('parse modules', 2);
  13078. this.phase = BuildPhase.ANALYSE;
  13079. // Phase 2 - linking. We populate the module dependency links and
  13080. // determine the topological execution order for the bundle
  13081. timeStart('analyse dependency graph', 2);
  13082. this.link(entryModules);
  13083. timeEnd('analyse dependency graph', 2);
  13084. // Phase 3 – marking. We include all statements that should be included
  13085. timeStart('mark included statements', 2);
  13086. if (inlineDynamicImports) {
  13087. if (entryModules.length > 1) {
  13088. throw new Error('Internal Error: can only inline dynamic imports for single-file builds.');
  13089. }
  13090. }
  13091. for (const module of entryModules) {
  13092. module.includeAllExports();
  13093. }
  13094. this.includeMarked(this.modules);
  13095. // check for unused external imports
  13096. for (const externalModule of this.externalModules)
  13097. externalModule.warnUnusedImports();
  13098. timeEnd('mark included statements', 2);
  13099. // Phase 4 – we construct the chunks, working out the optimal chunking using
  13100. // entry point graph colouring, before generating the import and export facades
  13101. timeStart('generate chunks', 2);
  13102. if (!this.preserveModules && !inlineDynamicImports) {
  13103. assignChunkColouringHashes(entryModules, manualChunkModulesByAlias);
  13104. }
  13105. // TODO: there is one special edge case unhandled here and that is that any module
  13106. // exposed as an unresolvable export * (to a graph external export *,
  13107. // either as a namespace import reexported or top-level export *)
  13108. // should be made to be its own entry point module before chunking
  13109. let chunks = [];
  13110. if (this.preserveModules) {
  13111. for (const module of this.modules) {
  13112. const chunk = new Chunk$1(this, [module]);
  13113. if (module.isEntryPoint || !chunk.isEmpty) {
  13114. chunk.entryModules = [module];
  13115. }
  13116. chunks.push(chunk);
  13117. }
  13118. }
  13119. else {
  13120. const chunkModules = {};
  13121. for (const module of this.modules) {
  13122. const entryPointsHashStr = Uint8ArrayToHexString(module.entryPointsHash);
  13123. const curChunk = chunkModules[entryPointsHashStr];
  13124. if (curChunk) {
  13125. curChunk.push(module);
  13126. }
  13127. else {
  13128. chunkModules[entryPointsHashStr] = [module];
  13129. }
  13130. }
  13131. for (const entryHashSum in chunkModules) {
  13132. const chunkModulesOrdered = chunkModules[entryHashSum];
  13133. sortByExecutionOrder(chunkModulesOrdered);
  13134. const chunk = new Chunk$1(this, chunkModulesOrdered);
  13135. chunks.push(chunk);
  13136. }
  13137. }
  13138. for (const chunk of chunks) {
  13139. chunk.link();
  13140. }
  13141. chunks = chunks.filter(isChunkRendered);
  13142. const facades = [];
  13143. for (const chunk of chunks) {
  13144. facades.push(...chunk.generateFacades());
  13145. }
  13146. timeEnd('generate chunks', 2);
  13147. this.phase = BuildPhase.GENERATE;
  13148. return chunks.concat(facades);
  13149. });
  13150. }
  13151. getCache() {
  13152. // handle plugin cache eviction
  13153. for (const name in this.pluginCache) {
  13154. const cache = this.pluginCache[name];
  13155. let allDeleted = true;
  13156. for (const key of Object.keys(cache)) {
  13157. if (cache[key][0] >= this.cacheExpiry)
  13158. delete cache[key];
  13159. else
  13160. allDeleted = false;
  13161. }
  13162. if (allDeleted)
  13163. delete this.pluginCache[name];
  13164. }
  13165. return {
  13166. modules: this.modules.map(module => module.toJSON()),
  13167. plugins: this.pluginCache
  13168. };
  13169. }
  13170. includeMarked(modules) {
  13171. if (this.treeshakingOptions) {
  13172. let treeshakingPass = 1;
  13173. do {
  13174. timeStart(`treeshaking pass ${treeshakingPass}`, 3);
  13175. this.needsTreeshakingPass = false;
  13176. for (const module of modules) {
  13177. if (module.isExecuted)
  13178. module.include();
  13179. }
  13180. timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
  13181. } while (this.needsTreeshakingPass);
  13182. }
  13183. else {
  13184. // Necessary to properly replace namespace imports
  13185. for (const module of modules)
  13186. module.includeAllInBundle();
  13187. }
  13188. }
  13189. warn(warning) {
  13190. warning.toString = () => {
  13191. let str = '';
  13192. if (warning.plugin)
  13193. str += `(${warning.plugin} plugin) `;
  13194. if (warning.loc)
  13195. str += `${relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `;
  13196. str += warning.message;
  13197. return str;
  13198. };
  13199. this.onwarn(warning);
  13200. }
  13201. warnDeprecation(deprecation, activeDeprecation) {
  13202. if (activeDeprecation || this.strictDeprecations) {
  13203. const warning = errDeprecation(deprecation);
  13204. if (this.strictDeprecations) {
  13205. return error(warning);
  13206. }
  13207. this.warn(warning);
  13208. }
  13209. }
  13210. link(entryModules) {
  13211. for (const module of this.modules) {
  13212. module.linkDependencies();
  13213. }
  13214. const { orderedModules, cyclePaths } = analyseModuleExecution(entryModules);
  13215. for (const cyclePath of cyclePaths) {
  13216. this.warn({
  13217. code: 'CIRCULAR_DEPENDENCY',
  13218. cycle: cyclePath,
  13219. importer: cyclePath[0],
  13220. message: `Circular dependency: ${cyclePath.join(' -> ')}`
  13221. });
  13222. }
  13223. this.modules = orderedModules;
  13224. for (const module of this.modules) {
  13225. module.bindReferences();
  13226. }
  13227. this.warnForMissingExports();
  13228. }
  13229. warnForMissingExports() {
  13230. for (const module of this.modules) {
  13231. for (const importName of Object.keys(module.importDescriptions)) {
  13232. const importDescription = module.importDescriptions[importName];
  13233. if (importDescription.name !== '*' &&
  13234. !importDescription.module.getVariableForExportName(importDescription.name)) {
  13235. module.warn({
  13236. code: 'NON_EXISTENT_EXPORT',
  13237. message: `Non-existent export '${importDescription.name}' is imported from ${relativeId(importDescription.module.id)}`,
  13238. name: importDescription.name,
  13239. source: importDescription.module.id
  13240. }, importDescription.start);
  13241. }
  13242. }
  13243. }
  13244. }
  13245. }
  13246. function evalIfFn(strOrFn) {
  13247. switch (typeof strOrFn) {
  13248. case 'function':
  13249. return strOrFn();
  13250. case 'string':
  13251. return strOrFn;
  13252. default:
  13253. return '';
  13254. }
  13255. }
  13256. const concatSep = (out, next) => (next ? `${out}\n${next}` : out);
  13257. const concatDblSep = (out, next) => (next ? `${out}\n\n${next}` : out);
  13258. function createAddons(options, outputPluginDriver) {
  13259. return Promise.all([
  13260. outputPluginDriver.hookReduceValue('banner', evalIfFn(options.banner), [], concatSep),
  13261. outputPluginDriver.hookReduceValue('footer', evalIfFn(options.footer), [], concatSep),
  13262. outputPluginDriver.hookReduceValue('intro', evalIfFn(options.intro), [], concatDblSep),
  13263. outputPluginDriver.hookReduceValue('outro', evalIfFn(options.outro), [], concatDblSep)
  13264. ])
  13265. .then(([banner, footer, intro, outro]) => {
  13266. if (intro)
  13267. intro += '\n\n';
  13268. if (outro)
  13269. outro = `\n\n${outro}`;
  13270. if (banner.length)
  13271. banner += '\n';
  13272. if (footer.length)
  13273. footer = '\n' + footer;
  13274. return { intro, outro, banner, footer };
  13275. })
  13276. .catch((err) => {
  13277. return error({
  13278. code: 'ADDON_ERROR',
  13279. message: `Could not retrieve ${err.hook}. Check configuration of plugin ${err.plugin}.
  13280. \tError Message: ${err.message}`
  13281. });
  13282. });
  13283. }
  13284. function assignChunkIds(chunks, inputOptions, outputOptions, inputBase, addons, bundle, outputPluginDriver) {
  13285. const entryChunks = [];
  13286. const otherChunks = [];
  13287. for (const chunk of chunks) {
  13288. (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint
  13289. ? entryChunks
  13290. : otherChunks).push(chunk);
  13291. }
  13292. // make sure entry chunk names take precedence with regard to deconflicting
  13293. const chunksForNaming = entryChunks.concat(otherChunks);
  13294. for (const chunk of chunksForNaming) {
  13295. if (outputOptions.file) {
  13296. chunk.id = path.basename(outputOptions.file);
  13297. }
  13298. else if (inputOptions.preserveModules) {
  13299. chunk.id = chunk.generateIdPreserveModules(inputBase, outputOptions, bundle);
  13300. }
  13301. else {
  13302. chunk.id = chunk.generateId(addons, outputOptions, bundle, true, outputPluginDriver);
  13303. }
  13304. bundle[chunk.id] = FILE_PLACEHOLDER;
  13305. }
  13306. }
  13307. // ported from https://github.com/substack/node-commondir
  13308. function commondir(files) {
  13309. if (files.length === 0)
  13310. return '/';
  13311. if (files.length === 1)
  13312. return path.dirname(files[0]);
  13313. const commonSegments = files.slice(1).reduce((commonSegments, file) => {
  13314. const pathSegements = file.split(/\/+|\\+/);
  13315. let i;
  13316. for (i = 0; commonSegments[i] === pathSegements[i] &&
  13317. i < Math.min(commonSegments.length, pathSegements.length); i++)
  13318. ;
  13319. return commonSegments.slice(0, i);
  13320. }, files[0].split(/\/+|\\+/));
  13321. // Windows correctly handles paths with forward-slashes
  13322. return commonSegments.length > 1 ? commonSegments.join('/') : '/';
  13323. }
  13324. function getExportMode(chunk, { exports: exportMode, name, format }, facadeModuleId) {
  13325. const exportKeys = chunk.getExportNames();
  13326. if (exportMode === 'default') {
  13327. if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
  13328. return error(errIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
  13329. }
  13330. }
  13331. else if (exportMode === 'none' && exportKeys.length) {
  13332. return error(errIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
  13333. }
  13334. if (!exportMode || exportMode === 'auto') {
  13335. if (exportKeys.length === 0) {
  13336. exportMode = 'none';
  13337. }
  13338. else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
  13339. exportMode = 'default';
  13340. }
  13341. else {
  13342. if (format !== 'es' && exportKeys.indexOf('default') !== -1) {
  13343. chunk.graph.warn(errMixedExport(facadeModuleId, name));
  13344. }
  13345. exportMode = 'named';
  13346. }
  13347. }
  13348. return exportMode;
  13349. }
  13350. const createGetOption = (config, command) => (name, defaultValue) => command[name] !== undefined
  13351. ? command[name]
  13352. : config[name] !== undefined
  13353. ? config[name]
  13354. : defaultValue;
  13355. const normalizeObjectOptionValue = (optionValue) => {
  13356. if (!optionValue) {
  13357. return optionValue;
  13358. }
  13359. if (typeof optionValue !== 'object') {
  13360. return {};
  13361. }
  13362. return optionValue;
  13363. };
  13364. const getObjectOption = (config, command, name) => {
  13365. const commandOption = normalizeObjectOptionValue(command[name]);
  13366. const configOption = normalizeObjectOptionValue(config[name]);
  13367. if (commandOption !== undefined) {
  13368. return commandOption && configOption ? Object.assign(Object.assign({}, configOption), commandOption) : commandOption;
  13369. }
  13370. return configOption;
  13371. };
  13372. function ensureArray(items) {
  13373. if (Array.isArray(items)) {
  13374. return items.filter(Boolean);
  13375. }
  13376. if (items) {
  13377. return [items];
  13378. }
  13379. return [];
  13380. }
  13381. const defaultOnWarn = warning => {
  13382. if (typeof warning === 'string') {
  13383. console.warn(warning);
  13384. }
  13385. else {
  13386. console.warn(warning.message);
  13387. }
  13388. };
  13389. const getOnWarn = (config, defaultOnWarnHandler = defaultOnWarn) => config.onwarn
  13390. ? warning => config.onwarn(warning, defaultOnWarnHandler)
  13391. : defaultOnWarnHandler;
  13392. const getExternal = (config, command) => {
  13393. const configExternal = config.external;
  13394. return typeof configExternal === 'function'
  13395. ? (id, ...rest) => configExternal(id, ...rest) || command.external.indexOf(id) !== -1
  13396. : (typeof config.external === 'string'
  13397. ? [configExternal]
  13398. : Array.isArray(configExternal)
  13399. ? configExternal
  13400. : []).concat(command.external);
  13401. };
  13402. const commandAliases = {
  13403. c: 'config',
  13404. d: 'dir',
  13405. e: 'external',
  13406. f: 'format',
  13407. g: 'globals',
  13408. h: 'help',
  13409. i: 'input',
  13410. m: 'sourcemap',
  13411. n: 'name',
  13412. o: 'file',
  13413. p: 'plugin',
  13414. v: 'version',
  13415. w: 'watch'
  13416. };
  13417. function mergeOptions({ config = {}, command: rawCommandOptions = {}, defaultOnWarnHandler }) {
  13418. const command = getCommandOptions(rawCommandOptions);
  13419. const inputOptions = getInputOptions(config, command, defaultOnWarnHandler);
  13420. if (command.output) {
  13421. Object.assign(command, command.output);
  13422. }
  13423. const output = config.output;
  13424. const normalizedOutputOptions = Array.isArray(output) ? output : output ? [output] : [];
  13425. if (normalizedOutputOptions.length === 0)
  13426. normalizedOutputOptions.push({});
  13427. const outputOptions = normalizedOutputOptions.map(singleOutputOptions => getOutputOptions(singleOutputOptions, command));
  13428. const unknownOptionErrors = [];
  13429. const validInputOptions = Object.keys(inputOptions);
  13430. addUnknownOptionErrors(unknownOptionErrors, Object.keys(config), validInputOptions, 'input option', /^output$/);
  13431. const validOutputOptions = Object.keys(outputOptions[0]);
  13432. addUnknownOptionErrors(unknownOptionErrors, outputOptions.reduce((allKeys, options) => allKeys.concat(Object.keys(options)), []), validOutputOptions, 'output option');
  13433. const validCliOutputOptions = validOutputOptions.filter(option => option !== 'sourcemapPathTransform');
  13434. addUnknownOptionErrors(unknownOptionErrors, Object.keys(command), validInputOptions.concat(validCliOutputOptions, Object.keys(commandAliases), 'config', 'environment', 'plugin', 'silent', 'stdin'), 'CLI flag', /^_|output|(config.*)$/);
  13435. return {
  13436. inputOptions,
  13437. optionError: unknownOptionErrors.length > 0 ? unknownOptionErrors.join('\n') : null,
  13438. outputOptions
  13439. };
  13440. }
  13441. function addUnknownOptionErrors(errors, options, validOptions, optionType, ignoredKeys = /$./) {
  13442. const validOptionSet = new Set(validOptions);
  13443. const unknownOptions = options.filter(key => !validOptionSet.has(key) && !ignoredKeys.test(key));
  13444. if (unknownOptions.length > 0)
  13445. errors.push(`Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${Array.from(validOptionSet)
  13446. .sort()
  13447. .join(', ')}`);
  13448. }
  13449. function getCommandOptions(rawCommandOptions) {
  13450. const external = rawCommandOptions.external && typeof rawCommandOptions.external === 'string'
  13451. ? rawCommandOptions.external.split(',')
  13452. : [];
  13453. return Object.assign(Object.assign({}, rawCommandOptions), { external, globals: typeof rawCommandOptions.globals === 'string'
  13454. ? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => {
  13455. const [id, variableName] = globalDefinition.split(':');
  13456. globals[id] = variableName;
  13457. if (external.indexOf(id) === -1) {
  13458. external.push(id);
  13459. }
  13460. return globals;
  13461. }, Object.create(null))
  13462. : undefined });
  13463. }
  13464. function getInputOptions(config, command = { external: [], globals: undefined }, defaultOnWarnHandler) {
  13465. const getOption = createGetOption(config, command);
  13466. const inputOptions = {
  13467. acorn: config.acorn,
  13468. acornInjectPlugins: config.acornInjectPlugins,
  13469. cache: getOption('cache'),
  13470. chunkGroupingSize: getOption('chunkGroupingSize', 5000),
  13471. context: getOption('context'),
  13472. experimentalCacheExpiry: getOption('experimentalCacheExpiry', 10),
  13473. experimentalOptimizeChunks: getOption('experimentalOptimizeChunks'),
  13474. external: getExternal(config, command),
  13475. inlineDynamicImports: getOption('inlineDynamicImports', false),
  13476. input: getOption('input', []),
  13477. manualChunks: getOption('manualChunks'),
  13478. moduleContext: config.moduleContext,
  13479. onwarn: getOnWarn(config, defaultOnWarnHandler),
  13480. perf: getOption('perf', false),
  13481. plugins: ensureArray(config.plugins),
  13482. preserveModules: getOption('preserveModules'),
  13483. preserveSymlinks: getOption('preserveSymlinks'),
  13484. shimMissingExports: getOption('shimMissingExports'),
  13485. strictDeprecations: getOption('strictDeprecations', false),
  13486. treeshake: getObjectOption(config, command, 'treeshake'),
  13487. watch: config.watch
  13488. };
  13489. // support rollup({ cache: prevBuildObject })
  13490. if (inputOptions.cache && inputOptions.cache.cache)
  13491. inputOptions.cache = inputOptions.cache.cache;
  13492. return inputOptions;
  13493. }
  13494. function getOutputOptions(config, command = {}) {
  13495. const getOption = createGetOption(config, command);
  13496. let format = getOption('format');
  13497. // Handle format aliases
  13498. switch (format) {
  13499. case undefined:
  13500. case 'esm':
  13501. case 'module':
  13502. format = 'es';
  13503. break;
  13504. case 'commonjs':
  13505. format = 'cjs';
  13506. }
  13507. return {
  13508. amd: Object.assign(Object.assign({}, config.amd), command.amd),
  13509. assetFileNames: getOption('assetFileNames'),
  13510. banner: getOption('banner'),
  13511. chunkFileNames: getOption('chunkFileNames'),
  13512. compact: getOption('compact', false),
  13513. dir: getOption('dir'),
  13514. dynamicImportFunction: getOption('dynamicImportFunction'),
  13515. entryFileNames: getOption('entryFileNames'),
  13516. esModule: getOption('esModule', true),
  13517. exports: getOption('exports'),
  13518. extend: getOption('extend'),
  13519. externalLiveBindings: getOption('externalLiveBindings', true),
  13520. file: getOption('file'),
  13521. footer: getOption('footer'),
  13522. format,
  13523. freeze: getOption('freeze', true),
  13524. globals: getOption('globals'),
  13525. hoistTransitiveImports: getOption('hoistTransitiveImports', true),
  13526. indent: getOption('indent', true),
  13527. interop: getOption('interop', true),
  13528. intro: getOption('intro'),
  13529. name: getOption('name'),
  13530. namespaceToStringTag: getOption('namespaceToStringTag', false),
  13531. noConflict: getOption('noConflict'),
  13532. outro: getOption('outro'),
  13533. paths: getOption('paths'),
  13534. plugins: ensureArray(config.plugins),
  13535. preferConst: getOption('preferConst'),
  13536. sourcemap: getOption('sourcemap'),
  13537. sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
  13538. sourcemapFile: getOption('sourcemapFile'),
  13539. sourcemapPathTransform: getOption('sourcemapPathTransform'),
  13540. strict: getOption('strict', true)
  13541. };
  13542. }
  13543. function checkOutputOptions(options) {
  13544. if (options.format === 'es6') {
  13545. return error(errDeprecation({
  13546. message: 'The "es6" output format is deprecated – use "esm" instead',
  13547. url: `https://rollupjs.org/guide/en/#output-format`
  13548. }));
  13549. }
  13550. if (['amd', 'cjs', 'system', 'es', 'iife', 'umd'].indexOf(options.format) < 0) {
  13551. return error({
  13552. message: `You must specify "output.format", which can be one of "amd", "cjs", "system", "esm", "iife" or "umd".`,
  13553. url: `https://rollupjs.org/guide/en/#output-format`
  13554. });
  13555. }
  13556. if (options.exports && !['default', 'named', 'none', 'auto'].includes(options.exports)) {
  13557. return error(errInvalidExportOptionValue(options.exports));
  13558. }
  13559. }
  13560. function getAbsoluteEntryModulePaths(chunks) {
  13561. const absoluteEntryModulePaths = [];
  13562. for (const chunk of chunks) {
  13563. for (const entryModule of chunk.entryModules) {
  13564. if (isAbsolute(entryModule.id)) {
  13565. absoluteEntryModulePaths.push(entryModule.id);
  13566. }
  13567. }
  13568. }
  13569. return absoluteEntryModulePaths;
  13570. }
  13571. const throwAsyncGenerateError = {
  13572. get() {
  13573. throw new Error(`bundle.generate(...) now returns a Promise instead of a { code, map } object`);
  13574. }
  13575. };
  13576. function applyOptionHook(inputOptions, plugin) {
  13577. if (plugin.options)
  13578. return plugin.options.call({ meta: { rollupVersion: version } }, inputOptions) || inputOptions;
  13579. return inputOptions;
  13580. }
  13581. function normalizePlugins(rawPlugins, anonymousPrefix) {
  13582. const plugins = ensureArray(rawPlugins);
  13583. for (let pluginIndex = 0; pluginIndex < plugins.length; pluginIndex++) {
  13584. const plugin = plugins[pluginIndex];
  13585. if (!plugin.name) {
  13586. plugin.name = `${anonymousPrefix}${pluginIndex + 1}`;
  13587. }
  13588. }
  13589. return plugins;
  13590. }
  13591. function getInputOptions$1(rawInputOptions) {
  13592. if (!rawInputOptions) {
  13593. throw new Error('You must supply an options object to rollup');
  13594. }
  13595. let { inputOptions, optionError } = mergeOptions({
  13596. config: rawInputOptions
  13597. });
  13598. if (optionError)
  13599. inputOptions.onwarn({ message: optionError, code: 'UNKNOWN_OPTION' });
  13600. inputOptions = inputOptions.plugins.reduce(applyOptionHook, inputOptions);
  13601. inputOptions.plugins = normalizePlugins(inputOptions.plugins, ANONYMOUS_PLUGIN_PREFIX);
  13602. if (inputOptions.inlineDynamicImports) {
  13603. if (inputOptions.preserveModules)
  13604. return error({
  13605. code: 'INVALID_OPTION',
  13606. message: `"preserveModules" does not support the "inlineDynamicImports" option.`
  13607. });
  13608. if (inputOptions.manualChunks)
  13609. return error({
  13610. code: 'INVALID_OPTION',
  13611. message: '"manualChunks" option is not supported for "inlineDynamicImports".'
  13612. });
  13613. if (inputOptions.experimentalOptimizeChunks)
  13614. return error({
  13615. code: 'INVALID_OPTION',
  13616. message: '"experimentalOptimizeChunks" option is not supported for "inlineDynamicImports".'
  13617. });
  13618. if ((inputOptions.input instanceof Array && inputOptions.input.length > 1) ||
  13619. (typeof inputOptions.input === 'object' && Object.keys(inputOptions.input).length > 1))
  13620. return error({
  13621. code: 'INVALID_OPTION',
  13622. message: 'Multiple inputs are not supported for "inlineDynamicImports".'
  13623. });
  13624. }
  13625. else if (inputOptions.preserveModules) {
  13626. if (inputOptions.manualChunks)
  13627. return error({
  13628. code: 'INVALID_OPTION',
  13629. message: '"preserveModules" does not support the "manualChunks" option.'
  13630. });
  13631. if (inputOptions.experimentalOptimizeChunks)
  13632. return error({
  13633. code: 'INVALID_OPTION',
  13634. message: '"preserveModules" does not support the "experimentalOptimizeChunks" option.'
  13635. });
  13636. }
  13637. return inputOptions;
  13638. }
  13639. let curWatcher;
  13640. function setWatcher(watcher) {
  13641. curWatcher = watcher;
  13642. }
  13643. function assignChunksToBundle(chunks, outputBundle) {
  13644. for (let i = 0; i < chunks.length; i++) {
  13645. const chunk = chunks[i];
  13646. const facadeModule = chunk.facadeModule;
  13647. outputBundle[chunk.id] = {
  13648. code: undefined,
  13649. dynamicImports: chunk.getDynamicImportIds(),
  13650. exports: chunk.getExportNames(),
  13651. facadeModuleId: facadeModule && facadeModule.id,
  13652. fileName: chunk.id,
  13653. imports: chunk.getImportIds(),
  13654. isDynamicEntry: facadeModule !== null && facadeModule.dynamicallyImportedBy.length > 0,
  13655. isEntry: facadeModule !== null && facadeModule.isEntryPoint,
  13656. map: undefined,
  13657. modules: chunk.renderedModules,
  13658. get name() {
  13659. return chunk.getChunkName();
  13660. },
  13661. type: 'chunk'
  13662. };
  13663. }
  13664. return outputBundle;
  13665. }
  13666. function rollup(rawInputOptions) {
  13667. return __awaiter(this, void 0, void 0, function* () {
  13668. const inputOptions = getInputOptions$1(rawInputOptions);
  13669. initialiseTimers(inputOptions);
  13670. const graph = new Graph(inputOptions, curWatcher);
  13671. curWatcher = undefined;
  13672. // remove the cache option from the memory after graph creation (cache is not used anymore)
  13673. const useCache = rawInputOptions.cache !== false;
  13674. delete inputOptions.cache;
  13675. delete rawInputOptions.cache;
  13676. timeStart('BUILD', 1);
  13677. let chunks;
  13678. try {
  13679. yield graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
  13680. chunks = yield graph.build(inputOptions.input, inputOptions.manualChunks, inputOptions.inlineDynamicImports);
  13681. }
  13682. catch (err) {
  13683. const watchFiles = Object.keys(graph.watchFiles);
  13684. if (watchFiles.length > 0) {
  13685. err.watchFiles = watchFiles;
  13686. }
  13687. yield graph.pluginDriver.hookParallel('buildEnd', [err]);
  13688. throw err;
  13689. }
  13690. yield graph.pluginDriver.hookParallel('buildEnd', []);
  13691. timeEnd('BUILD', 1);
  13692. // ensure we only do one optimization pass per build
  13693. let optimized = false;
  13694. function getOutputOptionsAndPluginDriver(rawOutputOptions) {
  13695. if (!rawOutputOptions) {
  13696. throw new Error('You must supply an options object');
  13697. }
  13698. const outputPluginDriver = graph.pluginDriver.createOutputPluginDriver(normalizePlugins(rawOutputOptions.plugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX));
  13699. return {
  13700. outputOptions: normalizeOutputOptions(inputOptions, rawOutputOptions, chunks.length > 1, outputPluginDriver),
  13701. outputPluginDriver
  13702. };
  13703. }
  13704. function generate(outputOptions, isWrite, outputPluginDriver) {
  13705. return __awaiter(this, void 0, void 0, function* () {
  13706. timeStart('GENERATE', 1);
  13707. const assetFileNames = outputOptions.assetFileNames || 'assets/[name]-[hash][extname]';
  13708. const inputBase = commondir(getAbsoluteEntryModulePaths(chunks));
  13709. const outputBundleWithPlaceholders = Object.create(null);
  13710. outputPluginDriver.setOutputBundle(outputBundleWithPlaceholders, assetFileNames);
  13711. let outputBundle;
  13712. try {
  13713. yield outputPluginDriver.hookParallel('renderStart', [outputOptions, inputOptions]);
  13714. const addons = yield createAddons(outputOptions, outputPluginDriver);
  13715. for (const chunk of chunks) {
  13716. if (!inputOptions.preserveModules)
  13717. chunk.generateInternalExports(outputOptions);
  13718. if (inputOptions.preserveModules || (chunk.facadeModule && chunk.facadeModule.isEntryPoint))
  13719. chunk.exportMode = getExportMode(chunk, outputOptions, chunk.facadeModule.id);
  13720. }
  13721. for (const chunk of chunks) {
  13722. chunk.preRender(outputOptions, inputBase);
  13723. }
  13724. if (!optimized && inputOptions.experimentalOptimizeChunks) {
  13725. optimizeChunks(chunks, outputOptions, inputOptions.chunkGroupingSize, inputBase);
  13726. optimized = true;
  13727. }
  13728. assignChunkIds(chunks, inputOptions, outputOptions, inputBase, addons, outputBundleWithPlaceholders, outputPluginDriver);
  13729. outputBundle = assignChunksToBundle(chunks, outputBundleWithPlaceholders);
  13730. yield Promise.all(chunks.map(chunk => {
  13731. const outputChunk = outputBundleWithPlaceholders[chunk.id];
  13732. return chunk
  13733. .render(outputOptions, addons, outputChunk, outputPluginDriver)
  13734. .then(rendered => {
  13735. outputChunk.code = rendered.code;
  13736. outputChunk.map = rendered.map;
  13737. return outputPluginDriver.hookParallel('ongenerate', [
  13738. Object.assign({ bundle: outputChunk }, outputOptions),
  13739. outputChunk
  13740. ]);
  13741. });
  13742. }));
  13743. }
  13744. catch (error) {
  13745. yield outputPluginDriver.hookParallel('renderError', [error]);
  13746. throw error;
  13747. }
  13748. yield outputPluginDriver.hookSeq('generateBundle', [outputOptions, outputBundle, isWrite]);
  13749. for (const key of Object.keys(outputBundle)) {
  13750. const file = outputBundle[key];
  13751. if (!file.type) {
  13752. graph.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.', false);
  13753. file.type = 'asset';
  13754. }
  13755. }
  13756. outputPluginDriver.finaliseAssets();
  13757. timeEnd('GENERATE', 1);
  13758. return outputBundle;
  13759. });
  13760. }
  13761. const cache = useCache ? graph.getCache() : undefined;
  13762. const result = {
  13763. cache: cache,
  13764. generate: ((rawOutputOptions) => {
  13765. const { outputOptions, outputPluginDriver } = getOutputOptionsAndPluginDriver(rawOutputOptions);
  13766. const promise = generate(outputOptions, false, outputPluginDriver).then(result => createOutput(result));
  13767. Object.defineProperty(promise, 'code', throwAsyncGenerateError);
  13768. Object.defineProperty(promise, 'map', throwAsyncGenerateError);
  13769. return promise;
  13770. }),
  13771. watchFiles: Object.keys(graph.watchFiles),
  13772. write: ((rawOutputOptions) => {
  13773. const { outputOptions, outputPluginDriver } = getOutputOptionsAndPluginDriver(rawOutputOptions);
  13774. if (!outputOptions.dir && !outputOptions.file) {
  13775. return error({
  13776. code: 'MISSING_OPTION',
  13777. message: 'You must specify "output.file" or "output.dir" for the build.'
  13778. });
  13779. }
  13780. return generate(outputOptions, true, outputPluginDriver).then((bundle) => __awaiter(this, void 0, void 0, function* () {
  13781. let chunkCount = 0;
  13782. for (const fileName of Object.keys(bundle)) {
  13783. const file = bundle[fileName];
  13784. if (file.type === 'asset')
  13785. continue;
  13786. chunkCount++;
  13787. if (chunkCount > 1)
  13788. break;
  13789. }
  13790. if (chunkCount > 1) {
  13791. if (outputOptions.sourcemapFile)
  13792. return error({
  13793. code: 'INVALID_OPTION',
  13794. message: '"output.sourcemapFile" is only supported for single-file builds.'
  13795. });
  13796. if (typeof outputOptions.file === 'string')
  13797. return error({
  13798. code: 'INVALID_OPTION',
  13799. message: 'When building multiple chunks, the "output.dir" option must be used, not "output.file".' +
  13800. (typeof inputOptions.input !== 'string' ||
  13801. inputOptions.inlineDynamicImports === true
  13802. ? ''
  13803. : ' To inline dynamic imports, set the "inlineDynamicImports" option.')
  13804. });
  13805. }
  13806. yield Promise.all(Object.keys(bundle).map(chunkId => writeOutputFile(result, bundle[chunkId], outputOptions, outputPluginDriver)));
  13807. yield outputPluginDriver.hookParallel('writeBundle', [bundle]);
  13808. return createOutput(bundle);
  13809. }));
  13810. })
  13811. };
  13812. if (inputOptions.perf === true)
  13813. result.getTimings = getTimings;
  13814. return result;
  13815. });
  13816. }
  13817. var SortingFileType;
  13818. (function (SortingFileType) {
  13819. SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
  13820. SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
  13821. SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
  13822. })(SortingFileType || (SortingFileType = {}));
  13823. function getSortingFileType(file) {
  13824. if (file.type === 'asset') {
  13825. return SortingFileType.ASSET;
  13826. }
  13827. if (file.isEntry) {
  13828. return SortingFileType.ENTRY_CHUNK;
  13829. }
  13830. return SortingFileType.SECONDARY_CHUNK;
  13831. }
  13832. function createOutput(outputBundle) {
  13833. return {
  13834. output: Object.keys(outputBundle)
  13835. .map(fileName => outputBundle[fileName])
  13836. .filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => {
  13837. const fileTypeA = getSortingFileType(outputFileA);
  13838. const fileTypeB = getSortingFileType(outputFileB);
  13839. if (fileTypeA === fileTypeB)
  13840. return 0;
  13841. return fileTypeA < fileTypeB ? -1 : 1;
  13842. })
  13843. };
  13844. }
  13845. function writeOutputFile(build, outputFile, outputOptions, outputPluginDriver) {
  13846. const fileName = path.resolve(outputOptions.dir || path.dirname(outputOptions.file), outputFile.fileName);
  13847. let writeSourceMapPromise;
  13848. let source;
  13849. if (outputFile.type === 'asset') {
  13850. source = outputFile.source;
  13851. }
  13852. else {
  13853. source = outputFile.code;
  13854. if (outputOptions.sourcemap && outputFile.map) {
  13855. let url;
  13856. if (outputOptions.sourcemap === 'inline') {
  13857. url = outputFile.map.toUrl();
  13858. }
  13859. else {
  13860. url = `${path.basename(outputFile.fileName)}.map`;
  13861. writeSourceMapPromise = writeFile(`${fileName}.map`, outputFile.map.toString());
  13862. }
  13863. if (outputOptions.sourcemap !== 'hidden') {
  13864. source += `//# ${SOURCEMAPPING_URL}=${url}\n`;
  13865. }
  13866. }
  13867. }
  13868. return writeFile(fileName, source)
  13869. .then(() => writeSourceMapPromise)
  13870. .then(() => outputFile.type === 'chunk' &&
  13871. outputPluginDriver.hookSeq('onwrite', [
  13872. Object.assign({ bundle: build }, outputOptions),
  13873. outputFile
  13874. ]))
  13875. .then(() => { });
  13876. }
  13877. function normalizeOutputOptions(inputOptions, rawOutputOptions, hasMultipleChunks, outputPluginDriver) {
  13878. const mergedOptions = mergeOptions({
  13879. config: {
  13880. output: Object.assign(Object.assign(Object.assign({}, rawOutputOptions), rawOutputOptions.output), inputOptions.output)
  13881. }
  13882. });
  13883. if (mergedOptions.optionError)
  13884. throw new Error(mergedOptions.optionError);
  13885. // now outputOptions is an array, but rollup.rollup API doesn't support arrays
  13886. const mergedOutputOptions = mergedOptions.outputOptions[0];
  13887. const outputOptionsReducer = (outputOptions, result) => result || outputOptions;
  13888. const outputOptions = outputPluginDriver.hookReduceArg0Sync('outputOptions', [mergedOutputOptions], outputOptionsReducer, pluginContext => {
  13889. const emitError = () => pluginContext.error(errCannotEmitFromOptionsHook());
  13890. return Object.assign(Object.assign({}, pluginContext), { emitFile: emitError, setAssetSource: emitError });
  13891. });
  13892. checkOutputOptions(outputOptions);
  13893. if (typeof outputOptions.file === 'string') {
  13894. if (typeof outputOptions.dir === 'string')
  13895. return error({
  13896. code: 'INVALID_OPTION',
  13897. message: 'You must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks.'
  13898. });
  13899. if (inputOptions.preserveModules) {
  13900. return error({
  13901. code: 'INVALID_OPTION',
  13902. message: 'You must set "output.dir" instead of "output.file" when using the "preserveModules" option.'
  13903. });
  13904. }
  13905. if (typeof inputOptions.input === 'object' && !Array.isArray(inputOptions.input))
  13906. return error({
  13907. code: 'INVALID_OPTION',
  13908. message: 'You must set "output.dir" instead of "output.file" when providing named inputs.'
  13909. });
  13910. }
  13911. if (hasMultipleChunks) {
  13912. if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
  13913. return error({
  13914. code: 'INVALID_OPTION',
  13915. message: 'UMD and IIFE output formats are not supported for code-splitting builds.'
  13916. });
  13917. if (typeof outputOptions.file === 'string')
  13918. return error({
  13919. code: 'INVALID_OPTION',
  13920. message: 'You must set "output.dir" instead of "output.file" when generating multiple chunks.'
  13921. });
  13922. }
  13923. return outputOptions;
  13924. }
  13925. var utils$1 = createCommonjsModule(function (module, exports) {
  13926. exports.isInteger = num => {
  13927. if (typeof num === 'number') {
  13928. return Number.isInteger(num);
  13929. }
  13930. if (typeof num === 'string' && num.trim() !== '') {
  13931. return Number.isInteger(Number(num));
  13932. }
  13933. return false;
  13934. };
  13935. /**
  13936. * Find a node of the given type
  13937. */
  13938. exports.find = (node, type) => node.nodes.find(node => node.type === type);
  13939. /**
  13940. * Find a node of the given type
  13941. */
  13942. exports.exceedsLimit = (min, max, step = 1, limit) => {
  13943. if (limit === false)
  13944. return false;
  13945. if (!exports.isInteger(min) || !exports.isInteger(max))
  13946. return false;
  13947. return ((Number(max) - Number(min)) / Number(step)) >= limit;
  13948. };
  13949. /**
  13950. * Escape the given node with '\\' before node.value
  13951. */
  13952. exports.escapeNode = (block, n = 0, type) => {
  13953. let node = block.nodes[n];
  13954. if (!node)
  13955. return;
  13956. if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {
  13957. if (node.escaped !== true) {
  13958. node.value = '\\' + node.value;
  13959. node.escaped = true;
  13960. }
  13961. }
  13962. };
  13963. /**
  13964. * Returns true if the given brace node should be enclosed in literal braces
  13965. */
  13966. exports.encloseBrace = node => {
  13967. if (node.type !== 'brace')
  13968. return false;
  13969. if ((node.commas >> 0 + node.ranges >> 0) === 0) {
  13970. node.invalid = true;
  13971. return true;
  13972. }
  13973. return false;
  13974. };
  13975. /**
  13976. * Returns true if a brace node is invalid.
  13977. */
  13978. exports.isInvalidBrace = block => {
  13979. if (block.type !== 'brace')
  13980. return false;
  13981. if (block.invalid === true || block.dollar)
  13982. return true;
  13983. if ((block.commas >> 0 + block.ranges >> 0) === 0) {
  13984. block.invalid = true;
  13985. return true;
  13986. }
  13987. if (block.open !== true || block.close !== true) {
  13988. block.invalid = true;
  13989. return true;
  13990. }
  13991. return false;
  13992. };
  13993. /**
  13994. * Returns true if a node is an open or close node
  13995. */
  13996. exports.isOpenOrClose = node => {
  13997. if (node.type === 'open' || node.type === 'close') {
  13998. return true;
  13999. }
  14000. return node.open === true || node.close === true;
  14001. };
  14002. /**
  14003. * Reduce an array of text nodes.
  14004. */
  14005. exports.reduce = nodes => nodes.reduce((acc, node) => {
  14006. if (node.type === 'text')
  14007. acc.push(node.value);
  14008. if (node.type === 'range')
  14009. node.type = 'text';
  14010. return acc;
  14011. }, []);
  14012. /**
  14013. * Flatten an array
  14014. */
  14015. exports.flatten = (...args) => {
  14016. const result = [];
  14017. const flat = arr => {
  14018. for (let i = 0; i < arr.length; i++) {
  14019. let ele = arr[i];
  14020. Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);
  14021. }
  14022. return result;
  14023. };
  14024. flat(args);
  14025. return result;
  14026. };
  14027. });
  14028. var stringify = (ast, options = {}) => {
  14029. let stringify = (node, parent = {}) => {
  14030. let invalidBlock = options.escapeInvalid && utils$1.isInvalidBrace(parent);
  14031. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  14032. let output = '';
  14033. if (node.value) {
  14034. if ((invalidBlock || invalidNode) && utils$1.isOpenOrClose(node)) {
  14035. return '\\' + node.value;
  14036. }
  14037. return node.value;
  14038. }
  14039. if (node.value) {
  14040. return node.value;
  14041. }
  14042. if (node.nodes) {
  14043. for (let child of node.nodes) {
  14044. output += stringify(child);
  14045. }
  14046. }
  14047. return output;
  14048. };
  14049. return stringify(ast);
  14050. };
  14051. /*!
  14052. * is-number <https://github.com/jonschlinkert/is-number>
  14053. *
  14054. * Copyright (c) 2014-present, Jon Schlinkert.
  14055. * Released under the MIT License.
  14056. */
  14057. var isNumber = function (num) {
  14058. if (typeof num === 'number') {
  14059. return num - num === 0;
  14060. }
  14061. if (typeof num === 'string' && num.trim() !== '') {
  14062. return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
  14063. }
  14064. return false;
  14065. };
  14066. const toRegexRange = (min, max, options) => {
  14067. if (isNumber(min) === false) {
  14068. throw new TypeError('toRegexRange: expected the first argument to be a number');
  14069. }
  14070. if (max === void 0 || min === max) {
  14071. return String(min);
  14072. }
  14073. if (isNumber(max) === false) {
  14074. throw new TypeError('toRegexRange: expected the second argument to be a number.');
  14075. }
  14076. let opts = Object.assign({ relaxZeros: true }, options);
  14077. if (typeof opts.strictZeros === 'boolean') {
  14078. opts.relaxZeros = opts.strictZeros === false;
  14079. }
  14080. let relax = String(opts.relaxZeros);
  14081. let shorthand = String(opts.shorthand);
  14082. let capture = String(opts.capture);
  14083. let wrap = String(opts.wrap);
  14084. let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
  14085. if (toRegexRange.cache.hasOwnProperty(cacheKey)) {
  14086. return toRegexRange.cache[cacheKey].result;
  14087. }
  14088. let a = Math.min(min, max);
  14089. let b = Math.max(min, max);
  14090. if (Math.abs(a - b) === 1) {
  14091. let result = min + '|' + max;
  14092. if (opts.capture) {
  14093. return `(${result})`;
  14094. }
  14095. if (opts.wrap === false) {
  14096. return result;
  14097. }
  14098. return `(?:${result})`;
  14099. }
  14100. let isPadded = hasPadding(min) || hasPadding(max);
  14101. let state = { min, max, a, b };
  14102. let positives = [];
  14103. let negatives = [];
  14104. if (isPadded) {
  14105. state.isPadded = isPadded;
  14106. state.maxLen = String(state.max).length;
  14107. }
  14108. if (a < 0) {
  14109. let newMin = b < 0 ? Math.abs(b) : 1;
  14110. negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
  14111. a = state.a = 0;
  14112. }
  14113. if (b >= 0) {
  14114. positives = splitToPatterns(a, b, state, opts);
  14115. }
  14116. state.negatives = negatives;
  14117. state.positives = positives;
  14118. state.result = collatePatterns(negatives, positives);
  14119. if (opts.capture === true) {
  14120. state.result = `(${state.result})`;
  14121. }
  14122. else if (opts.wrap !== false && (positives.length + negatives.length) > 1) {
  14123. state.result = `(?:${state.result})`;
  14124. }
  14125. toRegexRange.cache[cacheKey] = state;
  14126. return state.result;
  14127. };
  14128. function collatePatterns(neg, pos, options) {
  14129. let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
  14130. let onlyPositive = filterPatterns(pos, neg, '', false) || [];
  14131. let intersected = filterPatterns(neg, pos, '-?', true) || [];
  14132. let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
  14133. return subpatterns.join('|');
  14134. }
  14135. function splitToRanges(min, max) {
  14136. let nines = 1;
  14137. let zeros = 1;
  14138. let stop = countNines(min, nines);
  14139. let stops = new Set([max]);
  14140. while (min <= stop && stop <= max) {
  14141. stops.add(stop);
  14142. nines += 1;
  14143. stop = countNines(min, nines);
  14144. }
  14145. stop = countZeros(max + 1, zeros) - 1;
  14146. while (min < stop && stop <= max) {
  14147. stops.add(stop);
  14148. zeros += 1;
  14149. stop = countZeros(max + 1, zeros) - 1;
  14150. }
  14151. stops = [...stops];
  14152. stops.sort(compare);
  14153. return stops;
  14154. }
  14155. /**
  14156. * Convert a range to a regex pattern
  14157. * @param {Number} `start`
  14158. * @param {Number} `stop`
  14159. * @return {String}
  14160. */
  14161. function rangeToPattern(start, stop, options) {
  14162. if (start === stop) {
  14163. return { pattern: start, count: [], digits: 0 };
  14164. }
  14165. let zipped = zip(start, stop);
  14166. let digits = zipped.length;
  14167. let pattern = '';
  14168. let count = 0;
  14169. for (let i = 0; i < digits; i++) {
  14170. let [startDigit, stopDigit] = zipped[i];
  14171. if (startDigit === stopDigit) {
  14172. pattern += startDigit;
  14173. }
  14174. else if (startDigit !== '0' || stopDigit !== '9') {
  14175. pattern += toCharacterClass(startDigit, stopDigit);
  14176. }
  14177. else {
  14178. count++;
  14179. }
  14180. }
  14181. if (count) {
  14182. pattern += options.shorthand === true ? '\\d' : '[0-9]';
  14183. }
  14184. return { pattern, count: [count], digits };
  14185. }
  14186. function splitToPatterns(min, max, tok, options) {
  14187. let ranges = splitToRanges(min, max);
  14188. let tokens = [];
  14189. let start = min;
  14190. let prev;
  14191. for (let i = 0; i < ranges.length; i++) {
  14192. let max = ranges[i];
  14193. let obj = rangeToPattern(String(start), String(max), options);
  14194. let zeros = '';
  14195. if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
  14196. if (prev.count.length > 1) {
  14197. prev.count.pop();
  14198. }
  14199. prev.count.push(obj.count[0]);
  14200. prev.string = prev.pattern + toQuantifier(prev.count);
  14201. start = max + 1;
  14202. continue;
  14203. }
  14204. if (tok.isPadded) {
  14205. zeros = padZeros(max, tok, options);
  14206. }
  14207. obj.string = zeros + obj.pattern + toQuantifier(obj.count);
  14208. tokens.push(obj);
  14209. start = max + 1;
  14210. prev = obj;
  14211. }
  14212. return tokens;
  14213. }
  14214. function filterPatterns(arr, comparison, prefix, intersection, options) {
  14215. let result = [];
  14216. for (let ele of arr) {
  14217. let { string } = ele;
  14218. // only push if _both_ are negative...
  14219. if (!intersection && !contains(comparison, 'string', string)) {
  14220. result.push(prefix + string);
  14221. }
  14222. // or _both_ are positive
  14223. if (intersection && contains(comparison, 'string', string)) {
  14224. result.push(prefix + string);
  14225. }
  14226. }
  14227. return result;
  14228. }
  14229. /**
  14230. * Zip strings
  14231. */
  14232. function zip(a, b) {
  14233. let arr = [];
  14234. for (let i = 0; i < a.length; i++)
  14235. arr.push([a[i], b[i]]);
  14236. return arr;
  14237. }
  14238. function compare(a, b) {
  14239. return a > b ? 1 : b > a ? -1 : 0;
  14240. }
  14241. function contains(arr, key, val) {
  14242. return arr.some(ele => ele[key] === val);
  14243. }
  14244. function countNines(min, len) {
  14245. return Number(String(min).slice(0, -len) + '9'.repeat(len));
  14246. }
  14247. function countZeros(integer, zeros) {
  14248. return integer - (integer % Math.pow(10, zeros));
  14249. }
  14250. function toQuantifier(digits) {
  14251. let [start = 0, stop = ''] = digits;
  14252. if (stop || start > 1) {
  14253. return `{${start + (stop ? ',' + stop : '')}}`;
  14254. }
  14255. return '';
  14256. }
  14257. function toCharacterClass(a, b, options) {
  14258. return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;
  14259. }
  14260. function hasPadding(str) {
  14261. return /^-?(0+)\d/.test(str);
  14262. }
  14263. function padZeros(value, tok, options) {
  14264. if (!tok.isPadded) {
  14265. return value;
  14266. }
  14267. let diff = Math.abs(tok.maxLen - String(value).length);
  14268. let relax = options.relaxZeros !== false;
  14269. switch (diff) {
  14270. case 0:
  14271. return '';
  14272. case 1:
  14273. return relax ? '0?' : '0';
  14274. case 2:
  14275. return relax ? '0{0,2}' : '00';
  14276. default: {
  14277. return relax ? `0{0,${diff}}` : `0{${diff}}`;
  14278. }
  14279. }
  14280. }
  14281. /**
  14282. * Cache
  14283. */
  14284. toRegexRange.cache = {};
  14285. toRegexRange.clearCache = () => (toRegexRange.cache = {});
  14286. /**
  14287. * Expose `toRegexRange`
  14288. */
  14289. var toRegexRange_1 = toRegexRange;
  14290. const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  14291. const transform$1 = toNumber => {
  14292. return value => toNumber === true ? Number(value) : String(value);
  14293. };
  14294. const isValidValue = value => {
  14295. return typeof value === 'number' || (typeof value === 'string' && value !== '');
  14296. };
  14297. const isNumber$1 = num => Number.isInteger(+num);
  14298. const zeros = input => {
  14299. let value = `${input}`;
  14300. let index = -1;
  14301. if (value[0] === '-')
  14302. value = value.slice(1);
  14303. if (value === '0')
  14304. return false;
  14305. while (value[++index] === '0')
  14306. ;
  14307. return index > 0;
  14308. };
  14309. const stringify$1 = (start, end, options) => {
  14310. if (typeof start === 'string' || typeof end === 'string') {
  14311. return true;
  14312. }
  14313. return options.stringify === true;
  14314. };
  14315. const pad = (input, maxLength, toNumber) => {
  14316. if (maxLength > 0) {
  14317. let dash = input[0] === '-' ? '-' : '';
  14318. if (dash)
  14319. input = input.slice(1);
  14320. input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));
  14321. }
  14322. if (toNumber === false) {
  14323. return String(input);
  14324. }
  14325. return input;
  14326. };
  14327. const toMaxLen = (input, maxLength) => {
  14328. let negative = input[0] === '-' ? '-' : '';
  14329. if (negative) {
  14330. input = input.slice(1);
  14331. maxLength--;
  14332. }
  14333. while (input.length < maxLength)
  14334. input = '0' + input;
  14335. return negative ? ('-' + input) : input;
  14336. };
  14337. const toSequence = (parts, options) => {
  14338. parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  14339. parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  14340. let prefix = options.capture ? '' : '?:';
  14341. let positives = '';
  14342. let negatives = '';
  14343. let result;
  14344. if (parts.positives.length) {
  14345. positives = parts.positives.join('|');
  14346. }
  14347. if (parts.negatives.length) {
  14348. negatives = `-(${prefix}${parts.negatives.join('|')})`;
  14349. }
  14350. if (positives && negatives) {
  14351. result = `${positives}|${negatives}`;
  14352. }
  14353. else {
  14354. result = positives || negatives;
  14355. }
  14356. if (options.wrap) {
  14357. return `(${prefix}${result})`;
  14358. }
  14359. return result;
  14360. };
  14361. const toRange = (a, b, isNumbers, options) => {
  14362. if (isNumbers) {
  14363. return toRegexRange_1(a, b, Object.assign({ wrap: false }, options));
  14364. }
  14365. let start = String.fromCharCode(a);
  14366. if (a === b)
  14367. return start;
  14368. let stop = String.fromCharCode(b);
  14369. return `[${start}-${stop}]`;
  14370. };
  14371. const toRegex = (start, end, options) => {
  14372. if (Array.isArray(start)) {
  14373. let wrap = options.wrap === true;
  14374. let prefix = options.capture ? '' : '?:';
  14375. return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
  14376. }
  14377. return toRegexRange_1(start, end, options);
  14378. };
  14379. const rangeError = (...args) => {
  14380. return new RangeError('Invalid range arguments: ' + util.inspect(...args));
  14381. };
  14382. const invalidRange = (start, end, options) => {
  14383. if (options.strictRanges === true)
  14384. throw rangeError([start, end]);
  14385. return [];
  14386. };
  14387. const invalidStep = (step, options) => {
  14388. if (options.strictRanges === true) {
  14389. throw new TypeError(`Expected step "${step}" to be a number`);
  14390. }
  14391. return [];
  14392. };
  14393. const fillNumbers = (start, end, step = 1, options = {}) => {
  14394. let a = Number(start);
  14395. let b = Number(end);
  14396. if (!Number.isInteger(a) || !Number.isInteger(b)) {
  14397. if (options.strictRanges === true)
  14398. throw rangeError([start, end]);
  14399. return [];
  14400. }
  14401. // fix negative zero
  14402. if (a === 0)
  14403. a = 0;
  14404. if (b === 0)
  14405. b = 0;
  14406. let descending = a > b;
  14407. let startString = String(start);
  14408. let endString = String(end);
  14409. let stepString = String(step);
  14410. step = Math.max(Math.abs(step), 1);
  14411. let padded = zeros(startString) || zeros(endString) || zeros(stepString);
  14412. let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
  14413. let toNumber = padded === false && stringify$1(start, end, options) === false;
  14414. let format = options.transform || transform$1(toNumber);
  14415. if (options.toRegex && step === 1) {
  14416. return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
  14417. }
  14418. let parts = { negatives: [], positives: [] };
  14419. let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
  14420. let range = [];
  14421. let index = 0;
  14422. while (descending ? a >= b : a <= b) {
  14423. if (options.toRegex === true && step > 1) {
  14424. push(a);
  14425. }
  14426. else {
  14427. range.push(pad(format(a, index), maxLen, toNumber));
  14428. }
  14429. a = descending ? a - step : a + step;
  14430. index++;
  14431. }
  14432. if (options.toRegex === true) {
  14433. return step > 1
  14434. ? toSequence(parts, options)
  14435. : toRegex(range, null, Object.assign({ wrap: false }, options));
  14436. }
  14437. return range;
  14438. };
  14439. const fillLetters = (start, end, step = 1, options = {}) => {
  14440. if ((!isNumber$1(start) && start.length > 1) || (!isNumber$1(end) && end.length > 1)) {
  14441. return invalidRange(start, end, options);
  14442. }
  14443. let format = options.transform || (val => String.fromCharCode(val));
  14444. let a = `${start}`.charCodeAt(0);
  14445. let b = `${end}`.charCodeAt(0);
  14446. let descending = a > b;
  14447. let min = Math.min(a, b);
  14448. let max = Math.max(a, b);
  14449. if (options.toRegex && step === 1) {
  14450. return toRange(min, max, false, options);
  14451. }
  14452. let range = [];
  14453. let index = 0;
  14454. while (descending ? a >= b : a <= b) {
  14455. range.push(format(a, index));
  14456. a = descending ? a - step : a + step;
  14457. index++;
  14458. }
  14459. if (options.toRegex === true) {
  14460. return toRegex(range, null, { wrap: false, options });
  14461. }
  14462. return range;
  14463. };
  14464. const fill = (start, end, step, options = {}) => {
  14465. if (end == null && isValidValue(start)) {
  14466. return [start];
  14467. }
  14468. if (!isValidValue(start) || !isValidValue(end)) {
  14469. return invalidRange(start, end, options);
  14470. }
  14471. if (typeof step === 'function') {
  14472. return fill(start, end, 1, { transform: step });
  14473. }
  14474. if (isObject$1(step)) {
  14475. return fill(start, end, 0, step);
  14476. }
  14477. let opts = Object.assign({}, options);
  14478. if (opts.capture === true)
  14479. opts.wrap = true;
  14480. step = step || opts.step || 1;
  14481. if (!isNumber$1(step)) {
  14482. if (step != null && !isObject$1(step))
  14483. return invalidStep(step, opts);
  14484. return fill(start, end, 1, step);
  14485. }
  14486. if (isNumber$1(start) && isNumber$1(end)) {
  14487. return fillNumbers(start, end, step, opts);
  14488. }
  14489. return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
  14490. };
  14491. var fillRange = fill;
  14492. const compile = (ast, options = {}) => {
  14493. let walk = (node, parent = {}) => {
  14494. let invalidBlock = utils$1.isInvalidBrace(parent);
  14495. let invalidNode = node.invalid === true && options.escapeInvalid === true;
  14496. let invalid = invalidBlock === true || invalidNode === true;
  14497. let prefix = options.escapeInvalid === true ? '\\' : '';
  14498. let output = '';
  14499. if (node.isOpen === true) {
  14500. return prefix + node.value;
  14501. }
  14502. if (node.isClose === true) {
  14503. return prefix + node.value;
  14504. }
  14505. if (node.type === 'open') {
  14506. return invalid ? (prefix + node.value) : '(';
  14507. }
  14508. if (node.type === 'close') {
  14509. return invalid ? (prefix + node.value) : ')';
  14510. }
  14511. if (node.type === 'comma') {
  14512. return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|');
  14513. }
  14514. if (node.value) {
  14515. return node.value;
  14516. }
  14517. if (node.nodes && node.ranges > 0) {
  14518. let args = utils$1.reduce(node.nodes);
  14519. let range = fillRange(...args, Object.assign(Object.assign({}, options), { wrap: false, toRegex: true }));
  14520. if (range.length !== 0) {
  14521. return args.length > 1 && range.length > 1 ? `(${range})` : range;
  14522. }
  14523. }
  14524. if (node.nodes) {
  14525. for (let child of node.nodes) {
  14526. output += walk(child, node);
  14527. }
  14528. }
  14529. return output;
  14530. };
  14531. return walk(ast);
  14532. };
  14533. var compile_1 = compile;
  14534. const append = (queue = '', stash = '', enclose = false) => {
  14535. let result = [];
  14536. queue = [].concat(queue);
  14537. stash = [].concat(stash);
  14538. if (!stash.length)
  14539. return queue;
  14540. if (!queue.length) {
  14541. return enclose ? utils$1.flatten(stash).map(ele => `{${ele}}`) : stash;
  14542. }
  14543. for (let item of queue) {
  14544. if (Array.isArray(item)) {
  14545. for (let value of item) {
  14546. result.push(append(value, stash, enclose));
  14547. }
  14548. }
  14549. else {
  14550. for (let ele of stash) {
  14551. if (enclose === true && typeof ele === 'string')
  14552. ele = `{${ele}}`;
  14553. result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele));
  14554. }
  14555. }
  14556. }
  14557. return utils$1.flatten(result);
  14558. };
  14559. const expand = (ast, options = {}) => {
  14560. let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
  14561. let walk = (node, parent = {}) => {
  14562. node.queue = [];
  14563. let p = parent;
  14564. let q = parent.queue;
  14565. while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
  14566. p = p.parent;
  14567. q = p.queue;
  14568. }
  14569. if (node.invalid || node.dollar) {
  14570. q.push(append(q.pop(), stringify(node, options)));
  14571. return;
  14572. }
  14573. if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
  14574. q.push(append(q.pop(), ['{}']));
  14575. return;
  14576. }
  14577. if (node.nodes && node.ranges > 0) {
  14578. let args = utils$1.reduce(node.nodes);
  14579. if (utils$1.exceedsLimit(...args, options.step, rangeLimit)) {
  14580. throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
  14581. }
  14582. let range = fillRange(...args, options);
  14583. if (range.length === 0) {
  14584. range = stringify(node, options);
  14585. }
  14586. q.push(append(q.pop(), range));
  14587. node.nodes = [];
  14588. return;
  14589. }
  14590. let enclose = utils$1.encloseBrace(node);
  14591. let queue = node.queue;
  14592. let block = node;
  14593. while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
  14594. block = block.parent;
  14595. queue = block.queue;
  14596. }
  14597. for (let i = 0; i < node.nodes.length; i++) {
  14598. let child = node.nodes[i];
  14599. if (child.type === 'comma' && node.type === 'brace') {
  14600. if (i === 1)
  14601. queue.push('');
  14602. queue.push('');
  14603. continue;
  14604. }
  14605. if (child.type === 'close') {
  14606. q.push(append(q.pop(), queue, enclose));
  14607. continue;
  14608. }
  14609. if (child.value && child.type !== 'open') {
  14610. queue.push(append(queue.pop(), child.value));
  14611. continue;
  14612. }
  14613. if (child.nodes) {
  14614. walk(child, node);
  14615. }
  14616. }
  14617. return queue;
  14618. };
  14619. return utils$1.flatten(walk(ast));
  14620. };
  14621. var expand_1 = expand;
  14622. var constants = {
  14623. MAX_LENGTH: 1024 * 64,
  14624. // Digits
  14625. CHAR_0: '0',
  14626. CHAR_9: '9',
  14627. // Alphabet chars.
  14628. CHAR_UPPERCASE_A: 'A',
  14629. CHAR_LOWERCASE_A: 'a',
  14630. CHAR_UPPERCASE_Z: 'Z',
  14631. CHAR_LOWERCASE_Z: 'z',
  14632. CHAR_LEFT_PARENTHESES: '(',
  14633. CHAR_RIGHT_PARENTHESES: ')',
  14634. CHAR_ASTERISK: '*',
  14635. // Non-alphabetic chars.
  14636. CHAR_AMPERSAND: '&',
  14637. CHAR_AT: '@',
  14638. CHAR_BACKSLASH: '\\',
  14639. CHAR_BACKTICK: '`',
  14640. CHAR_CARRIAGE_RETURN: '\r',
  14641. CHAR_CIRCUMFLEX_ACCENT: '^',
  14642. CHAR_COLON: ':',
  14643. CHAR_COMMA: ',',
  14644. CHAR_DOLLAR: '$',
  14645. CHAR_DOT: '.',
  14646. CHAR_DOUBLE_QUOTE: '"',
  14647. CHAR_EQUAL: '=',
  14648. CHAR_EXCLAMATION_MARK: '!',
  14649. CHAR_FORM_FEED: '\f',
  14650. CHAR_FORWARD_SLASH: '/',
  14651. CHAR_HASH: '#',
  14652. CHAR_HYPHEN_MINUS: '-',
  14653. CHAR_LEFT_ANGLE_BRACKET: '<',
  14654. CHAR_LEFT_CURLY_BRACE: '{',
  14655. CHAR_LEFT_SQUARE_BRACKET: '[',
  14656. CHAR_LINE_FEED: '\n',
  14657. CHAR_NO_BREAK_SPACE: '\u00A0',
  14658. CHAR_PERCENT: '%',
  14659. CHAR_PLUS: '+',
  14660. CHAR_QUESTION_MARK: '?',
  14661. CHAR_RIGHT_ANGLE_BRACKET: '>',
  14662. CHAR_RIGHT_CURLY_BRACE: '}',
  14663. CHAR_RIGHT_SQUARE_BRACKET: ']',
  14664. CHAR_SEMICOLON: ';',
  14665. CHAR_SINGLE_QUOTE: '\'',
  14666. CHAR_SPACE: ' ',
  14667. CHAR_TAB: '\t',
  14668. CHAR_UNDERSCORE: '_',
  14669. CHAR_VERTICAL_LINE: '|',
  14670. CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */
  14671. };
  14672. /**
  14673. * Constants
  14674. */
  14675. const { MAX_LENGTH, CHAR_BACKSLASH, /* \ */ CHAR_BACKTICK, /* ` */ CHAR_COMMA, /* , */ CHAR_DOT, /* . */ CHAR_LEFT_PARENTHESES, /* ( */ CHAR_RIGHT_PARENTHESES, /* ) */ CHAR_LEFT_CURLY_BRACE, /* { */ CHAR_RIGHT_CURLY_BRACE, /* } */ CHAR_LEFT_SQUARE_BRACKET, /* [ */ CHAR_RIGHT_SQUARE_BRACKET, /* ] */ CHAR_DOUBLE_QUOTE, /* " */ CHAR_SINGLE_QUOTE, /* ' */ CHAR_NO_BREAK_SPACE, CHAR_ZERO_WIDTH_NOBREAK_SPACE } = constants;
  14676. /**
  14677. * parse
  14678. */
  14679. const parse = (input, options = {}) => {
  14680. if (typeof input !== 'string') {
  14681. throw new TypeError('Expected a string');
  14682. }
  14683. let opts = options || {};
  14684. let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  14685. if (input.length > max) {
  14686. throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
  14687. }
  14688. let ast = { type: 'root', input, nodes: [] };
  14689. let stack = [ast];
  14690. let block = ast;
  14691. let prev = ast;
  14692. let brackets = 0;
  14693. let length = input.length;
  14694. let index = 0;
  14695. let depth = 0;
  14696. let value;
  14697. /**
  14698. * Helpers
  14699. */
  14700. const advance = () => input[index++];
  14701. const push = node => {
  14702. if (node.type === 'text' && prev.type === 'dot') {
  14703. prev.type = 'text';
  14704. }
  14705. if (prev && prev.type === 'text' && node.type === 'text') {
  14706. prev.value += node.value;
  14707. return;
  14708. }
  14709. block.nodes.push(node);
  14710. node.parent = block;
  14711. node.prev = prev;
  14712. prev = node;
  14713. return node;
  14714. };
  14715. push({ type: 'bos' });
  14716. while (index < length) {
  14717. block = stack[stack.length - 1];
  14718. value = advance();
  14719. /**
  14720. * Invalid chars
  14721. */
  14722. if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
  14723. continue;
  14724. }
  14725. /**
  14726. * Escaped chars
  14727. */
  14728. if (value === CHAR_BACKSLASH) {
  14729. push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });
  14730. continue;
  14731. }
  14732. /**
  14733. * Right square bracket (literal): ']'
  14734. */
  14735. if (value === CHAR_RIGHT_SQUARE_BRACKET) {
  14736. push({ type: 'text', value: '\\' + value });
  14737. continue;
  14738. }
  14739. /**
  14740. * Left square bracket: '['
  14741. */
  14742. if (value === CHAR_LEFT_SQUARE_BRACKET) {
  14743. brackets++;
  14744. let next;
  14745. while (index < length && (next = advance())) {
  14746. value += next;
  14747. if (next === CHAR_LEFT_SQUARE_BRACKET) {
  14748. brackets++;
  14749. continue;
  14750. }
  14751. if (next === CHAR_BACKSLASH) {
  14752. value += advance();
  14753. continue;
  14754. }
  14755. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  14756. brackets--;
  14757. if (brackets === 0) {
  14758. break;
  14759. }
  14760. }
  14761. }
  14762. push({ type: 'text', value });
  14763. continue;
  14764. }
  14765. /**
  14766. * Parentheses
  14767. */
  14768. if (value === CHAR_LEFT_PARENTHESES) {
  14769. block = push({ type: 'paren', nodes: [] });
  14770. stack.push(block);
  14771. push({ type: 'text', value });
  14772. continue;
  14773. }
  14774. if (value === CHAR_RIGHT_PARENTHESES) {
  14775. if (block.type !== 'paren') {
  14776. push({ type: 'text', value });
  14777. continue;
  14778. }
  14779. block = stack.pop();
  14780. push({ type: 'text', value });
  14781. block = stack[stack.length - 1];
  14782. continue;
  14783. }
  14784. /**
  14785. * Quotes: '|"|`
  14786. */
  14787. if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
  14788. let open = value;
  14789. let next;
  14790. if (options.keepQuotes !== true) {
  14791. value = '';
  14792. }
  14793. while (index < length && (next = advance())) {
  14794. if (next === CHAR_BACKSLASH) {
  14795. value += next + advance();
  14796. continue;
  14797. }
  14798. if (next === open) {
  14799. if (options.keepQuotes === true)
  14800. value += next;
  14801. break;
  14802. }
  14803. value += next;
  14804. }
  14805. push({ type: 'text', value });
  14806. continue;
  14807. }
  14808. /**
  14809. * Left curly brace: '{'
  14810. */
  14811. if (value === CHAR_LEFT_CURLY_BRACE) {
  14812. depth++;
  14813. let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
  14814. let brace = {
  14815. type: 'brace',
  14816. open: true,
  14817. close: false,
  14818. dollar,
  14819. depth,
  14820. commas: 0,
  14821. ranges: 0,
  14822. nodes: []
  14823. };
  14824. block = push(brace);
  14825. stack.push(block);
  14826. push({ type: 'open', value });
  14827. continue;
  14828. }
  14829. /**
  14830. * Right curly brace: '}'
  14831. */
  14832. if (value === CHAR_RIGHT_CURLY_BRACE) {
  14833. if (block.type !== 'brace') {
  14834. push({ type: 'text', value });
  14835. continue;
  14836. }
  14837. let type = 'close';
  14838. block = stack.pop();
  14839. block.close = true;
  14840. push({ type, value });
  14841. depth--;
  14842. block = stack[stack.length - 1];
  14843. continue;
  14844. }
  14845. /**
  14846. * Comma: ','
  14847. */
  14848. if (value === CHAR_COMMA && depth > 0) {
  14849. if (block.ranges > 0) {
  14850. block.ranges = 0;
  14851. let open = block.nodes.shift();
  14852. block.nodes = [open, { type: 'text', value: stringify(block) }];
  14853. }
  14854. push({ type: 'comma', value });
  14855. block.commas++;
  14856. continue;
  14857. }
  14858. /**
  14859. * Dot: '.'
  14860. */
  14861. if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
  14862. let siblings = block.nodes;
  14863. if (depth === 0 || siblings.length === 0) {
  14864. push({ type: 'text', value });
  14865. continue;
  14866. }
  14867. if (prev.type === 'dot') {
  14868. block.range = [];
  14869. prev.value += value;
  14870. prev.type = 'range';
  14871. if (block.nodes.length !== 3 && block.nodes.length !== 5) {
  14872. block.invalid = true;
  14873. block.ranges = 0;
  14874. prev.type = 'text';
  14875. continue;
  14876. }
  14877. block.ranges++;
  14878. block.args = [];
  14879. continue;
  14880. }
  14881. if (prev.type === 'range') {
  14882. siblings.pop();
  14883. let before = siblings[siblings.length - 1];
  14884. before.value += prev.value + value;
  14885. prev = before;
  14886. block.ranges--;
  14887. continue;
  14888. }
  14889. push({ type: 'dot', value });
  14890. continue;
  14891. }
  14892. /**
  14893. * Text
  14894. */
  14895. push({ type: 'text', value });
  14896. }
  14897. // Mark imbalanced braces and brackets as invalid
  14898. do {
  14899. block = stack.pop();
  14900. if (block.type !== 'root') {
  14901. block.nodes.forEach(node => {
  14902. if (!node.nodes) {
  14903. if (node.type === 'open')
  14904. node.isOpen = true;
  14905. if (node.type === 'close')
  14906. node.isClose = true;
  14907. if (!node.nodes)
  14908. node.type = 'text';
  14909. node.invalid = true;
  14910. }
  14911. });
  14912. // get the location of the block on parent.nodes (block's siblings)
  14913. let parent = stack[stack.length - 1];
  14914. let index = parent.nodes.indexOf(block);
  14915. // replace the (invalid) block with it's nodes
  14916. parent.nodes.splice(index, 1, ...block.nodes);
  14917. }
  14918. } while (stack.length > 0);
  14919. push({ type: 'eos' });
  14920. return ast;
  14921. };
  14922. var parse_1 = parse;
  14923. /**
  14924. * Expand the given pattern or create a regex-compatible string.
  14925. *
  14926. * ```js
  14927. * const braces = require('braces');
  14928. * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
  14929. * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
  14930. * ```
  14931. * @param {String} `str`
  14932. * @param {Object} `options`
  14933. * @return {String}
  14934. * @api public
  14935. */
  14936. const braces = (input, options = {}) => {
  14937. let output = [];
  14938. if (Array.isArray(input)) {
  14939. for (let pattern of input) {
  14940. let result = braces.create(pattern, options);
  14941. if (Array.isArray(result)) {
  14942. output.push(...result);
  14943. }
  14944. else {
  14945. output.push(result);
  14946. }
  14947. }
  14948. }
  14949. else {
  14950. output = [].concat(braces.create(input, options));
  14951. }
  14952. if (options && options.expand === true && options.nodupes === true) {
  14953. output = [...new Set(output)];
  14954. }
  14955. return output;
  14956. };
  14957. /**
  14958. * Parse the given `str` with the given `options`.
  14959. *
  14960. * ```js
  14961. * // braces.parse(pattern, [, options]);
  14962. * const ast = braces.parse('a/{b,c}/d');
  14963. * console.log(ast);
  14964. * ```
  14965. * @param {String} pattern Brace pattern to parse
  14966. * @param {Object} options
  14967. * @return {Object} Returns an AST
  14968. * @api public
  14969. */
  14970. braces.parse = (input, options = {}) => parse_1(input, options);
  14971. /**
  14972. * Creates a braces string from an AST, or an AST node.
  14973. *
  14974. * ```js
  14975. * const braces = require('braces');
  14976. * let ast = braces.parse('foo/{a,b}/bar');
  14977. * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
  14978. * ```
  14979. * @param {String} `input` Brace pattern or AST.
  14980. * @param {Object} `options`
  14981. * @return {Array} Returns an array of expanded values.
  14982. * @api public
  14983. */
  14984. braces.stringify = (input, options = {}) => {
  14985. if (typeof input === 'string') {
  14986. return stringify(braces.parse(input, options), options);
  14987. }
  14988. return stringify(input, options);
  14989. };
  14990. /**
  14991. * Compiles a brace pattern into a regex-compatible, optimized string.
  14992. * This method is called by the main [braces](#braces) function by default.
  14993. *
  14994. * ```js
  14995. * const braces = require('braces');
  14996. * console.log(braces.compile('a/{b,c}/d'));
  14997. * //=> ['a/(b|c)/d']
  14998. * ```
  14999. * @param {String} `input` Brace pattern or AST.
  15000. * @param {Object} `options`
  15001. * @return {Array} Returns an array of expanded values.
  15002. * @api public
  15003. */
  15004. braces.compile = (input, options = {}) => {
  15005. if (typeof input === 'string') {
  15006. input = braces.parse(input, options);
  15007. }
  15008. return compile_1(input, options);
  15009. };
  15010. /**
  15011. * Expands a brace pattern into an array. This method is called by the
  15012. * main [braces](#braces) function when `options.expand` is true. Before
  15013. * using this method it's recommended that you read the [performance notes](#performance))
  15014. * and advantages of using [.compile](#compile) instead.
  15015. *
  15016. * ```js
  15017. * const braces = require('braces');
  15018. * console.log(braces.expand('a/{b,c}/d'));
  15019. * //=> ['a/b/d', 'a/c/d'];
  15020. * ```
  15021. * @param {String} `pattern` Brace pattern
  15022. * @param {Object} `options`
  15023. * @return {Array} Returns an array of expanded values.
  15024. * @api public
  15025. */
  15026. braces.expand = (input, options = {}) => {
  15027. if (typeof input === 'string') {
  15028. input = braces.parse(input, options);
  15029. }
  15030. let result = expand_1(input, options);
  15031. // filter out empty strings if specified
  15032. if (options.noempty === true) {
  15033. result = result.filter(Boolean);
  15034. }
  15035. // filter out duplicates if specified
  15036. if (options.nodupes === true) {
  15037. result = [...new Set(result)];
  15038. }
  15039. return result;
  15040. };
  15041. /**
  15042. * Processes a brace pattern and returns either an expanded array
  15043. * (if `options.expand` is true), a highly optimized regex-compatible string.
  15044. * This method is called by the main [braces](#braces) function.
  15045. *
  15046. * ```js
  15047. * const braces = require('braces');
  15048. * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
  15049. * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
  15050. * ```
  15051. * @param {String} `pattern` Brace pattern
  15052. * @param {Object} `options`
  15053. * @return {Array} Returns an array of expanded values.
  15054. * @api public
  15055. */
  15056. braces.create = (input, options = {}) => {
  15057. if (input === '' || input.length < 3) {
  15058. return [input];
  15059. }
  15060. return options.expand !== true
  15061. ? braces.compile(input, options)
  15062. : braces.expand(input, options);
  15063. };
  15064. /**
  15065. * Expose "braces"
  15066. */
  15067. var braces_1 = braces;
  15068. const WIN_SLASH = '\\\\/';
  15069. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  15070. /**
  15071. * Posix glob regex
  15072. */
  15073. const DOT_LITERAL = '\\.';
  15074. const PLUS_LITERAL = '\\+';
  15075. const QMARK_LITERAL = '\\?';
  15076. const SLASH_LITERAL = '\\/';
  15077. const ONE_CHAR = '(?=.)';
  15078. const QMARK = '[^/]';
  15079. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  15080. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  15081. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  15082. const NO_DOT = `(?!${DOT_LITERAL})`;
  15083. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  15084. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  15085. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  15086. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  15087. const STAR = `${QMARK}*?`;
  15088. const POSIX_CHARS = {
  15089. DOT_LITERAL,
  15090. PLUS_LITERAL,
  15091. QMARK_LITERAL,
  15092. SLASH_LITERAL,
  15093. ONE_CHAR,
  15094. QMARK,
  15095. END_ANCHOR,
  15096. DOTS_SLASH,
  15097. NO_DOT,
  15098. NO_DOTS,
  15099. NO_DOT_SLASH,
  15100. NO_DOTS_SLASH,
  15101. QMARK_NO_DOT,
  15102. STAR,
  15103. START_ANCHOR
  15104. };
  15105. /**
  15106. * Windows glob regex
  15107. */
  15108. const WINDOWS_CHARS = Object.assign(Object.assign({}, POSIX_CHARS), { SLASH_LITERAL: `[${WIN_SLASH}]`, QMARK: WIN_NO_SLASH, STAR: `${WIN_NO_SLASH}*?`, DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, NO_DOT: `(?!${DOT_LITERAL})`, NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, QMARK_NO_DOT: `[^.${WIN_SLASH}]`, START_ANCHOR: `(?:^|[${WIN_SLASH}])`, END_ANCHOR: `(?:[${WIN_SLASH}]|$)` });
  15109. /**
  15110. * POSIX Bracket Regex
  15111. */
  15112. const POSIX_REGEX_SOURCE = {
  15113. alnum: 'a-zA-Z0-9',
  15114. alpha: 'a-zA-Z',
  15115. ascii: '\\x00-\\x7F',
  15116. blank: ' \\t',
  15117. cntrl: '\\x00-\\x1F\\x7F',
  15118. digit: '0-9',
  15119. graph: '\\x21-\\x7E',
  15120. lower: 'a-z',
  15121. print: '\\x20-\\x7E ',
  15122. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  15123. space: ' \\t\\r\\n\\v\\f',
  15124. upper: 'A-Z',
  15125. word: 'A-Za-z0-9_',
  15126. xdigit: 'A-Fa-f0-9'
  15127. };
  15128. var constants$1 = {
  15129. MAX_LENGTH: 1024 * 64,
  15130. POSIX_REGEX_SOURCE,
  15131. // regular expressions
  15132. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  15133. REGEX_NON_SPECIAL_CHAR: /^[^@![\].,$*+?^{}()|\\/]+/,
  15134. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  15135. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  15136. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  15137. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  15138. // Replace globs with equivalent patterns to reduce parsing time.
  15139. REPLACEMENTS: {
  15140. '***': '*',
  15141. '**/**': '**',
  15142. '**/**/**': '**'
  15143. },
  15144. // Digits
  15145. CHAR_0: 48,
  15146. CHAR_9: 57,
  15147. // Alphabet chars.
  15148. CHAR_UPPERCASE_A: 65,
  15149. CHAR_LOWERCASE_A: 97,
  15150. CHAR_UPPERCASE_Z: 90,
  15151. CHAR_LOWERCASE_Z: 122,
  15152. CHAR_LEFT_PARENTHESES: 40,
  15153. CHAR_RIGHT_PARENTHESES: 41,
  15154. CHAR_ASTERISK: 42,
  15155. // Non-alphabetic chars.
  15156. CHAR_AMPERSAND: 38,
  15157. CHAR_AT: 64,
  15158. CHAR_BACKWARD_SLASH: 92,
  15159. CHAR_CARRIAGE_RETURN: 13,
  15160. CHAR_CIRCUMFLEX_ACCENT: 94,
  15161. CHAR_COLON: 58,
  15162. CHAR_COMMA: 44,
  15163. CHAR_DOT: 46,
  15164. CHAR_DOUBLE_QUOTE: 34,
  15165. CHAR_EQUAL: 61,
  15166. CHAR_EXCLAMATION_MARK: 33,
  15167. CHAR_FORM_FEED: 12,
  15168. CHAR_FORWARD_SLASH: 47,
  15169. CHAR_GRAVE_ACCENT: 96,
  15170. CHAR_HASH: 35,
  15171. CHAR_HYPHEN_MINUS: 45,
  15172. CHAR_LEFT_ANGLE_BRACKET: 60,
  15173. CHAR_LEFT_CURLY_BRACE: 123,
  15174. CHAR_LEFT_SQUARE_BRACKET: 91,
  15175. CHAR_LINE_FEED: 10,
  15176. CHAR_NO_BREAK_SPACE: 160,
  15177. CHAR_PERCENT: 37,
  15178. CHAR_PLUS: 43,
  15179. CHAR_QUESTION_MARK: 63,
  15180. CHAR_RIGHT_ANGLE_BRACKET: 62,
  15181. CHAR_RIGHT_CURLY_BRACE: 125,
  15182. CHAR_RIGHT_SQUARE_BRACKET: 93,
  15183. CHAR_SEMICOLON: 59,
  15184. CHAR_SINGLE_QUOTE: 39,
  15185. CHAR_SPACE: 32,
  15186. CHAR_TAB: 9,
  15187. CHAR_UNDERSCORE: 95,
  15188. CHAR_VERTICAL_LINE: 124,
  15189. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
  15190. SEP: path.sep,
  15191. /**
  15192. * Create EXTGLOB_CHARS
  15193. */
  15194. extglobChars(chars) {
  15195. return {
  15196. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  15197. '?': { type: 'qmark', open: '(?:', close: ')?' },
  15198. '+': { type: 'plus', open: '(?:', close: ')+' },
  15199. '*': { type: 'star', open: '(?:', close: ')*' },
  15200. '@': { type: 'at', open: '(?:', close: ')' }
  15201. };
  15202. },
  15203. /**
  15204. * Create GLOB_CHARS
  15205. */
  15206. globChars(win32) {
  15207. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  15208. }
  15209. };
  15210. var utils$2 = createCommonjsModule(function (module, exports) {
  15211. const win32 = process.platform === 'win32';
  15212. const { REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL, REGEX_REMOVE_BACKSLASH } = constants$1;
  15213. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  15214. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  15215. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  15216. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  15217. exports.toPosixSlashes = str => str.replace(/\\/g, '/');
  15218. exports.removeBackslashes = str => {
  15219. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  15220. return match === '\\' ? '' : match;
  15221. });
  15222. };
  15223. exports.supportsLookbehinds = () => {
  15224. let segs = process.version.slice(1).split('.');
  15225. if (segs.length === 3 && +segs[0] >= 9 || (+segs[0] === 8 && +segs[1] >= 10)) {
  15226. return true;
  15227. }
  15228. return false;
  15229. };
  15230. exports.isWindows = options => {
  15231. if (options && typeof options.windows === 'boolean') {
  15232. return options.windows;
  15233. }
  15234. return win32 === true || path.sep === '\\';
  15235. };
  15236. exports.escapeLast = (input, char, lastIdx) => {
  15237. let idx = input.lastIndexOf(char, lastIdx);
  15238. if (idx === -1)
  15239. return input;
  15240. if (input[idx - 1] === '\\')
  15241. return exports.escapeLast(input, char, idx - 1);
  15242. return input.slice(0, idx) + '\\' + input.slice(idx);
  15243. };
  15244. });
  15245. const { CHAR_ASTERISK, /* * */ CHAR_AT, /* @ */ CHAR_BACKWARD_SLASH, /* \ */ CHAR_COMMA: CHAR_COMMA$1, /* , */ CHAR_DOT: CHAR_DOT$1, /* . */ CHAR_EXCLAMATION_MARK, /* ! */ CHAR_FORWARD_SLASH, /* / */ CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */ CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */ CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */ CHAR_PLUS, /* + */ CHAR_QUESTION_MARK, /* ? */ CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */ CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */ CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1 /* ] */ } = constants$1;
  15246. const isPathSeparator = code => {
  15247. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  15248. };
  15249. /**
  15250. * Quickly scans a glob pattern and returns an object with a handful of
  15251. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  15252. * `glob` (the actual pattern), and `negated` (true if the path starts with `!`).
  15253. *
  15254. * ```js
  15255. * const pm = require('picomatch');
  15256. * console.log(pm.scan('foo/bar/*.js'));
  15257. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  15258. * ```
  15259. * @param {String} `str`
  15260. * @param {Object} `options`
  15261. * @return {Object} Returns an object with tokens and regex source string.
  15262. * @api public
  15263. */
  15264. var scan = (input, options) => {
  15265. let opts = options || {};
  15266. let length = input.length - 1;
  15267. let index = -1;
  15268. let start = 0;
  15269. let lastIndex = 0;
  15270. let isGlob = false;
  15271. let backslashes = false;
  15272. let negated = false;
  15273. let braces = 0;
  15274. let prev;
  15275. let code;
  15276. let braceEscaped = false;
  15277. let eos = () => index >= length;
  15278. let advance = () => {
  15279. prev = code;
  15280. return input.charCodeAt(++index);
  15281. };
  15282. while (index < length) {
  15283. code = advance();
  15284. let next;
  15285. if (code === CHAR_BACKWARD_SLASH) {
  15286. backslashes = true;
  15287. next = advance();
  15288. if (next === CHAR_LEFT_CURLY_BRACE$1) {
  15289. braceEscaped = true;
  15290. }
  15291. continue;
  15292. }
  15293. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) {
  15294. braces++;
  15295. while (!eos() && (next = advance())) {
  15296. if (next === CHAR_BACKWARD_SLASH) {
  15297. backslashes = true;
  15298. next = advance();
  15299. continue;
  15300. }
  15301. if (next === CHAR_LEFT_CURLY_BRACE$1) {
  15302. braces++;
  15303. continue;
  15304. }
  15305. if (!braceEscaped && next === CHAR_DOT$1 && (next = advance()) === CHAR_DOT$1) {
  15306. isGlob = true;
  15307. break;
  15308. }
  15309. if (!braceEscaped && next === CHAR_COMMA$1) {
  15310. isGlob = true;
  15311. break;
  15312. }
  15313. if (next === CHAR_RIGHT_CURLY_BRACE$1) {
  15314. braces--;
  15315. if (braces === 0) {
  15316. braceEscaped = false;
  15317. break;
  15318. }
  15319. }
  15320. }
  15321. }
  15322. if (code === CHAR_FORWARD_SLASH) {
  15323. if (prev === CHAR_DOT$1 && index === (start + 1)) {
  15324. start += 2;
  15325. continue;
  15326. }
  15327. lastIndex = index + 1;
  15328. continue;
  15329. }
  15330. if (code === CHAR_ASTERISK) {
  15331. isGlob = true;
  15332. break;
  15333. }
  15334. if (code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK) {
  15335. isGlob = true;
  15336. break;
  15337. }
  15338. if (code === CHAR_LEFT_SQUARE_BRACKET$1) {
  15339. while (!eos() && (next = advance())) {
  15340. if (next === CHAR_BACKWARD_SLASH) {
  15341. backslashes = true;
  15342. next = advance();
  15343. continue;
  15344. }
  15345. if (next === CHAR_RIGHT_SQUARE_BRACKET$1) {
  15346. isGlob = true;
  15347. break;
  15348. }
  15349. }
  15350. }
  15351. let isExtglobChar = code === CHAR_PLUS
  15352. || code === CHAR_AT
  15353. || code === CHAR_EXCLAMATION_MARK;
  15354. if (isExtglobChar && input.charCodeAt(index + 1) === CHAR_LEFT_PARENTHESES$1) {
  15355. isGlob = true;
  15356. break;
  15357. }
  15358. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  15359. negated = true;
  15360. start++;
  15361. continue;
  15362. }
  15363. if (code === CHAR_LEFT_PARENTHESES$1) {
  15364. while (!eos() && (next = advance())) {
  15365. if (next === CHAR_BACKWARD_SLASH) {
  15366. backslashes = true;
  15367. next = advance();
  15368. continue;
  15369. }
  15370. if (next === CHAR_RIGHT_PARENTHESES$1) {
  15371. isGlob = true;
  15372. break;
  15373. }
  15374. }
  15375. }
  15376. if (isGlob) {
  15377. break;
  15378. }
  15379. }
  15380. let prefix = '';
  15381. let orig = input;
  15382. let base = input;
  15383. let glob = '';
  15384. if (start > 0) {
  15385. prefix = input.slice(0, start);
  15386. input = input.slice(start);
  15387. lastIndex -= start;
  15388. }
  15389. if (base && isGlob === true && lastIndex > 0) {
  15390. base = input.slice(0, lastIndex);
  15391. glob = input.slice(lastIndex);
  15392. }
  15393. else if (isGlob === true) {
  15394. base = '';
  15395. glob = input;
  15396. }
  15397. else {
  15398. base = input;
  15399. }
  15400. if (base && base !== '' && base !== '/' && base !== input) {
  15401. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  15402. base = base.slice(0, -1);
  15403. }
  15404. }
  15405. if (opts.unescape === true) {
  15406. if (glob)
  15407. glob = utils$2.removeBackslashes(glob);
  15408. if (base && backslashes === true) {
  15409. base = utils$2.removeBackslashes(base);
  15410. }
  15411. }
  15412. return { prefix, input: orig, base, glob, negated, isGlob };
  15413. };
  15414. /**
  15415. * Constants
  15416. */
  15417. const { MAX_LENGTH: MAX_LENGTH$1, POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1, REGEX_NON_SPECIAL_CHAR, REGEX_SPECIAL_CHARS_BACKREF, REPLACEMENTS } = constants$1;
  15418. /**
  15419. * Helpers
  15420. */
  15421. const expandRange = (args, options) => {
  15422. if (typeof options.expandRange === 'function') {
  15423. return options.expandRange(...args, options);
  15424. }
  15425. args.sort();
  15426. let value = `[${args.join('-')}]`;
  15427. return value;
  15428. };
  15429. const negate = state => {
  15430. let count = 1;
  15431. while (state.peek() === '!' && (state.peek(2) !== '(' || state.peek(3) === '?')) {
  15432. state.advance();
  15433. state.start++;
  15434. count++;
  15435. }
  15436. if (count % 2 === 0) {
  15437. return false;
  15438. }
  15439. state.negated = true;
  15440. state.start++;
  15441. return true;
  15442. };
  15443. /**
  15444. * Create the message for a syntax error
  15445. */
  15446. const syntaxError = (type, char) => {
  15447. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  15448. };
  15449. /**
  15450. * Parse the given input string.
  15451. * @param {String} input
  15452. * @param {Object} options
  15453. * @return {Object}
  15454. */
  15455. const parse$1 = (input, options) => {
  15456. if (typeof input !== 'string') {
  15457. throw new TypeError('Expected a string');
  15458. }
  15459. input = REPLACEMENTS[input] || input;
  15460. let opts = Object.assign({}, options);
  15461. let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
  15462. let len = input.length;
  15463. if (len > max) {
  15464. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  15465. }
  15466. let bos = { type: 'bos', value: '', output: opts.prepend || '' };
  15467. let tokens = [bos];
  15468. let capture = opts.capture ? '' : '?:';
  15469. let win32 = utils$2.isWindows(options);
  15470. // create constants based on platform, for windows or posix
  15471. const PLATFORM_CHARS = constants$1.globChars(win32);
  15472. const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
  15473. const { DOT_LITERAL, PLUS_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK, QMARK_NO_DOT, STAR, START_ANCHOR } = PLATFORM_CHARS;
  15474. const globstar = (opts) => {
  15475. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  15476. };
  15477. let nodot = opts.dot ? '' : NO_DOT;
  15478. let star = opts.bash === true ? globstar(opts) : STAR;
  15479. let qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  15480. if (opts.capture) {
  15481. star = `(${star})`;
  15482. }
  15483. // minimatch options support
  15484. if (typeof opts.noext === 'boolean') {
  15485. opts.noextglob = opts.noext;
  15486. }
  15487. let state = {
  15488. index: -1,
  15489. start: 0,
  15490. consumed: '',
  15491. output: '',
  15492. backtrack: false,
  15493. brackets: 0,
  15494. braces: 0,
  15495. parens: 0,
  15496. quotes: 0,
  15497. tokens
  15498. };
  15499. let extglobs = [];
  15500. let stack = [];
  15501. let prev = bos;
  15502. let value;
  15503. /**
  15504. * Tokenizing helpers
  15505. */
  15506. const eos = () => state.index === len - 1;
  15507. const peek = state.peek = (n = 1) => input[state.index + n];
  15508. const advance = state.advance = () => input[++state.index];
  15509. const append = token => {
  15510. state.output += token.output != null ? token.output : token.value;
  15511. state.consumed += token.value || '';
  15512. };
  15513. const increment = type => {
  15514. state[type]++;
  15515. stack.push(type);
  15516. };
  15517. const decrement = type => {
  15518. state[type]--;
  15519. stack.pop();
  15520. };
  15521. /**
  15522. * Push tokens onto the tokens array. This helper speeds up
  15523. * tokenizing by 1) helping us avoid backtracking as much as possible,
  15524. * and 2) helping us avoid creating extra tokens when consecutive
  15525. * characters are plain text. This improves performance and simplifies
  15526. * lookbehinds.
  15527. */
  15528. const push = tok => {
  15529. if (prev.type === 'globstar') {
  15530. let isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  15531. let isExtglob = extglobs.length && (tok.type === 'pipe' || tok.type === 'paren');
  15532. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  15533. state.output = state.output.slice(0, -prev.output.length);
  15534. prev.type = 'star';
  15535. prev.value = '*';
  15536. prev.output = star;
  15537. state.output += prev.output;
  15538. }
  15539. }
  15540. if (extglobs.length && tok.type !== 'paren' && !EXTGLOB_CHARS[tok.value]) {
  15541. extglobs[extglobs.length - 1].inner += tok.value;
  15542. }
  15543. if (tok.value || tok.output)
  15544. append(tok);
  15545. if (prev && prev.type === 'text' && tok.type === 'text') {
  15546. prev.value += tok.value;
  15547. return;
  15548. }
  15549. tok.prev = prev;
  15550. tokens.push(tok);
  15551. prev = tok;
  15552. };
  15553. const extglobOpen = (type, value) => {
  15554. let token = Object.assign(Object.assign({}, EXTGLOB_CHARS[value]), { conditions: 1, inner: '' });
  15555. token.prev = prev;
  15556. token.parens = state.parens;
  15557. token.output = state.output;
  15558. let output = (opts.capture ? '(' : '') + token.open;
  15559. push({ type, value, output: state.output ? '' : ONE_CHAR });
  15560. push({ type: 'paren', extglob: true, value: advance(), output });
  15561. increment('parens');
  15562. extglobs.push(token);
  15563. };
  15564. const extglobClose = token => {
  15565. let output = token.close + (opts.capture ? ')' : '');
  15566. if (token.type === 'negate') {
  15567. let extglobStar = star;
  15568. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  15569. extglobStar = globstar(opts);
  15570. }
  15571. if (extglobStar !== star || eos() || /^\)+$/.test(input.slice(state.index + 1))) {
  15572. output = token.close = ')$))' + extglobStar;
  15573. }
  15574. if (token.prev.type === 'bos' && eos()) {
  15575. state.negatedExtglob = true;
  15576. }
  15577. }
  15578. push({ type: 'paren', extglob: true, value, output });
  15579. decrement('parens');
  15580. };
  15581. if (opts.fastpaths !== false && !/(^[*!]|[/{[()\]}"])/.test(input)) {
  15582. let backslashes = false;
  15583. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  15584. if (first === '\\') {
  15585. backslashes = true;
  15586. return m;
  15587. }
  15588. if (first === '?') {
  15589. if (esc) {
  15590. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  15591. }
  15592. if (index === 0) {
  15593. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  15594. }
  15595. return QMARK.repeat(chars.length);
  15596. }
  15597. if (first === '.') {
  15598. return DOT_LITERAL.repeat(chars.length);
  15599. }
  15600. if (first === '*') {
  15601. if (esc) {
  15602. return esc + first + (rest ? star : '');
  15603. }
  15604. return star;
  15605. }
  15606. return esc ? m : '\\' + m;
  15607. });
  15608. if (backslashes === true) {
  15609. if (opts.unescape === true) {
  15610. output = output.replace(/\\/g, '');
  15611. }
  15612. else {
  15613. output = output.replace(/\\+/g, m => {
  15614. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  15615. });
  15616. }
  15617. }
  15618. state.output = output;
  15619. return state;
  15620. }
  15621. /**
  15622. * Tokenize input until we reach end-of-string
  15623. */
  15624. while (!eos()) {
  15625. value = advance();
  15626. if (value === '\u0000') {
  15627. continue;
  15628. }
  15629. /**
  15630. * Escaped characters
  15631. */
  15632. if (value === '\\') {
  15633. let next = peek();
  15634. if (next === '/' && opts.bash !== true) {
  15635. continue;
  15636. }
  15637. if (next === '.' || next === ';') {
  15638. continue;
  15639. }
  15640. if (!next) {
  15641. value += '\\';
  15642. push({ type: 'text', value });
  15643. continue;
  15644. }
  15645. // collapse slashes to reduce potential for exploits
  15646. let match = /^\\+/.exec(input.slice(state.index + 1));
  15647. let slashes = 0;
  15648. if (match && match[0].length > 2) {
  15649. slashes = match[0].length;
  15650. state.index += slashes;
  15651. if (slashes % 2 !== 0) {
  15652. value += '\\';
  15653. }
  15654. }
  15655. if (opts.unescape === true) {
  15656. value = advance() || '';
  15657. }
  15658. else {
  15659. value += advance() || '';
  15660. }
  15661. if (state.brackets === 0) {
  15662. push({ type: 'text', value });
  15663. continue;
  15664. }
  15665. }
  15666. /**
  15667. * If we're inside a regex character class, continue
  15668. * until we reach the closing bracket.
  15669. */
  15670. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  15671. if (opts.posix !== false && value === ':') {
  15672. let inner = prev.value.slice(1);
  15673. if (inner.includes('[')) {
  15674. prev.posix = true;
  15675. if (inner.includes(':')) {
  15676. let idx = prev.value.lastIndexOf('[');
  15677. let pre = prev.value.slice(0, idx);
  15678. let rest = prev.value.slice(idx + 2);
  15679. let posix = POSIX_REGEX_SOURCE$1[rest];
  15680. if (posix) {
  15681. prev.value = pre + posix;
  15682. state.backtrack = true;
  15683. advance();
  15684. if (!bos.output && tokens.indexOf(prev) === 1) {
  15685. bos.output = ONE_CHAR;
  15686. }
  15687. continue;
  15688. }
  15689. }
  15690. }
  15691. }
  15692. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  15693. value = '\\' + value;
  15694. }
  15695. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  15696. value = '\\' + value;
  15697. }
  15698. if (opts.posix === true && value === '!' && prev.value === '[') {
  15699. value = '^';
  15700. }
  15701. prev.value += value;
  15702. append({ value });
  15703. continue;
  15704. }
  15705. /**
  15706. * If we're inside a quoted string, continue
  15707. * until we reach the closing double quote.
  15708. */
  15709. if (state.quotes === 1 && value !== '"') {
  15710. value = utils$2.escapeRegex(value);
  15711. prev.value += value;
  15712. append({ value });
  15713. continue;
  15714. }
  15715. /**
  15716. * Double quotes
  15717. */
  15718. if (value === '"') {
  15719. state.quotes = state.quotes === 1 ? 0 : 1;
  15720. if (opts.keepQuotes === true) {
  15721. push({ type: 'text', value });
  15722. }
  15723. continue;
  15724. }
  15725. /**
  15726. * Parentheses
  15727. */
  15728. if (value === '(') {
  15729. push({ type: 'paren', value });
  15730. increment('parens');
  15731. continue;
  15732. }
  15733. if (value === ')') {
  15734. if (state.parens === 0 && opts.strictBrackets === true) {
  15735. throw new SyntaxError(syntaxError('opening', '('));
  15736. }
  15737. let extglob = extglobs[extglobs.length - 1];
  15738. if (extglob && state.parens === extglob.parens + 1) {
  15739. extglobClose(extglobs.pop());
  15740. continue;
  15741. }
  15742. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  15743. decrement('parens');
  15744. continue;
  15745. }
  15746. /**
  15747. * Brackets
  15748. */
  15749. if (value === '[') {
  15750. if (opts.nobracket === true || !input.slice(state.index + 1).includes(']')) {
  15751. if (opts.nobracket !== true && opts.strictBrackets === true) {
  15752. throw new SyntaxError(syntaxError('closing', ']'));
  15753. }
  15754. value = '\\' + value;
  15755. }
  15756. else {
  15757. increment('brackets');
  15758. }
  15759. push({ type: 'bracket', value });
  15760. continue;
  15761. }
  15762. if (value === ']') {
  15763. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  15764. push({ type: 'text', value, output: '\\' + value });
  15765. continue;
  15766. }
  15767. if (state.brackets === 0) {
  15768. if (opts.strictBrackets === true) {
  15769. throw new SyntaxError(syntaxError('opening', '['));
  15770. }
  15771. push({ type: 'text', value, output: '\\' + value });
  15772. continue;
  15773. }
  15774. decrement('brackets');
  15775. let prevValue = prev.value.slice(1);
  15776. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  15777. value = '/' + value;
  15778. }
  15779. prev.value += value;
  15780. append({ value });
  15781. // when literal brackets are explicitly disabled
  15782. // assume we should match with a regex character class
  15783. if (opts.literalBrackets === false || utils$2.hasRegexChars(prevValue)) {
  15784. continue;
  15785. }
  15786. let escaped = utils$2.escapeRegex(prev.value);
  15787. state.output = state.output.slice(0, -prev.value.length);
  15788. // when literal brackets are explicitly enabled
  15789. // assume we should escape the brackets to match literal characters
  15790. if (opts.literalBrackets === true) {
  15791. state.output += escaped;
  15792. prev.value = escaped;
  15793. continue;
  15794. }
  15795. // when the user specifies nothing, try to match both
  15796. prev.value = `(${capture}${escaped}|${prev.value})`;
  15797. state.output += prev.value;
  15798. continue;
  15799. }
  15800. /**
  15801. * Braces
  15802. */
  15803. if (value === '{' && opts.nobrace !== true) {
  15804. push({ type: 'brace', value, output: '(' });
  15805. increment('braces');
  15806. continue;
  15807. }
  15808. if (value === '}') {
  15809. if (opts.nobrace === true || state.braces === 0) {
  15810. push({ type: 'text', value, output: '\\' + value });
  15811. continue;
  15812. }
  15813. let output = ')';
  15814. if (state.dots === true) {
  15815. let arr = tokens.slice();
  15816. let range = [];
  15817. for (let i = arr.length - 1; i >= 0; i--) {
  15818. tokens.pop();
  15819. if (arr[i].type === 'brace') {
  15820. break;
  15821. }
  15822. if (arr[i].type !== 'dots') {
  15823. range.unshift(arr[i].value);
  15824. }
  15825. }
  15826. output = expandRange(range, opts);
  15827. state.backtrack = true;
  15828. }
  15829. push({ type: 'brace', value, output });
  15830. decrement('braces');
  15831. continue;
  15832. }
  15833. /**
  15834. * Pipes
  15835. */
  15836. if (value === '|') {
  15837. if (extglobs.length > 0) {
  15838. extglobs[extglobs.length - 1].conditions++;
  15839. }
  15840. push({ type: 'text', value });
  15841. continue;
  15842. }
  15843. /**
  15844. * Commas
  15845. */
  15846. if (value === ',') {
  15847. let output = value;
  15848. if (state.braces > 0 && stack[stack.length - 1] === 'braces') {
  15849. output = '|';
  15850. }
  15851. push({ type: 'comma', value, output });
  15852. continue;
  15853. }
  15854. /**
  15855. * Slashes
  15856. */
  15857. if (value === '/') {
  15858. // if the beginning of the glob is "./", advance the start
  15859. // to the current index, and don't add the "./" characters
  15860. // to the state. This greatly simplifies lookbehinds when
  15861. // checking for BOS characters like "!" and "." (not "./")
  15862. if (prev.type === 'dot' && state.index === 1) {
  15863. state.start = state.index + 1;
  15864. state.consumed = '';
  15865. state.output = '';
  15866. tokens.pop();
  15867. prev = bos; // reset "prev" to the first token
  15868. continue;
  15869. }
  15870. push({ type: 'slash', value, output: SLASH_LITERAL });
  15871. continue;
  15872. }
  15873. /**
  15874. * Dots
  15875. */
  15876. if (value === '.') {
  15877. if (state.braces > 0 && prev.type === 'dot') {
  15878. if (prev.value === '.')
  15879. prev.output = DOT_LITERAL;
  15880. prev.type = 'dots';
  15881. prev.output += value;
  15882. prev.value += value;
  15883. state.dots = true;
  15884. continue;
  15885. }
  15886. push({ type: 'dot', value, output: DOT_LITERAL });
  15887. continue;
  15888. }
  15889. /**
  15890. * Question marks
  15891. */
  15892. if (value === '?') {
  15893. if (prev && prev.type === 'paren') {
  15894. let next = peek();
  15895. let output = value;
  15896. if (next === '<' && !utils$2.supportsLookbehinds()) {
  15897. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  15898. }
  15899. if (prev.value === '(' && !/[!=<:]/.test(next) || (next === '<' && !/[!=]/.test(peek(2)))) {
  15900. output = '\\' + value;
  15901. }
  15902. push({ type: 'text', value, output });
  15903. continue;
  15904. }
  15905. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  15906. extglobOpen('qmark', value);
  15907. continue;
  15908. }
  15909. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  15910. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  15911. continue;
  15912. }
  15913. push({ type: 'qmark', value, output: QMARK });
  15914. continue;
  15915. }
  15916. /**
  15917. * Exclamation
  15918. */
  15919. if (value === '!') {
  15920. if (opts.noextglob !== true && peek() === '(') {
  15921. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  15922. extglobOpen('negate', value);
  15923. continue;
  15924. }
  15925. }
  15926. if (opts.nonegate !== true && state.index === 0) {
  15927. negate(state);
  15928. continue;
  15929. }
  15930. }
  15931. /**
  15932. * Plus
  15933. */
  15934. if (value === '+') {
  15935. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  15936. extglobOpen('plus', value);
  15937. continue;
  15938. }
  15939. if (prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) {
  15940. let output = prev.extglob === true ? '\\' + value : value;
  15941. push({ type: 'plus', value, output });
  15942. continue;
  15943. }
  15944. // use regex behavior inside parens
  15945. if (state.parens > 0 && opts.regex !== false) {
  15946. push({ type: 'plus', value });
  15947. continue;
  15948. }
  15949. push({ type: 'plus', value: PLUS_LITERAL });
  15950. continue;
  15951. }
  15952. /**
  15953. * Plain text
  15954. */
  15955. if (value === '@') {
  15956. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  15957. push({ type: 'at', value, output: '' });
  15958. continue;
  15959. }
  15960. push({ type: 'text', value });
  15961. continue;
  15962. }
  15963. /**
  15964. * Plain text
  15965. */
  15966. if (value !== '*') {
  15967. if (value === '$' || value === '^') {
  15968. value = '\\' + value;
  15969. }
  15970. let match = REGEX_NON_SPECIAL_CHAR.exec(input.slice(state.index + 1));
  15971. if (match) {
  15972. value += match[0];
  15973. state.index += match[0].length;
  15974. }
  15975. push({ type: 'text', value });
  15976. continue;
  15977. }
  15978. /**
  15979. * Stars
  15980. */
  15981. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  15982. prev.type = 'star';
  15983. prev.star = true;
  15984. prev.value += value;
  15985. prev.output = star;
  15986. state.backtrack = true;
  15987. state.consumed += value;
  15988. continue;
  15989. }
  15990. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  15991. extglobOpen('star', value);
  15992. continue;
  15993. }
  15994. if (prev.type === 'star') {
  15995. if (opts.noglobstar === true) {
  15996. state.consumed += value;
  15997. continue;
  15998. }
  15999. let prior = prev.prev;
  16000. let before = prior.prev;
  16001. let isStart = prior.type === 'slash' || prior.type === 'bos';
  16002. let afterStar = before && (before.type === 'star' || before.type === 'globstar');
  16003. if (opts.bash === true && (!isStart || (!eos() && peek() !== '/'))) {
  16004. push({ type: 'star', value, output: '' });
  16005. continue;
  16006. }
  16007. let isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  16008. let isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  16009. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  16010. push({ type: 'star', value, output: '' });
  16011. continue;
  16012. }
  16013. // strip consecutive `/**/`
  16014. while (input.slice(state.index + 1, state.index + 4) === '/**') {
  16015. let after = input[state.index + 4];
  16016. if (after && after !== '/') {
  16017. break;
  16018. }
  16019. state.consumed += '/**';
  16020. state.index += 3;
  16021. }
  16022. if (prior.type === 'bos' && eos()) {
  16023. prev.type = 'globstar';
  16024. prev.value += value;
  16025. prev.output = globstar(opts);
  16026. state.output = prev.output;
  16027. state.consumed += value;
  16028. continue;
  16029. }
  16030. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  16031. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  16032. prior.output = '(?:' + prior.output;
  16033. prev.type = 'globstar';
  16034. prev.output = globstar(opts) + '|$)';
  16035. prev.value += value;
  16036. state.output += prior.output + prev.output;
  16037. state.consumed += value;
  16038. continue;
  16039. }
  16040. let next = peek();
  16041. if (prior.type === 'slash' && prior.prev.type !== 'bos' && next === '/') {
  16042. let end = peek(2) !== void 0 ? '|$' : '';
  16043. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  16044. prior.output = '(?:' + prior.output;
  16045. prev.type = 'globstar';
  16046. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  16047. prev.value += value;
  16048. state.output += prior.output + prev.output;
  16049. state.consumed += value + advance();
  16050. push({ type: 'slash', value, output: '' });
  16051. continue;
  16052. }
  16053. if (prior.type === 'bos' && next === '/') {
  16054. prev.type = 'globstar';
  16055. prev.value += value;
  16056. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  16057. state.output = prev.output;
  16058. state.consumed += value + advance();
  16059. push({ type: 'slash', value, output: '' });
  16060. continue;
  16061. }
  16062. // remove single star from output
  16063. state.output = state.output.slice(0, -prev.output.length);
  16064. // reset previous token to globstar
  16065. prev.type = 'globstar';
  16066. prev.output = globstar(opts);
  16067. prev.value += value;
  16068. // reset output with globstar
  16069. state.output += prev.output;
  16070. state.consumed += value;
  16071. continue;
  16072. }
  16073. let token = { type: 'star', value, output: star };
  16074. if (opts.bash === true) {
  16075. token.output = '.*?';
  16076. if (prev.type === 'bos' || prev.type === 'slash') {
  16077. token.output = nodot + token.output;
  16078. }
  16079. push(token);
  16080. continue;
  16081. }
  16082. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  16083. token.output = value;
  16084. push(token);
  16085. continue;
  16086. }
  16087. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  16088. if (prev.type === 'dot') {
  16089. state.output += NO_DOT_SLASH;
  16090. prev.output += NO_DOT_SLASH;
  16091. }
  16092. else if (opts.dot === true) {
  16093. state.output += NO_DOTS_SLASH;
  16094. prev.output += NO_DOTS_SLASH;
  16095. }
  16096. else {
  16097. state.output += nodot;
  16098. prev.output += nodot;
  16099. }
  16100. if (peek() !== '*') {
  16101. state.output += ONE_CHAR;
  16102. prev.output += ONE_CHAR;
  16103. }
  16104. }
  16105. push(token);
  16106. }
  16107. while (state.brackets > 0) {
  16108. if (opts.strictBrackets === true)
  16109. throw new SyntaxError(syntaxError('closing', ']'));
  16110. state.output = utils$2.escapeLast(state.output, '[');
  16111. decrement('brackets');
  16112. }
  16113. while (state.parens > 0) {
  16114. if (opts.strictBrackets === true)
  16115. throw new SyntaxError(syntaxError('closing', ')'));
  16116. state.output = utils$2.escapeLast(state.output, '(');
  16117. decrement('parens');
  16118. }
  16119. while (state.braces > 0) {
  16120. if (opts.strictBrackets === true)
  16121. throw new SyntaxError(syntaxError('closing', '}'));
  16122. state.output = utils$2.escapeLast(state.output, '{');
  16123. decrement('braces');
  16124. }
  16125. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  16126. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  16127. }
  16128. // rebuild the output if we had to backtrack at any point
  16129. if (state.backtrack === true) {
  16130. state.output = '';
  16131. for (let token of state.tokens) {
  16132. state.output += token.output != null ? token.output : token.value;
  16133. if (token.suffix) {
  16134. state.output += token.suffix;
  16135. }
  16136. }
  16137. }
  16138. return state;
  16139. };
  16140. /**
  16141. * Fast paths for creating regular expressions for common glob patterns.
  16142. * This can significantly speed up processing and has very little downside
  16143. * impact when none of the fast paths match.
  16144. */
  16145. parse$1.fastpaths = (input, options) => {
  16146. let opts = Object.assign({}, options);
  16147. let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
  16148. let len = input.length;
  16149. if (len > max) {
  16150. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  16151. }
  16152. input = REPLACEMENTS[input] || input;
  16153. let win32 = utils$2.isWindows(options);
  16154. // create constants based on platform, for windows or posix
  16155. const { DOT_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOTS, NO_DOTS_SLASH, STAR, START_ANCHOR } = constants$1.globChars(win32);
  16156. let capture = opts.capture ? '' : '?:';
  16157. let star = opts.bash === true ? '.*?' : STAR;
  16158. let nodot = opts.dot ? NO_DOTS : NO_DOT;
  16159. let slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  16160. if (opts.capture) {
  16161. star = `(${star})`;
  16162. }
  16163. const globstar = (opts) => {
  16164. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  16165. };
  16166. const create = str => {
  16167. switch (str) {
  16168. case '*':
  16169. return `${nodot}${ONE_CHAR}${star}`;
  16170. case '.*':
  16171. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  16172. case '*.*':
  16173. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  16174. case '*/*':
  16175. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  16176. case '**':
  16177. return nodot + globstar(opts);
  16178. case '**/*':
  16179. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  16180. case '**/*.*':
  16181. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  16182. case '**/.*':
  16183. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  16184. default: {
  16185. let match = /^(.*?)\.(\w+)$/.exec(str);
  16186. if (!match)
  16187. return;
  16188. let source = create(match[1]);
  16189. if (!source)
  16190. return;
  16191. return source + DOT_LITERAL + match[2];
  16192. }
  16193. }
  16194. };
  16195. let output = create(input);
  16196. if (output && opts.strictSlashes !== true) {
  16197. output += `${SLASH_LITERAL}?`;
  16198. }
  16199. return output;
  16200. };
  16201. var parse_1$1 = parse$1;
  16202. /**
  16203. * Creates a matcher function from one or more glob patterns. The
  16204. * returned function takes a string to match as its first argument,
  16205. * and returns true if the string is a match. The returned matcher
  16206. * function also takes a boolean as the second argument that, when true,
  16207. * returns an object with additional information.
  16208. *
  16209. * ```js
  16210. * const picomatch = require('picomatch');
  16211. * // picomatch(glob[, options]);
  16212. *
  16213. * const isMatch = picomatch('*.!(*a)');
  16214. * console.log(isMatch('a.a')); //=> false
  16215. * console.log(isMatch('a.b')); //=> true
  16216. * ```
  16217. * @name picomatch
  16218. * @param {String|Array} `globs` One or more glob patterns.
  16219. * @param {Object=} `options`
  16220. * @return {Function=} Returns a matcher function.
  16221. * @api public
  16222. */
  16223. const picomatch = (glob, options, returnState = false) => {
  16224. if (Array.isArray(glob)) {
  16225. let fns = glob.map(input => picomatch(input, options, returnState));
  16226. return str => {
  16227. for (let isMatch of fns) {
  16228. let state = isMatch(str);
  16229. if (state)
  16230. return state;
  16231. }
  16232. return false;
  16233. };
  16234. }
  16235. if (typeof glob !== 'string' || glob === '') {
  16236. throw new TypeError('Expected pattern to be a non-empty string');
  16237. }
  16238. let opts = options || {};
  16239. let posix = utils$2.isWindows(options);
  16240. let regex = picomatch.makeRe(glob, options, false, true);
  16241. let state = regex.state;
  16242. delete regex.state;
  16243. let isIgnored = () => false;
  16244. if (opts.ignore) {
  16245. let ignoreOpts = Object.assign(Object.assign({}, options), { ignore: null, onMatch: null, onResult: null });
  16246. isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
  16247. }
  16248. const matcher = (input, returnObject = false) => {
  16249. let { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
  16250. let result = { glob, state, regex, posix, input, output, match, isMatch };
  16251. if (typeof opts.onResult === 'function') {
  16252. opts.onResult(result);
  16253. }
  16254. if (isMatch === false) {
  16255. result.isMatch = false;
  16256. return returnObject ? result : false;
  16257. }
  16258. if (isIgnored(input)) {
  16259. if (typeof opts.onIgnore === 'function') {
  16260. opts.onIgnore(result);
  16261. }
  16262. result.isMatch = false;
  16263. return returnObject ? result : false;
  16264. }
  16265. if (typeof opts.onMatch === 'function') {
  16266. opts.onMatch(result);
  16267. }
  16268. return returnObject ? result : true;
  16269. };
  16270. if (returnState) {
  16271. matcher.state = state;
  16272. }
  16273. return matcher;
  16274. };
  16275. /**
  16276. * Test `input` with the given `regex`. This is used by the main
  16277. * `picomatch()` function to test the input string.
  16278. *
  16279. * ```js
  16280. * const picomatch = require('picomatch');
  16281. * // picomatch.test(input, regex[, options]);
  16282. *
  16283. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  16284. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  16285. * ```
  16286. * @param {String} `input` String to test.
  16287. * @param {RegExp} `regex`
  16288. * @return {Object} Returns an object with matching info.
  16289. * @api public
  16290. */
  16291. picomatch.test = (input, regex, options, { glob, posix } = {}) => {
  16292. if (typeof input !== 'string') {
  16293. throw new TypeError('Expected input to be a string');
  16294. }
  16295. if (input === '') {
  16296. return { isMatch: false, output: '' };
  16297. }
  16298. let opts = options || {};
  16299. let format = opts.format || (posix ? utils$2.toPosixSlashes : null);
  16300. let match = input === glob;
  16301. let output = (match && format) ? format(input) : input;
  16302. if (match === false) {
  16303. output = format ? format(input) : input;
  16304. match = output === glob;
  16305. }
  16306. if (match === false || opts.capture === true) {
  16307. if (opts.matchBase === true || opts.basename === true) {
  16308. match = picomatch.matchBase(input, regex, options, posix);
  16309. }
  16310. else {
  16311. match = regex.exec(output);
  16312. }
  16313. }
  16314. return { isMatch: !!match, match, output };
  16315. };
  16316. /**
  16317. * Match the basename of a filepath.
  16318. *
  16319. * ```js
  16320. * const picomatch = require('picomatch');
  16321. * // picomatch.matchBase(input, glob[, options]);
  16322. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  16323. * ```
  16324. * @param {String} `input` String to test.
  16325. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  16326. * @return {Boolean}
  16327. * @api public
  16328. */
  16329. picomatch.matchBase = (input, glob, options, posix = utils$2.isWindows(options)) => {
  16330. let regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
  16331. return regex.test(path.basename(input));
  16332. };
  16333. /**
  16334. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  16335. *
  16336. * ```js
  16337. * const picomatch = require('picomatch');
  16338. * // picomatch.isMatch(string, patterns[, options]);
  16339. *
  16340. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  16341. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  16342. * ```
  16343. * @param {String|Array} str The string to test.
  16344. * @param {String|Array} patterns One or more glob patterns to use for matching.
  16345. * @param {Object} [options] See available [options](#options).
  16346. * @return {Boolean} Returns true if any patterns match `str`
  16347. * @api public
  16348. */
  16349. picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
  16350. /**
  16351. * Parse a glob pattern to create the source string for a regular
  16352. * expression.
  16353. *
  16354. * ```js
  16355. * const picomatch = require('picomatch');
  16356. * const result = picomatch.parse(glob[, options]);
  16357. * ```
  16358. * @param {String} `glob`
  16359. * @param {Object} `options`
  16360. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  16361. * @api public
  16362. */
  16363. picomatch.parse = (glob, options) => parse_1$1(glob, options);
  16364. /**
  16365. * Scan a glob pattern to separate the pattern into segments.
  16366. *
  16367. * ```js
  16368. * const picomatch = require('picomatch');
  16369. * // picomatch.scan(input[, options]);
  16370. *
  16371. * const result = picomatch.scan('!./foo/*.js');
  16372. * console.log(result);
  16373. * // { prefix: '!./',
  16374. * // input: '!./foo/*.js',
  16375. * // base: 'foo',
  16376. * // glob: '*.js',
  16377. * // negated: true,
  16378. * // isGlob: true }
  16379. * ```
  16380. * @param {String} `input` Glob pattern to scan.
  16381. * @param {Object} `options`
  16382. * @return {Object} Returns an object with
  16383. * @api public
  16384. */
  16385. picomatch.scan = (input, options) => scan(input, options);
  16386. /**
  16387. * Create a regular expression from a glob pattern.
  16388. *
  16389. * ```js
  16390. * const picomatch = require('picomatch');
  16391. * // picomatch.makeRe(input[, options]);
  16392. *
  16393. * console.log(picomatch.makeRe('*.js'));
  16394. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  16395. * ```
  16396. * @param {String} `input` A glob pattern to convert to regex.
  16397. * @param {Object} `options`
  16398. * @return {RegExp} Returns a regex created from the given pattern.
  16399. * @api public
  16400. */
  16401. picomatch.makeRe = (input, options, returnOutput = false, returnState = false) => {
  16402. if (!input || typeof input !== 'string') {
  16403. throw new TypeError('Expected a non-empty string');
  16404. }
  16405. let opts = options || {};
  16406. let prepend = opts.contains ? '' : '^';
  16407. let append = opts.contains ? '' : '$';
  16408. let state = { negated: false, fastpaths: true };
  16409. let prefix = '';
  16410. let output;
  16411. if (input.startsWith('./')) {
  16412. input = input.slice(2);
  16413. prefix = state.prefix = './';
  16414. }
  16415. if (opts.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  16416. output = parse_1$1.fastpaths(input, options);
  16417. }
  16418. if (output === void 0) {
  16419. state = picomatch.parse(input, options);
  16420. state.prefix = prefix + (state.prefix || '');
  16421. output = state.output;
  16422. }
  16423. if (returnOutput === true) {
  16424. return output;
  16425. }
  16426. let source = `${prepend}(?:${output})${append}`;
  16427. if (state && state.negated === true) {
  16428. source = `^(?!${source}).*$`;
  16429. }
  16430. let regex = picomatch.toRegex(source, options);
  16431. if (returnState === true) {
  16432. regex.state = state;
  16433. }
  16434. return regex;
  16435. };
  16436. /**
  16437. * Create a regular expression from the given regex source string.
  16438. *
  16439. * ```js
  16440. * const picomatch = require('picomatch');
  16441. * // picomatch.toRegex(source[, options]);
  16442. *
  16443. * const { output } = picomatch.parse('*.js');
  16444. * console.log(picomatch.toRegex(output));
  16445. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  16446. * ```
  16447. * @param {String} `source` Regular expression source string.
  16448. * @param {Object} `options`
  16449. * @return {RegExp}
  16450. * @api public
  16451. */
  16452. picomatch.toRegex = (source, options) => {
  16453. try {
  16454. let opts = options || {};
  16455. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  16456. }
  16457. catch (err) {
  16458. if (options && options.debug === true)
  16459. throw err;
  16460. return /$^/;
  16461. }
  16462. };
  16463. /**
  16464. * Picomatch constants.
  16465. * @return {Object}
  16466. */
  16467. picomatch.constants = constants$1;
  16468. /**
  16469. * Expose "picomatch"
  16470. */
  16471. var picomatch_1 = picomatch;
  16472. var picomatch$1 = picomatch_1;
  16473. const isEmptyString = val => typeof val === 'string' && (val === '' || val === './');
  16474. /**
  16475. * Returns an array of strings that match one or more glob patterns.
  16476. *
  16477. * ```js
  16478. * const mm = require('micromatch');
  16479. * // mm(list, patterns[, options]);
  16480. *
  16481. * console.log(mm(['a.js', 'a.txt'], ['*.js']));
  16482. * //=> [ 'a.js' ]
  16483. * ```
  16484. * @param {String|Array<string>} list List of strings to match.
  16485. * @param {String|Array<string>} patterns One or more glob patterns to use for matching.
  16486. * @param {Object} options See available [options](#options)
  16487. * @return {Array} Returns an array of matches
  16488. * @summary false
  16489. * @api public
  16490. */
  16491. const micromatch = (list, patterns, options) => {
  16492. patterns = [].concat(patterns);
  16493. list = [].concat(list);
  16494. let omit = new Set();
  16495. let keep = new Set();
  16496. let items = new Set();
  16497. let negatives = 0;
  16498. let onResult = state => {
  16499. items.add(state.output);
  16500. if (options && options.onResult) {
  16501. options.onResult(state);
  16502. }
  16503. };
  16504. for (let i = 0; i < patterns.length; i++) {
  16505. let isMatch = picomatch$1(String(patterns[i]), Object.assign(Object.assign({}, options), { onResult }), true);
  16506. let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
  16507. if (negated)
  16508. negatives++;
  16509. for (let item of list) {
  16510. let matched = isMatch(item, true);
  16511. let match = negated ? !matched.isMatch : matched.isMatch;
  16512. if (!match)
  16513. continue;
  16514. if (negated) {
  16515. omit.add(matched.output);
  16516. }
  16517. else {
  16518. omit.delete(matched.output);
  16519. keep.add(matched.output);
  16520. }
  16521. }
  16522. }
  16523. let result = negatives === patterns.length ? [...items] : [...keep];
  16524. let matches = result.filter(item => !omit.has(item));
  16525. if (options && matches.length === 0) {
  16526. if (options.failglob === true) {
  16527. throw new Error(`No matches found for "${patterns.join(', ')}"`);
  16528. }
  16529. if (options.nonull === true || options.nullglob === true) {
  16530. return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;
  16531. }
  16532. }
  16533. return matches;
  16534. };
  16535. /**
  16536. * Backwards compatibility
  16537. */
  16538. micromatch.match = micromatch;
  16539. /**
  16540. * Returns a matcher function from the given glob `pattern` and `options`.
  16541. * The returned function takes a string to match as its only argument and returns
  16542. * true if the string is a match.
  16543. *
  16544. * ```js
  16545. * const mm = require('micromatch');
  16546. * // mm.matcher(pattern[, options]);
  16547. *
  16548. * const isMatch = mm.matcher('*.!(*a)');
  16549. * console.log(isMatch('a.a')); //=> false
  16550. * console.log(isMatch('a.b')); //=> true
  16551. * ```
  16552. * @param {String} `pattern` Glob pattern
  16553. * @param {Object} `options`
  16554. * @return {Function} Returns a matcher function.
  16555. * @api public
  16556. */
  16557. micromatch.matcher = (pattern, options) => picomatch$1(pattern, options);
  16558. /**
  16559. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  16560. *
  16561. * ```js
  16562. * const mm = require('micromatch');
  16563. * // mm.isMatch(string, patterns[, options]);
  16564. *
  16565. * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
  16566. * console.log(mm.isMatch('a.a', 'b.*')); //=> false
  16567. * ```
  16568. * @param {String} str The string to test.
  16569. * @param {String|Array} patterns One or more glob patterns to use for matching.
  16570. * @param {Object} [options] See available [options](#options).
  16571. * @return {Boolean} Returns true if any patterns match `str`
  16572. * @api public
  16573. */
  16574. micromatch.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);
  16575. /**
  16576. * Backwards compatibility
  16577. */
  16578. micromatch.any = micromatch.isMatch;
  16579. /**
  16580. * Returns a list of strings that _**do not match any**_ of the given `patterns`.
  16581. *
  16582. * ```js
  16583. * const mm = require('micromatch');
  16584. * // mm.not(list, patterns[, options]);
  16585. *
  16586. * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
  16587. * //=> ['b.b', 'c.c']
  16588. * ```
  16589. * @param {Array} `list` Array of strings to match.
  16590. * @param {String|Array} `patterns` One or more glob pattern to use for matching.
  16591. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  16592. * @return {Array} Returns an array of strings that **do not match** the given patterns.
  16593. * @api public
  16594. */
  16595. micromatch.not = (list, patterns, options = {}) => {
  16596. patterns = [].concat(patterns).map(String);
  16597. let result = new Set();
  16598. let items = [];
  16599. let onResult = state => {
  16600. if (options.onResult)
  16601. options.onResult(state);
  16602. items.push(state.output);
  16603. };
  16604. let matches = micromatch(list, patterns, Object.assign(Object.assign({}, options), { onResult }));
  16605. for (let item of items) {
  16606. if (!matches.includes(item)) {
  16607. result.add(item);
  16608. }
  16609. }
  16610. return [...result];
  16611. };
  16612. /**
  16613. * Returns true if the given `string` contains the given pattern. Similar
  16614. * to [.isMatch](#isMatch) but the pattern can match any part of the string.
  16615. *
  16616. * ```js
  16617. * var mm = require('micromatch');
  16618. * // mm.contains(string, pattern[, options]);
  16619. *
  16620. * console.log(mm.contains('aa/bb/cc', '*b'));
  16621. * //=> true
  16622. * console.log(mm.contains('aa/bb/cc', '*d'));
  16623. * //=> false
  16624. * ```
  16625. * @param {String} `str` The string to match.
  16626. * @param {String|Array} `patterns` Glob pattern to use for matching.
  16627. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  16628. * @return {Boolean} Returns true if the patter matches any part of `str`.
  16629. * @api public
  16630. */
  16631. micromatch.contains = (str, pattern, options) => {
  16632. if (typeof str !== 'string') {
  16633. throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
  16634. }
  16635. if (Array.isArray(pattern)) {
  16636. return pattern.some(p => micromatch.contains(str, p, options));
  16637. }
  16638. if (typeof pattern === 'string') {
  16639. if (isEmptyString(str) || isEmptyString(pattern)) {
  16640. return false;
  16641. }
  16642. if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) {
  16643. return true;
  16644. }
  16645. }
  16646. return micromatch.isMatch(str, pattern, Object.assign(Object.assign({}, options), { contains: true }));
  16647. };
  16648. /**
  16649. * Filter the keys of the given object with the given `glob` pattern
  16650. * and `options`. Does not attempt to match nested keys. If you need this feature,
  16651. * use [glob-object][] instead.
  16652. *
  16653. * ```js
  16654. * const mm = require('micromatch');
  16655. * // mm.matchKeys(object, patterns[, options]);
  16656. *
  16657. * const obj = { aa: 'a', ab: 'b', ac: 'c' };
  16658. * console.log(mm.matchKeys(obj, '*b'));
  16659. * //=> { ab: 'b' }
  16660. * ```
  16661. * @param {Object} `object` The object with keys to filter.
  16662. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  16663. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  16664. * @return {Object} Returns an object with only keys that match the given patterns.
  16665. * @api public
  16666. */
  16667. micromatch.matchKeys = (obj, patterns, options) => {
  16668. if (!utils$2.isObject(obj)) {
  16669. throw new TypeError('Expected the first argument to be an object');
  16670. }
  16671. let keys = micromatch(Object.keys(obj), patterns, options);
  16672. let res = {};
  16673. for (let key of keys)
  16674. res[key] = obj[key];
  16675. return res;
  16676. };
  16677. /**
  16678. * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
  16679. *
  16680. * ```js
  16681. * const mm = require('micromatch');
  16682. * // mm.some(list, patterns[, options]);
  16683. *
  16684. * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
  16685. * // true
  16686. * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
  16687. * // false
  16688. * ```
  16689. * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
  16690. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  16691. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  16692. * @return {Boolean} Returns true if any patterns match `str`
  16693. * @api public
  16694. */
  16695. micromatch.some = (list, patterns, options) => {
  16696. let items = [].concat(list);
  16697. for (let pattern of [].concat(patterns)) {
  16698. let isMatch = picomatch$1(String(pattern), options);
  16699. if (items.some(item => isMatch(item))) {
  16700. return true;
  16701. }
  16702. }
  16703. return false;
  16704. };
  16705. /**
  16706. * Returns true if every string in the given `list` matches
  16707. * any of the given glob `patterns`.
  16708. *
  16709. * ```js
  16710. * const mm = require('micromatch');
  16711. * // mm.every(list, patterns[, options]);
  16712. *
  16713. * console.log(mm.every('foo.js', ['foo.js']));
  16714. * // true
  16715. * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
  16716. * // true
  16717. * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
  16718. * // false
  16719. * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
  16720. * // false
  16721. * ```
  16722. * @param {String|Array} `list` The string or array of strings to test.
  16723. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  16724. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  16725. * @return {Boolean} Returns true if any patterns match `str`
  16726. * @api public
  16727. */
  16728. micromatch.every = (list, patterns, options) => {
  16729. let items = [].concat(list);
  16730. for (let pattern of [].concat(patterns)) {
  16731. let isMatch = picomatch$1(String(pattern), options);
  16732. if (!items.every(item => isMatch(item))) {
  16733. return false;
  16734. }
  16735. }
  16736. return true;
  16737. };
  16738. /**
  16739. * Returns true if **all** of the given `patterns` match
  16740. * the specified string.
  16741. *
  16742. * ```js
  16743. * const mm = require('micromatch');
  16744. * // mm.all(string, patterns[, options]);
  16745. *
  16746. * console.log(mm.all('foo.js', ['foo.js']));
  16747. * // true
  16748. *
  16749. * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
  16750. * // false
  16751. *
  16752. * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
  16753. * // true
  16754. *
  16755. * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
  16756. * // true
  16757. * ```
  16758. * @param {String|Array} `str` The string to test.
  16759. * @param {String|Array} `patterns` One or more glob patterns to use for matching.
  16760. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  16761. * @return {Boolean} Returns true if any patterns match `str`
  16762. * @api public
  16763. */
  16764. micromatch.all = (str, patterns, options) => {
  16765. if (typeof str !== 'string') {
  16766. throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
  16767. }
  16768. return [].concat(patterns).every(p => picomatch$1(p, options)(str));
  16769. };
  16770. /**
  16771. * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
  16772. *
  16773. * ```js
  16774. * const mm = require('micromatch');
  16775. * // mm.capture(pattern, string[, options]);
  16776. *
  16777. * console.log(mm.capture('test/*.js', 'test/foo.js'));
  16778. * //=> ['foo']
  16779. * console.log(mm.capture('test/*.js', 'foo/bar.css'));
  16780. * //=> null
  16781. * ```
  16782. * @param {String} `glob` Glob pattern to use for matching.
  16783. * @param {String} `input` String to match
  16784. * @param {Object} `options` See available [options](#options) for changing how matches are performed
  16785. * @return {Boolean} Returns an array of captures if the input matches the glob pattern, otherwise `null`.
  16786. * @api public
  16787. */
  16788. micromatch.capture = (glob, input, options) => {
  16789. let posix = utils$2.isWindows(options);
  16790. let regex = picomatch$1.makeRe(String(glob), Object.assign(Object.assign({}, options), { capture: true }));
  16791. let match = regex.exec(posix ? utils$2.toPosixSlashes(input) : input);
  16792. if (match) {
  16793. return match.slice(1).map(v => v === void 0 ? '' : v);
  16794. }
  16795. };
  16796. /**
  16797. * Create a regular expression from the given glob `pattern`.
  16798. *
  16799. * ```js
  16800. * const mm = require('micromatch');
  16801. * // mm.makeRe(pattern[, options]);
  16802. *
  16803. * console.log(mm.makeRe('*.js'));
  16804. * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
  16805. * ```
  16806. * @param {String} `pattern` A glob pattern to convert to regex.
  16807. * @param {Object} `options`
  16808. * @return {RegExp} Returns a regex created from the given pattern.
  16809. * @api public
  16810. */
  16811. micromatch.makeRe = (...args) => picomatch$1.makeRe(...args);
  16812. /**
  16813. * Scan a glob pattern to separate the pattern into segments. Used
  16814. * by the [split](#split) method.
  16815. *
  16816. * ```js
  16817. * const mm = require('micromatch');
  16818. * const state = mm.scan(pattern[, options]);
  16819. * ```
  16820. * @param {String} `pattern`
  16821. * @param {Object} `options`
  16822. * @return {Object} Returns an object with
  16823. * @api public
  16824. */
  16825. micromatch.scan = (...args) => picomatch$1.scan(...args);
  16826. /**
  16827. * Parse a glob pattern to create the source string for a regular
  16828. * expression.
  16829. *
  16830. * ```js
  16831. * const mm = require('micromatch');
  16832. * const state = mm(pattern[, options]);
  16833. * ```
  16834. * @param {String} `glob`
  16835. * @param {Object} `options`
  16836. * @return {Object} Returns an object with useful properties and output to be used as regex source string.
  16837. * @api public
  16838. */
  16839. micromatch.parse = (patterns, options) => {
  16840. let res = [];
  16841. for (let pattern of [].concat(patterns || [])) {
  16842. for (let str of braces_1(String(pattern), options)) {
  16843. res.push(picomatch$1.parse(str, options));
  16844. }
  16845. }
  16846. return res;
  16847. };
  16848. /**
  16849. * Process the given brace `pattern`.
  16850. *
  16851. * ```js
  16852. * const { braces } = require('micromatch');
  16853. * console.log(braces('foo/{a,b,c}/bar'));
  16854. * //=> [ 'foo/(a|b|c)/bar' ]
  16855. *
  16856. * console.log(braces('foo/{a,b,c}/bar', { expand: true }));
  16857. * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
  16858. * ```
  16859. * @param {String} `pattern` String with brace pattern to process.
  16860. * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
  16861. * @return {Array}
  16862. * @api public
  16863. */
  16864. micromatch.braces = (pattern, options) => {
  16865. if (typeof pattern !== 'string')
  16866. throw new TypeError('Expected a string');
  16867. if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) {
  16868. return [pattern];
  16869. }
  16870. return braces_1(pattern, options);
  16871. };
  16872. /**
  16873. * Expand braces
  16874. */
  16875. micromatch.braceExpand = (pattern, options) => {
  16876. if (typeof pattern !== 'string')
  16877. throw new TypeError('Expected a string');
  16878. return micromatch.braces(pattern, Object.assign(Object.assign({}, options), { expand: true }));
  16879. };
  16880. /**
  16881. * Expose micromatch
  16882. */
  16883. var micromatch_1 = micromatch;
  16884. function ensureArray$1(thing) {
  16885. if (Array.isArray(thing))
  16886. return thing;
  16887. if (thing == undefined)
  16888. return [];
  16889. return [thing];
  16890. }
  16891. function getMatcherString(id, resolutionBase) {
  16892. if (resolutionBase === false) {
  16893. return id;
  16894. }
  16895. return path.resolve(...(typeof resolutionBase === 'string' ? [resolutionBase, id] : [id]));
  16896. }
  16897. const createFilter = function createFilter(include, exclude, options) {
  16898. const resolutionBase = options && options.resolve;
  16899. const getMatcher = (id) => {
  16900. return id instanceof RegExp
  16901. ? id
  16902. : {
  16903. test: micromatch_1.matcher(getMatcherString(id, resolutionBase)
  16904. .split(path.sep)
  16905. .join('/'), { dot: true })
  16906. };
  16907. };
  16908. const includeMatchers = ensureArray$1(include).map(getMatcher);
  16909. const excludeMatchers = ensureArray$1(exclude).map(getMatcher);
  16910. return function (id) {
  16911. if (typeof id !== 'string')
  16912. return false;
  16913. if (/\0/.test(id))
  16914. return false;
  16915. id = id.split(path.sep).join('/');
  16916. for (let i = 0; i < excludeMatchers.length; ++i) {
  16917. const matcher = excludeMatchers[i];
  16918. if (matcher.test(id))
  16919. return false;
  16920. }
  16921. for (let i = 0; i < includeMatchers.length; ++i) {
  16922. const matcher = includeMatchers[i];
  16923. if (matcher.test(id))
  16924. return true;
  16925. }
  16926. return !includeMatchers.length;
  16927. };
  16928. };
  16929. var modules = {};
  16930. var getModule = function (dir) {
  16931. var rootPath = dir ? path.resolve(dir) : process.cwd();
  16932. var rootName = path.join(rootPath, '@root');
  16933. var root = modules[rootName];
  16934. if (!root) {
  16935. root = new module$1(rootName);
  16936. root.filename = rootName;
  16937. root.paths = module$1._nodeModulePaths(rootPath);
  16938. modules[rootName] = root;
  16939. }
  16940. return root;
  16941. };
  16942. var requireRelative = function (requested, relativeTo) {
  16943. var root = getModule(relativeTo);
  16944. return root.require(requested);
  16945. };
  16946. requireRelative.resolve = function (requested, relativeTo) {
  16947. var root = getModule(relativeTo);
  16948. return module$1._resolveFilename(requested, root);
  16949. };
  16950. var requireRelative_1 = requireRelative;
  16951. let chokidar;
  16952. try {
  16953. chokidar = requireRelative_1('chokidar', process.cwd());
  16954. }
  16955. catch (err) {
  16956. chokidar = null;
  16957. }
  16958. var chokidar$1 = chokidar;
  16959. const opts = { encoding: 'utf-8', persistent: true };
  16960. const watchers = new Map();
  16961. function addTask(id, task, chokidarOptions, chokidarOptionsHash, isTransformDependency) {
  16962. if (!watchers.has(chokidarOptionsHash))
  16963. watchers.set(chokidarOptionsHash, new Map());
  16964. const group = watchers.get(chokidarOptionsHash);
  16965. const watcher = group.get(id) || new FileWatcher(id, chokidarOptions, group);
  16966. if (!watcher.fsWatcher) {
  16967. if (isTransformDependency)
  16968. throw new Error(`Transform dependency ${id} does not exist.`);
  16969. }
  16970. else {
  16971. watcher.addTask(task, isTransformDependency);
  16972. }
  16973. }
  16974. function deleteTask(id, target, chokidarOptionsHash) {
  16975. const group = watchers.get(chokidarOptionsHash);
  16976. const watcher = group.get(id);
  16977. if (watcher)
  16978. watcher.deleteTask(target, group);
  16979. }
  16980. class FileWatcher {
  16981. constructor(id, chokidarOptions, group) {
  16982. this.id = id;
  16983. this.tasks = new Set();
  16984. this.transformDependencyTasks = new Set();
  16985. let modifiedTime;
  16986. try {
  16987. const stats = fs.statSync(id);
  16988. modifiedTime = +stats.mtime;
  16989. }
  16990. catch (err) {
  16991. if (err.code === 'ENOENT') {
  16992. // can't watch files that don't exist (e.g. injected
  16993. // by plugins somehow)
  16994. return;
  16995. }
  16996. throw err;
  16997. }
  16998. const handleWatchEvent = (event) => {
  16999. if (event === 'rename' || event === 'unlink') {
  17000. this.close();
  17001. group.delete(id);
  17002. this.trigger(id);
  17003. return;
  17004. }
  17005. else {
  17006. let stats;
  17007. try {
  17008. stats = fs.statSync(id);
  17009. }
  17010. catch (err) {
  17011. if (err.code === 'ENOENT') {
  17012. modifiedTime = -1;
  17013. this.trigger(id);
  17014. return;
  17015. }
  17016. throw err;
  17017. }
  17018. // debounce
  17019. if (+stats.mtime - modifiedTime > 15)
  17020. this.trigger(id);
  17021. }
  17022. };
  17023. this.fsWatcher = chokidarOptions
  17024. ? chokidar$1.watch(id, chokidarOptions).on('all', handleWatchEvent)
  17025. : fs.watch(id, opts, handleWatchEvent);
  17026. group.set(id, this);
  17027. }
  17028. addTask(task, isTransformDependency) {
  17029. if (isTransformDependency)
  17030. this.transformDependencyTasks.add(task);
  17031. else
  17032. this.tasks.add(task);
  17033. }
  17034. close() {
  17035. if (this.fsWatcher)
  17036. this.fsWatcher.close();
  17037. }
  17038. deleteTask(task, group) {
  17039. let deleted = this.tasks.delete(task);
  17040. deleted = this.transformDependencyTasks.delete(task) || deleted;
  17041. if (deleted && this.tasks.size === 0 && this.transformDependencyTasks.size === 0) {
  17042. group.delete(this.id);
  17043. this.close();
  17044. }
  17045. }
  17046. trigger(id) {
  17047. for (const task of this.tasks) {
  17048. task.invalidate(id, false);
  17049. }
  17050. for (const task of this.transformDependencyTasks) {
  17051. task.invalidate(id, true);
  17052. }
  17053. }
  17054. }
  17055. const DELAY = 200;
  17056. class Watcher {
  17057. constructor(configs) {
  17058. this.buildTimeout = null;
  17059. this.invalidatedIds = new Set();
  17060. this.rerun = false;
  17061. this.emitter = new (class extends events.EventEmitter {
  17062. constructor(close) {
  17063. super();
  17064. this.close = close;
  17065. // Allows more than 10 bundles to be watched without
  17066. // showing the `MaxListenersExceededWarning` to the user.
  17067. this.setMaxListeners(Infinity);
  17068. }
  17069. })(this.close.bind(this));
  17070. this.tasks = (Array.isArray(configs) ? configs : configs ? [configs] : []).map(config => new Task(this, config));
  17071. this.running = true;
  17072. process.nextTick(() => this.run());
  17073. }
  17074. close() {
  17075. if (this.buildTimeout)
  17076. clearTimeout(this.buildTimeout);
  17077. for (const task of this.tasks) {
  17078. task.close();
  17079. }
  17080. this.emitter.removeAllListeners();
  17081. }
  17082. emit(event, value) {
  17083. this.emitter.emit(event, value);
  17084. }
  17085. invalidate(id) {
  17086. if (id) {
  17087. this.invalidatedIds.add(id);
  17088. }
  17089. if (this.running) {
  17090. this.rerun = true;
  17091. return;
  17092. }
  17093. if (this.buildTimeout)
  17094. clearTimeout(this.buildTimeout);
  17095. this.buildTimeout = setTimeout(() => {
  17096. this.buildTimeout = null;
  17097. for (const id of this.invalidatedIds) {
  17098. this.emit('change', id);
  17099. }
  17100. this.invalidatedIds.clear();
  17101. this.emit('restart');
  17102. this.run();
  17103. }, DELAY);
  17104. }
  17105. run() {
  17106. this.running = true;
  17107. this.emit('event', {
  17108. code: 'START'
  17109. });
  17110. let taskPromise = Promise.resolve();
  17111. for (const task of this.tasks)
  17112. taskPromise = taskPromise.then(() => task.run());
  17113. return taskPromise
  17114. .then(() => {
  17115. this.running = false;
  17116. this.emit('event', {
  17117. code: 'END'
  17118. });
  17119. })
  17120. .catch(error => {
  17121. this.running = false;
  17122. this.emit('event', {
  17123. code: 'ERROR',
  17124. error
  17125. });
  17126. })
  17127. .then(() => {
  17128. if (this.rerun) {
  17129. this.rerun = false;
  17130. this.invalidate();
  17131. }
  17132. });
  17133. }
  17134. }
  17135. class Task {
  17136. constructor(watcher, config) {
  17137. this.cache = { modules: [] };
  17138. this.watchFiles = [];
  17139. this.invalidated = true;
  17140. this.watcher = watcher;
  17141. this.closed = false;
  17142. this.watched = new Set();
  17143. const { inputOptions, outputOptions } = mergeOptions({
  17144. config
  17145. });
  17146. this.inputOptions = inputOptions;
  17147. this.outputs = outputOptions;
  17148. this.outputFiles = this.outputs.map(output => {
  17149. if (output.file || output.dir)
  17150. return path.resolve(output.file || output.dir);
  17151. return undefined;
  17152. });
  17153. const watchOptions = inputOptions.watch || {};
  17154. if ('useChokidar' in watchOptions)
  17155. watchOptions.chokidar = watchOptions.useChokidar;
  17156. let chokidarOptions = 'chokidar' in watchOptions ? watchOptions.chokidar : !!chokidar$1;
  17157. if (chokidarOptions) {
  17158. chokidarOptions = Object.assign(Object.assign({}, (chokidarOptions === true ? {} : chokidarOptions)), { disableGlobbing: true, ignoreInitial: true });
  17159. }
  17160. if (chokidarOptions && !chokidar$1) {
  17161. throw new Error(`watch.chokidar was provided, but chokidar could not be found. Have you installed it?`);
  17162. }
  17163. this.chokidarOptions = chokidarOptions;
  17164. this.chokidarOptionsHash = JSON.stringify(chokidarOptions);
  17165. this.filter = createFilter(watchOptions.include, watchOptions.exclude);
  17166. }
  17167. close() {
  17168. this.closed = true;
  17169. for (const id of this.watched) {
  17170. deleteTask(id, this, this.chokidarOptionsHash);
  17171. }
  17172. }
  17173. invalidate(id, isTransformDependency) {
  17174. this.invalidated = true;
  17175. if (isTransformDependency) {
  17176. for (const module of this.cache.modules) {
  17177. if (module.transformDependencies.indexOf(id) === -1)
  17178. continue;
  17179. // effective invalidation
  17180. module.originalCode = null;
  17181. }
  17182. }
  17183. this.watcher.invalidate(id);
  17184. }
  17185. run() {
  17186. if (!this.invalidated)
  17187. return;
  17188. this.invalidated = false;
  17189. const options = Object.assign(Object.assign({}, this.inputOptions), { cache: this.cache });
  17190. const start = Date.now();
  17191. this.watcher.emit('event', {
  17192. code: 'BUNDLE_START',
  17193. input: this.inputOptions.input,
  17194. output: this.outputFiles
  17195. });
  17196. setWatcher(this.watcher.emitter);
  17197. return rollup(options)
  17198. .then(result => {
  17199. if (this.closed)
  17200. return undefined;
  17201. this.updateWatchedFiles(result);
  17202. return Promise.all(this.outputs.map(output => result.write(output))).then(() => result);
  17203. })
  17204. .then((result) => {
  17205. this.watcher.emit('event', {
  17206. code: 'BUNDLE_END',
  17207. duration: Date.now() - start,
  17208. input: this.inputOptions.input,
  17209. output: this.outputFiles,
  17210. result
  17211. });
  17212. })
  17213. .catch((error) => {
  17214. if (this.closed)
  17215. return;
  17216. if (Array.isArray(error.watchFiles)) {
  17217. for (const id of error.watchFiles) {
  17218. this.watchFile(id);
  17219. }
  17220. }
  17221. if (error.id) {
  17222. this.cache.modules = this.cache.modules.filter(module => module.id !== error.id);
  17223. }
  17224. throw error;
  17225. });
  17226. }
  17227. updateWatchedFiles(result) {
  17228. const previouslyWatched = this.watched;
  17229. this.watched = new Set();
  17230. this.watchFiles = result.watchFiles;
  17231. this.cache = result.cache;
  17232. for (const id of this.watchFiles) {
  17233. this.watchFile(id);
  17234. }
  17235. for (const module of this.cache.modules) {
  17236. for (const depId of module.transformDependencies) {
  17237. this.watchFile(depId, true);
  17238. }
  17239. }
  17240. for (const id of previouslyWatched) {
  17241. if (!this.watched.has(id))
  17242. deleteTask(id, this, this.chokidarOptionsHash);
  17243. }
  17244. }
  17245. watchFile(id, isTransformDependency = false) {
  17246. if (!this.filter(id))
  17247. return;
  17248. this.watched.add(id);
  17249. if (this.outputFiles.some(file => file === id)) {
  17250. throw new Error('Cannot import the generated bundle');
  17251. }
  17252. // this is necessary to ensure that any 'renamed' files
  17253. // continue to be watched following an error
  17254. addTask(id, this, this.chokidarOptions, this.chokidarOptionsHash, isTransformDependency);
  17255. }
  17256. }
  17257. function watch(configs) {
  17258. return new Watcher(configs).emitter;
  17259. }
  17260. exports.__awaiter = __awaiter;
  17261. exports.commandAliases = commandAliases;
  17262. exports.createCommonjsModule = createCommonjsModule;
  17263. exports.getAliasName = getAliasName;
  17264. exports.mergeOptions = mergeOptions;
  17265. exports.relative = requireRelative_1;
  17266. exports.relativeId = relativeId;
  17267. exports.rollup = rollup;
  17268. exports.version = version;
  17269. exports.watch = watch;
  17270. //# sourceMappingURL=node-entry.js.map