compiler-sfc.esm-browser.js 1.5 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828
  1. /**
  2. * Make a map and return a function for checking if a key
  3. * is in that map.
  4. * IMPORTANT: all calls of this function must be prefixed with
  5. * \/\*#\_\_PURE\_\_\*\/
  6. * So that rollup can tree-shake them if necessary.
  7. */
  8. function makeMap(str, expectsLowerCase) {
  9. const map = Object.create(null);
  10. const list = str.split(',');
  11. for (let i = 0; i < list.length; i++) {
  12. map[list[i]] = true;
  13. }
  14. return expectsLowerCase ? val => !!map[val.toLowerCase()] : val => !!map[val];
  15. }
  16. /**
  17. * dev only flag -> name mapping
  18. */
  19. const PatchFlagNames = {
  20. [1 /* PatchFlags.TEXT */]: `TEXT`,
  21. [2 /* PatchFlags.CLASS */]: `CLASS`,
  22. [4 /* PatchFlags.STYLE */]: `STYLE`,
  23. [8 /* PatchFlags.PROPS */]: `PROPS`,
  24. [16 /* PatchFlags.FULL_PROPS */]: `FULL_PROPS`,
  25. [32 /* PatchFlags.HYDRATE_EVENTS */]: `HYDRATE_EVENTS`,
  26. [64 /* PatchFlags.STABLE_FRAGMENT */]: `STABLE_FRAGMENT`,
  27. [128 /* PatchFlags.KEYED_FRAGMENT */]: `KEYED_FRAGMENT`,
  28. [256 /* PatchFlags.UNKEYED_FRAGMENT */]: `UNKEYED_FRAGMENT`,
  29. [512 /* PatchFlags.NEED_PATCH */]: `NEED_PATCH`,
  30. [1024 /* PatchFlags.DYNAMIC_SLOTS */]: `DYNAMIC_SLOTS`,
  31. [2048 /* PatchFlags.DEV_ROOT_FRAGMENT */]: `DEV_ROOT_FRAGMENT`,
  32. [-1 /* PatchFlags.HOISTED */]: `HOISTED`,
  33. [-2 /* PatchFlags.BAIL */]: `BAIL`
  34. };
  35. /**
  36. * Dev only
  37. */
  38. const slotFlagsText = {
  39. [1 /* SlotFlags.STABLE */]: 'STABLE',
  40. [2 /* SlotFlags.DYNAMIC */]: 'DYNAMIC',
  41. [3 /* SlotFlags.FORWARDED */]: 'FORWARDED'
  42. };
  43. const GLOBALS_WHITE_LISTED = 'Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,' +
  44. 'decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,' +
  45. 'Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt';
  46. const isGloballyWhitelisted = /*#__PURE__*/ makeMap(GLOBALS_WHITE_LISTED);
  47. const range = 2;
  48. function generateCodeFrame(source, start = 0, end = source.length) {
  49. // Split the content into individual lines but capture the newline sequence
  50. // that separated each line. This is important because the actual sequence is
  51. // needed to properly take into account the full line length for offset
  52. // comparison
  53. let lines = source.split(/(\r?\n)/);
  54. // Separate the lines and newline sequences into separate arrays for easier referencing
  55. const newlineSequences = lines.filter((_, idx) => idx % 2 === 1);
  56. lines = lines.filter((_, idx) => idx % 2 === 0);
  57. let count = 0;
  58. const res = [];
  59. for (let i = 0; i < lines.length; i++) {
  60. count +=
  61. lines[i].length +
  62. ((newlineSequences[i] && newlineSequences[i].length) || 0);
  63. if (count >= start) {
  64. for (let j = i - range; j <= i + range || end > count; j++) {
  65. if (j < 0 || j >= lines.length)
  66. continue;
  67. const line = j + 1;
  68. res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
  69. const lineLength = lines[j].length;
  70. const newLineSeqLength = (newlineSequences[j] && newlineSequences[j].length) || 0;
  71. if (j === i) {
  72. // push underline
  73. const pad = start - (count - (lineLength + newLineSeqLength));
  74. const length = Math.max(1, end > count ? lineLength - pad : end - start);
  75. res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
  76. }
  77. else if (j > i) {
  78. if (end > count) {
  79. const length = Math.max(Math.min(end - count, lineLength), 1);
  80. res.push(` | ` + '^'.repeat(length));
  81. }
  82. count += lineLength + newLineSeqLength;
  83. }
  84. }
  85. break;
  86. }
  87. }
  88. return res.join('\n');
  89. }
  90. function normalizeStyle(value) {
  91. if (isArray$3(value)) {
  92. const res = {};
  93. for (let i = 0; i < value.length; i++) {
  94. const item = value[i];
  95. const normalized = isString$2(item)
  96. ? parseStringStyle(item)
  97. : normalizeStyle(item);
  98. if (normalized) {
  99. for (const key in normalized) {
  100. res[key] = normalized[key];
  101. }
  102. }
  103. }
  104. return res;
  105. }
  106. else if (isString$2(value)) {
  107. return value;
  108. }
  109. else if (isObject$2(value)) {
  110. return value;
  111. }
  112. }
  113. const listDelimiterRE = /;(?![^(]*\))/g;
  114. const propertyDelimiterRE = /:([^]+)/;
  115. const styleCommentRE = /\/\*.*?\*\//gs;
  116. function parseStringStyle(cssText) {
  117. const ret = {};
  118. cssText
  119. .replace(styleCommentRE, '')
  120. .split(listDelimiterRE)
  121. .forEach(item => {
  122. if (item) {
  123. const tmp = item.split(propertyDelimiterRE);
  124. tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
  125. }
  126. });
  127. return ret;
  128. }
  129. function stringifyStyle(styles) {
  130. let ret = '';
  131. if (!styles || isString$2(styles)) {
  132. return ret;
  133. }
  134. for (const key in styles) {
  135. const value = styles[key];
  136. const normalizedKey = key.startsWith(`--`) ? key : hyphenate(key);
  137. if (isString$2(value) || typeof value === 'number') {
  138. // only render valid values
  139. ret += `${normalizedKey}:${value};`;
  140. }
  141. }
  142. return ret;
  143. }
  144. function normalizeClass(value) {
  145. let res = '';
  146. if (isString$2(value)) {
  147. res = value;
  148. }
  149. else if (isArray$3(value)) {
  150. for (let i = 0; i < value.length; i++) {
  151. const normalized = normalizeClass(value[i]);
  152. if (normalized) {
  153. res += normalized + ' ';
  154. }
  155. }
  156. }
  157. else if (isObject$2(value)) {
  158. for (const name in value) {
  159. if (value[name]) {
  160. res += name + ' ';
  161. }
  162. }
  163. }
  164. return res.trim();
  165. }
  166. // These tag configs are shared between compiler-dom and runtime-dom, so they
  167. // https://developer.mozilla.org/en-US/docs/Web/HTML/Element
  168. const HTML_TAGS = 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +
  169. 'header,hgroup,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,' +
  170. 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +
  171. 'data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,' +
  172. 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +
  173. 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +
  174. 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +
  175. 'option,output,progress,select,textarea,details,dialog,menu,' +
  176. 'summary,template,blockquote,iframe,tfoot';
  177. // https://developer.mozilla.org/en-US/docs/Web/SVG/Element
  178. const SVG_TAGS = 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +
  179. 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +
  180. 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +
  181. 'feDistantLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +
  182. 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +
  183. 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +
  184. 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +
  185. 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +
  186. 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +
  187. 'text,textPath,title,tspan,unknown,use,view';
  188. const VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';
  189. /**
  190. * Compiler only.
  191. * Do NOT use in runtime code paths unless behind `true` flag.
  192. */
  193. const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
  194. /**
  195. * Compiler only.
  196. * Do NOT use in runtime code paths unless behind `true` flag.
  197. */
  198. const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
  199. /**
  200. * Compiler only.
  201. * Do NOT use in runtime code paths unless behind `true` flag.
  202. */
  203. const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
  204. /**
  205. * On the client we only need to offer special cases for boolean attributes that
  206. * have different names from their corresponding dom properties:
  207. * - itemscope -> N/A
  208. * - allowfullscreen -> allowFullscreen
  209. * - formnovalidate -> formNoValidate
  210. * - ismap -> isMap
  211. * - nomodule -> noModule
  212. * - novalidate -> noValidate
  213. * - readonly -> readOnly
  214. */
  215. const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
  216. /**
  217. * The full list is needed during SSR to produce the correct initial markup.
  218. */
  219. const isBooleanAttr = /*#__PURE__*/ makeMap(specialBooleanAttrs +
  220. `,async,autofocus,autoplay,controls,default,defer,disabled,hidden,` +
  221. `loop,open,required,reversed,scoped,seamless,` +
  222. `checked,muted,multiple,selected`);
  223. const unsafeAttrCharRE = /[>/="'\u0009\u000a\u000c\u0020]/;
  224. const attrValidationCache = {};
  225. function isSSRSafeAttrName(name) {
  226. if (attrValidationCache.hasOwnProperty(name)) {
  227. return attrValidationCache[name];
  228. }
  229. const isUnsafe = unsafeAttrCharRE.test(name);
  230. if (isUnsafe) {
  231. console.error(`unsafe attribute name: ${name}`);
  232. }
  233. return (attrValidationCache[name] = !isUnsafe);
  234. }
  235. const propsToAttrMap = {
  236. acceptCharset: 'accept-charset',
  237. className: 'class',
  238. htmlFor: 'for',
  239. httpEquiv: 'http-equiv'
  240. };
  241. /**
  242. * Known attributes, this is used for stringification of runtime static nodes
  243. * so that we don't stringify bindings that cannot be set from HTML.
  244. * Don't also forget to allow `data-*` and `aria-*`!
  245. * Generated from https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes
  246. */
  247. const isKnownHtmlAttr = /*#__PURE__*/ makeMap(`accept,accept-charset,accesskey,action,align,allow,alt,async,` +
  248. `autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,` +
  249. `border,buffered,capture,challenge,charset,checked,cite,class,code,` +
  250. `codebase,color,cols,colspan,content,contenteditable,contextmenu,controls,` +
  251. `coords,crossorigin,csp,data,datetime,decoding,default,defer,dir,dirname,` +
  252. `disabled,download,draggable,dropzone,enctype,enterkeyhint,for,form,` +
  253. `formaction,formenctype,formmethod,formnovalidate,formtarget,headers,` +
  254. `height,hidden,high,href,hreflang,http-equiv,icon,id,importance,integrity,` +
  255. `ismap,itemprop,keytype,kind,label,lang,language,loading,list,loop,low,` +
  256. `manifest,max,maxlength,minlength,media,min,multiple,muted,name,novalidate,` +
  257. `open,optimum,pattern,ping,placeholder,poster,preload,radiogroup,readonly,` +
  258. `referrerpolicy,rel,required,reversed,rows,rowspan,sandbox,scope,scoped,` +
  259. `selected,shape,size,sizes,slot,span,spellcheck,src,srcdoc,srclang,srcset,` +
  260. `start,step,style,summary,tabindex,target,title,translate,type,usemap,` +
  261. `value,width,wrap`);
  262. /**
  263. * Generated from https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute
  264. */
  265. const isKnownSvgAttr = /*#__PURE__*/ makeMap(`xmlns,accent-height,accumulate,additive,alignment-baseline,alphabetic,amplitude,` +
  266. `arabic-form,ascent,attributeName,attributeType,azimuth,baseFrequency,` +
  267. `baseline-shift,baseProfile,bbox,begin,bias,by,calcMode,cap-height,class,` +
  268. `clip,clipPathUnits,clip-path,clip-rule,color,color-interpolation,` +
  269. `color-interpolation-filters,color-profile,color-rendering,` +
  270. `contentScriptType,contentStyleType,crossorigin,cursor,cx,cy,d,decelerate,` +
  271. `descent,diffuseConstant,direction,display,divisor,dominant-baseline,dur,dx,` +
  272. `dy,edgeMode,elevation,enable-background,end,exponent,fill,fill-opacity,` +
  273. `fill-rule,filter,filterRes,filterUnits,flood-color,flood-opacity,` +
  274. `font-family,font-size,font-size-adjust,font-stretch,font-style,` +
  275. `font-variant,font-weight,format,from,fr,fx,fy,g1,g2,glyph-name,` +
  276. `glyph-orientation-horizontal,glyph-orientation-vertical,glyphRef,` +
  277. `gradientTransform,gradientUnits,hanging,height,href,hreflang,horiz-adv-x,` +
  278. `horiz-origin-x,id,ideographic,image-rendering,in,in2,intercept,k,k1,k2,k3,` +
  279. `k4,kernelMatrix,kernelUnitLength,kerning,keyPoints,keySplines,keyTimes,` +
  280. `lang,lengthAdjust,letter-spacing,lighting-color,limitingConeAngle,local,` +
  281. `marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,` +
  282. `mask,maskContentUnits,maskUnits,mathematical,max,media,method,min,mode,` +
  283. `name,numOctaves,offset,opacity,operator,order,orient,orientation,origin,` +
  284. `overflow,overline-position,overline-thickness,panose-1,paint-order,path,` +
  285. `pathLength,patternContentUnits,patternTransform,patternUnits,ping,` +
  286. `pointer-events,points,pointsAtX,pointsAtY,pointsAtZ,preserveAlpha,` +
  287. `preserveAspectRatio,primitiveUnits,r,radius,referrerPolicy,refX,refY,rel,` +
  288. `rendering-intent,repeatCount,repeatDur,requiredExtensions,requiredFeatures,` +
  289. `restart,result,rotate,rx,ry,scale,seed,shape-rendering,slope,spacing,` +
  290. `specularConstant,specularExponent,speed,spreadMethod,startOffset,` +
  291. `stdDeviation,stemh,stemv,stitchTiles,stop-color,stop-opacity,` +
  292. `strikethrough-position,strikethrough-thickness,string,stroke,` +
  293. `stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,` +
  294. `stroke-miterlimit,stroke-opacity,stroke-width,style,surfaceScale,` +
  295. `systemLanguage,tabindex,tableValues,target,targetX,targetY,text-anchor,` +
  296. `text-decoration,text-rendering,textLength,to,transform,transform-origin,` +
  297. `type,u1,u2,underline-position,underline-thickness,unicode,unicode-bidi,` +
  298. `unicode-range,units-per-em,v-alphabetic,v-hanging,v-ideographic,` +
  299. `v-mathematical,values,vector-effect,version,vert-adv-y,vert-origin-x,` +
  300. `vert-origin-y,viewBox,viewTarget,visibility,width,widths,word-spacing,` +
  301. `writing-mode,x,x-height,x1,x2,xChannelSelector,xlink:actuate,xlink:arcrole,` +
  302. `xlink:href,xlink:role,xlink:show,xlink:title,xlink:type,xml:base,xml:lang,` +
  303. `xml:space,y,y1,y2,yChannelSelector,z,zoomAndPan`);
  304. const escapeRE = /["'&<>]/;
  305. function escapeHtml(string) {
  306. const str = '' + string;
  307. const match = escapeRE.exec(str);
  308. if (!match) {
  309. return str;
  310. }
  311. let html = '';
  312. let escaped;
  313. let index;
  314. let lastIndex = 0;
  315. for (index = match.index; index < str.length; index++) {
  316. switch (str.charCodeAt(index)) {
  317. case 34: // "
  318. escaped = '&quot;';
  319. break;
  320. case 38: // &
  321. escaped = '&amp;';
  322. break;
  323. case 39: // '
  324. escaped = '&#39;';
  325. break;
  326. case 60: // <
  327. escaped = '&lt;';
  328. break;
  329. case 62: // >
  330. escaped = '&gt;';
  331. break;
  332. default:
  333. continue;
  334. }
  335. if (lastIndex !== index) {
  336. html += str.slice(lastIndex, index);
  337. }
  338. lastIndex = index + 1;
  339. html += escaped;
  340. }
  341. return lastIndex !== index ? html + str.slice(lastIndex, index) : html;
  342. }
  343. /**
  344. * For converting {{ interpolation }} values to displayed strings.
  345. * @private
  346. */
  347. const toDisplayString = (val) => {
  348. return isString$2(val)
  349. ? val
  350. : val == null
  351. ? ''
  352. : isArray$3(val) ||
  353. (isObject$2(val) &&
  354. (val.toString === objectToString$1 || !isFunction$1(val.toString)))
  355. ? JSON.stringify(val, replacer, 2)
  356. : String(val);
  357. };
  358. const replacer = (_key, val) => {
  359. // can't use isRef here since @vue/shared has no deps
  360. if (val && val.__v_isRef) {
  361. return replacer(_key, val.value);
  362. }
  363. else if (isMap(val)) {
  364. return {
  365. [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
  366. entries[`${key} =>`] = val;
  367. return entries;
  368. }, {})
  369. };
  370. }
  371. else if (isSet(val)) {
  372. return {
  373. [`Set(${val.size})`]: [...val.values()]
  374. };
  375. }
  376. else if (isObject$2(val) && !isArray$3(val) && !isPlainObject(val)) {
  377. return String(val);
  378. }
  379. return val;
  380. };
  381. const EMPTY_OBJ = Object.freeze({})
  382. ;
  383. const NOOP = () => { };
  384. /**
  385. * Always return false.
  386. */
  387. const NO = () => false;
  388. const onRE = /^on[^a-z]/;
  389. const isOn = (key) => onRE.test(key);
  390. const extend = Object.assign;
  391. const hasOwnProperty$3 = Object.prototype.hasOwnProperty;
  392. const hasOwn = (val, key) => hasOwnProperty$3.call(val, key);
  393. const isArray$3 = Array.isArray;
  394. const isMap = (val) => toTypeString(val) === '[object Map]';
  395. const isSet = (val) => toTypeString(val) === '[object Set]';
  396. const isFunction$1 = (val) => typeof val === 'function';
  397. const isString$2 = (val) => typeof val === 'string';
  398. const isSymbol$1 = (val) => typeof val === 'symbol';
  399. const isObject$2 = (val) => val !== null && typeof val === 'object';
  400. const objectToString$1 = Object.prototype.toString;
  401. const toTypeString = (value) => objectToString$1.call(value);
  402. const isPlainObject = (val) => toTypeString(val) === '[object Object]';
  403. const isReservedProp = /*#__PURE__*/ makeMap(
  404. // the leading comma is intentional so empty string "" is also included
  405. ',key,ref,ref_for,ref_key,' +
  406. 'onVnodeBeforeMount,onVnodeMounted,' +
  407. 'onVnodeBeforeUpdate,onVnodeUpdated,' +
  408. 'onVnodeBeforeUnmount,onVnodeUnmounted');
  409. const isBuiltInDirective = /*#__PURE__*/ makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo');
  410. const cacheStringFunction = (fn) => {
  411. const cache = Object.create(null);
  412. return ((str) => {
  413. const hit = cache[str];
  414. return hit || (cache[str] = fn(str));
  415. });
  416. };
  417. const camelizeRE = /-(\w)/g;
  418. /**
  419. * @private
  420. */
  421. const camelize = cacheStringFunction((str) => {
  422. return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
  423. });
  424. const hyphenateRE = /\B([A-Z])/g;
  425. /**
  426. * @private
  427. */
  428. const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
  429. /**
  430. * @private
  431. */
  432. const capitalize$1 = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
  433. /**
  434. * @private
  435. */
  436. const toHandlerKey = cacheStringFunction((str) => str ? `on${capitalize$1(str)}` : ``);
  437. const identRE = /^[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/;
  438. function genPropsAccessExp(name) {
  439. return identRE.test(name)
  440. ? `__props.${name}`
  441. : `__props[${JSON.stringify(name)}]`;
  442. }
  443. function defaultOnError(error) {
  444. throw error;
  445. }
  446. function defaultOnWarn(msg) {
  447. console.warn(`[Vue warn] ${msg.message}`);
  448. }
  449. function createCompilerError(code, loc, messages, additionalMessage) {
  450. const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
  451. ;
  452. const error = new SyntaxError(String(msg));
  453. error.code = code;
  454. error.loc = loc;
  455. return error;
  456. }
  457. const errorMessages = {
  458. // parse errors
  459. [0 /* ErrorCodes.ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
  460. [1 /* ErrorCodes.CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
  461. [2 /* ErrorCodes.DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
  462. [3 /* ErrorCodes.END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
  463. [4 /* ErrorCodes.END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
  464. [5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
  465. [6 /* ErrorCodes.EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
  466. [7 /* ErrorCodes.EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
  467. [8 /* ErrorCodes.EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
  468. [9 /* ErrorCodes.EOF_IN_TAG */]: 'Unexpected EOF in tag.',
  469. [10 /* ErrorCodes.INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
  470. [11 /* ErrorCodes.INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
  471. [12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
  472. [13 /* ErrorCodes.MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
  473. [14 /* ErrorCodes.MISSING_END_TAG_NAME */]: 'End tag name was expected.',
  474. [15 /* ErrorCodes.MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
  475. [16 /* ErrorCodes.NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
  476. [17 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
  477. [18 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
  478. [19 /* ErrorCodes.UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
  479. [21 /* ErrorCodes.UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
  480. [20 /* ErrorCodes.UNEXPECTED_NULL_CHARACTER */]: `Unexpected null character.`,
  481. [22 /* ErrorCodes.UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
  482. // Vue-specific parse errors
  483. [23 /* ErrorCodes.X_INVALID_END_TAG */]: 'Invalid end tag.',
  484. [24 /* ErrorCodes.X_MISSING_END_TAG */]: 'Element is missing end tag.',
  485. [25 /* ErrorCodes.X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
  486. [27 /* ErrorCodes.X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
  487. 'Note that dynamic directive argument cannot contain spaces.',
  488. [26 /* ErrorCodes.X_MISSING_DIRECTIVE_NAME */]: 'Legal directive name was expected.',
  489. // transform errors
  490. [28 /* ErrorCodes.X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
  491. [29 /* ErrorCodes.X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
  492. [30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if or v-else-if.`,
  493. [31 /* ErrorCodes.X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
  494. [32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
  495. [33 /* ErrorCodes.X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
  496. [34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
  497. [35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
  498. [36 /* ErrorCodes.X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
  499. [37 /* ErrorCodes.X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>. ` +
  500. `When there are multiple named slots, all slots should use <template> ` +
  501. `syntax to avoid scope ambiguity.`,
  502. [38 /* ErrorCodes.X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
  503. [39 /* ErrorCodes.X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
  504. `default slot. These children will be ignored.`,
  505. [40 /* ErrorCodes.X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
  506. [41 /* ErrorCodes.X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
  507. [42 /* ErrorCodes.X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
  508. [43 /* ErrorCodes.X_V_MODEL_ON_SCOPE_VARIABLE */]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,
  509. [44 /* ErrorCodes.X_V_MODEL_ON_PROPS */]: `v-model cannot be used on a prop, because local prop bindings are not writable.\nUse a v-bind binding combined with a v-on listener that emits update:x event instead.`,
  510. [45 /* ErrorCodes.X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
  511. [46 /* ErrorCodes.X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
  512. // generic errors
  513. [47 /* ErrorCodes.X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
  514. [48 /* ErrorCodes.X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
  515. [49 /* ErrorCodes.X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
  516. [50 /* ErrorCodes.X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`,
  517. // just to fulfill types
  518. [51 /* ErrorCodes.__EXTEND_POINT__ */]: ``
  519. };
  520. const FRAGMENT = Symbol(`Fragment` );
  521. const TELEPORT = Symbol(`Teleport` );
  522. const SUSPENSE = Symbol(`Suspense` );
  523. const KEEP_ALIVE = Symbol(`KeepAlive` );
  524. const BASE_TRANSITION = Symbol(`BaseTransition` );
  525. const OPEN_BLOCK = Symbol(`openBlock` );
  526. const CREATE_BLOCK = Symbol(`createBlock` );
  527. const CREATE_ELEMENT_BLOCK = Symbol(`createElementBlock` );
  528. const CREATE_VNODE = Symbol(`createVNode` );
  529. const CREATE_ELEMENT_VNODE = Symbol(`createElementVNode` );
  530. const CREATE_COMMENT = Symbol(`createCommentVNode` );
  531. const CREATE_TEXT = Symbol(`createTextVNode` );
  532. const CREATE_STATIC = Symbol(`createStaticVNode` );
  533. const RESOLVE_COMPONENT = Symbol(`resolveComponent` );
  534. const RESOLVE_DYNAMIC_COMPONENT = Symbol(`resolveDynamicComponent` );
  535. const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` );
  536. const RESOLVE_FILTER = Symbol(`resolveFilter` );
  537. const WITH_DIRECTIVES = Symbol(`withDirectives` );
  538. const RENDER_LIST = Symbol(`renderList` );
  539. const RENDER_SLOT = Symbol(`renderSlot` );
  540. const CREATE_SLOTS = Symbol(`createSlots` );
  541. const TO_DISPLAY_STRING = Symbol(`toDisplayString` );
  542. const MERGE_PROPS = Symbol(`mergeProps` );
  543. const NORMALIZE_CLASS = Symbol(`normalizeClass` );
  544. const NORMALIZE_STYLE = Symbol(`normalizeStyle` );
  545. const NORMALIZE_PROPS = Symbol(`normalizeProps` );
  546. const GUARD_REACTIVE_PROPS = Symbol(`guardReactiveProps` );
  547. const TO_HANDLERS = Symbol(`toHandlers` );
  548. const CAMELIZE = Symbol(`camelize` );
  549. const CAPITALIZE = Symbol(`capitalize` );
  550. const TO_HANDLER_KEY = Symbol(`toHandlerKey` );
  551. const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` );
  552. const PUSH_SCOPE_ID = Symbol(`pushScopeId` );
  553. const POP_SCOPE_ID = Symbol(`popScopeId` );
  554. const WITH_CTX = Symbol(`withCtx` );
  555. const UNREF = Symbol(`unref` );
  556. const IS_REF = Symbol(`isRef` );
  557. const WITH_MEMO = Symbol(`withMemo` );
  558. const IS_MEMO_SAME = Symbol(`isMemoSame` );
  559. // Name mapping for runtime helpers that need to be imported from 'vue' in
  560. // generated code. Make sure these are correctly exported in the runtime!
  561. const helperNameMap = {
  562. [FRAGMENT]: `Fragment`,
  563. [TELEPORT]: `Teleport`,
  564. [SUSPENSE]: `Suspense`,
  565. [KEEP_ALIVE]: `KeepAlive`,
  566. [BASE_TRANSITION]: `BaseTransition`,
  567. [OPEN_BLOCK]: `openBlock`,
  568. [CREATE_BLOCK]: `createBlock`,
  569. [CREATE_ELEMENT_BLOCK]: `createElementBlock`,
  570. [CREATE_VNODE]: `createVNode`,
  571. [CREATE_ELEMENT_VNODE]: `createElementVNode`,
  572. [CREATE_COMMENT]: `createCommentVNode`,
  573. [CREATE_TEXT]: `createTextVNode`,
  574. [CREATE_STATIC]: `createStaticVNode`,
  575. [RESOLVE_COMPONENT]: `resolveComponent`,
  576. [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
  577. [RESOLVE_DIRECTIVE]: `resolveDirective`,
  578. [RESOLVE_FILTER]: `resolveFilter`,
  579. [WITH_DIRECTIVES]: `withDirectives`,
  580. [RENDER_LIST]: `renderList`,
  581. [RENDER_SLOT]: `renderSlot`,
  582. [CREATE_SLOTS]: `createSlots`,
  583. [TO_DISPLAY_STRING]: `toDisplayString`,
  584. [MERGE_PROPS]: `mergeProps`,
  585. [NORMALIZE_CLASS]: `normalizeClass`,
  586. [NORMALIZE_STYLE]: `normalizeStyle`,
  587. [NORMALIZE_PROPS]: `normalizeProps`,
  588. [GUARD_REACTIVE_PROPS]: `guardReactiveProps`,
  589. [TO_HANDLERS]: `toHandlers`,
  590. [CAMELIZE]: `camelize`,
  591. [CAPITALIZE]: `capitalize`,
  592. [TO_HANDLER_KEY]: `toHandlerKey`,
  593. [SET_BLOCK_TRACKING]: `setBlockTracking`,
  594. [PUSH_SCOPE_ID]: `pushScopeId`,
  595. [POP_SCOPE_ID]: `popScopeId`,
  596. [WITH_CTX]: `withCtx`,
  597. [UNREF]: `unref`,
  598. [IS_REF]: `isRef`,
  599. [WITH_MEMO]: `withMemo`,
  600. [IS_MEMO_SAME]: `isMemoSame`
  601. };
  602. function registerRuntimeHelpers(helpers) {
  603. Object.getOwnPropertySymbols(helpers).forEach(s => {
  604. helperNameMap[s] = helpers[s];
  605. });
  606. }
  607. // AST Utilities ---------------------------------------------------------------
  608. // Some expressions, e.g. sequence and conditional expressions, are never
  609. // associated with template nodes, so their source locations are just a stub.
  610. // Container types like CompoundExpression also don't need a real location.
  611. const locStub = {
  612. source: '',
  613. start: { line: 1, column: 1, offset: 0 },
  614. end: { line: 1, column: 1, offset: 0 }
  615. };
  616. function createRoot(children, loc = locStub) {
  617. return {
  618. type: 0 /* NodeTypes.ROOT */,
  619. children,
  620. helpers: new Set(),
  621. components: [],
  622. directives: [],
  623. hoists: [],
  624. imports: [],
  625. cached: 0,
  626. temps: 0,
  627. codegenNode: undefined,
  628. loc
  629. };
  630. }
  631. function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent = false, loc = locStub) {
  632. if (context) {
  633. if (isBlock) {
  634. context.helper(OPEN_BLOCK);
  635. context.helper(getVNodeBlockHelper(context.inSSR, isComponent));
  636. }
  637. else {
  638. context.helper(getVNodeHelper(context.inSSR, isComponent));
  639. }
  640. if (directives) {
  641. context.helper(WITH_DIRECTIVES);
  642. }
  643. }
  644. return {
  645. type: 13 /* NodeTypes.VNODE_CALL */,
  646. tag,
  647. props,
  648. children,
  649. patchFlag,
  650. dynamicProps,
  651. directives,
  652. isBlock,
  653. disableTracking,
  654. isComponent,
  655. loc
  656. };
  657. }
  658. function createArrayExpression(elements, loc = locStub) {
  659. return {
  660. type: 17 /* NodeTypes.JS_ARRAY_EXPRESSION */,
  661. loc,
  662. elements
  663. };
  664. }
  665. function createObjectExpression(properties, loc = locStub) {
  666. return {
  667. type: 15 /* NodeTypes.JS_OBJECT_EXPRESSION */,
  668. loc,
  669. properties
  670. };
  671. }
  672. function createObjectProperty(key, value) {
  673. return {
  674. type: 16 /* NodeTypes.JS_PROPERTY */,
  675. loc: locStub,
  676. key: isString$2(key) ? createSimpleExpression(key, true) : key,
  677. value
  678. };
  679. }
  680. function createSimpleExpression(content, isStatic = false, loc = locStub, constType = 0 /* ConstantTypes.NOT_CONSTANT */) {
  681. return {
  682. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  683. loc,
  684. content,
  685. isStatic,
  686. constType: isStatic ? 3 /* ConstantTypes.CAN_STRINGIFY */ : constType
  687. };
  688. }
  689. function createInterpolation(content, loc) {
  690. return {
  691. type: 5 /* NodeTypes.INTERPOLATION */,
  692. loc,
  693. content: isString$2(content)
  694. ? createSimpleExpression(content, false, loc)
  695. : content
  696. };
  697. }
  698. function createCompoundExpression(children, loc = locStub) {
  699. return {
  700. type: 8 /* NodeTypes.COMPOUND_EXPRESSION */,
  701. loc,
  702. children
  703. };
  704. }
  705. function createCallExpression(callee, args = [], loc = locStub) {
  706. return {
  707. type: 14 /* NodeTypes.JS_CALL_EXPRESSION */,
  708. loc,
  709. callee,
  710. arguments: args
  711. };
  712. }
  713. function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
  714. return {
  715. type: 18 /* NodeTypes.JS_FUNCTION_EXPRESSION */,
  716. params,
  717. returns,
  718. newline,
  719. isSlot,
  720. loc
  721. };
  722. }
  723. function createConditionalExpression(test, consequent, alternate, newline = true) {
  724. return {
  725. type: 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */,
  726. test,
  727. consequent,
  728. alternate,
  729. newline,
  730. loc: locStub
  731. };
  732. }
  733. function createCacheExpression(index, value, isVNode = false) {
  734. return {
  735. type: 20 /* NodeTypes.JS_CACHE_EXPRESSION */,
  736. index,
  737. value,
  738. isVNode,
  739. loc: locStub
  740. };
  741. }
  742. function createBlockStatement(body) {
  743. return {
  744. type: 21 /* NodeTypes.JS_BLOCK_STATEMENT */,
  745. body,
  746. loc: locStub
  747. };
  748. }
  749. function createTemplateLiteral(elements) {
  750. return {
  751. type: 22 /* NodeTypes.JS_TEMPLATE_LITERAL */,
  752. elements,
  753. loc: locStub
  754. };
  755. }
  756. function createIfStatement(test, consequent, alternate) {
  757. return {
  758. type: 23 /* NodeTypes.JS_IF_STATEMENT */,
  759. test,
  760. consequent,
  761. alternate,
  762. loc: locStub
  763. };
  764. }
  765. function createAssignmentExpression(left, right) {
  766. return {
  767. type: 24 /* NodeTypes.JS_ASSIGNMENT_EXPRESSION */,
  768. left,
  769. right,
  770. loc: locStub
  771. };
  772. }
  773. function createSequenceExpression(expressions) {
  774. return {
  775. type: 25 /* NodeTypes.JS_SEQUENCE_EXPRESSION */,
  776. expressions,
  777. loc: locStub
  778. };
  779. }
  780. function createReturnStatement(returns) {
  781. return {
  782. type: 26 /* NodeTypes.JS_RETURN_STATEMENT */,
  783. returns,
  784. loc: locStub
  785. };
  786. }
  787. function getDefaultExportFromCjs (x) {
  788. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  789. }
  790. function getAugmentedNamespace(n) {
  791. var f = n.default;
  792. if (typeof f == "function") {
  793. var a = function () {
  794. return f.apply(this, arguments);
  795. };
  796. a.prototype = f.prototype;
  797. } else a = {};
  798. Object.defineProperty(a, '__esModule', {value: true});
  799. Object.keys(n).forEach(function (k) {
  800. var d = Object.getOwnPropertyDescriptor(n, k);
  801. Object.defineProperty(a, k, d.get ? d : {
  802. enumerable: true,
  803. get: function () {
  804. return n[k];
  805. }
  806. });
  807. });
  808. return a;
  809. }
  810. var lib = {};
  811. Object.defineProperty(lib, '__esModule', { value: true });
  812. const lineBreak = /\r\n?|[\n\u2028\u2029]/;
  813. const lineBreakG = new RegExp(lineBreak.source, "g");
  814. function isNewLine(code) {
  815. switch (code) {
  816. case 10:
  817. case 13:
  818. case 8232:
  819. case 8233:
  820. return true;
  821. default:
  822. return false;
  823. }
  824. }
  825. const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  826. const skipWhiteSpaceInLine = /(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/y;
  827. const skipWhiteSpaceToLineBreak = new RegExp("(?=(" + skipWhiteSpaceInLine.source + "))\\1" + /(?=[\n\r\u2028\u2029]|\/\*(?!.*?\*\/)|$)/.source, "y");
  828. function isWhitespace(code) {
  829. switch (code) {
  830. case 0x0009:
  831. case 0x000b:
  832. case 0x000c:
  833. case 32:
  834. case 160:
  835. case 5760:
  836. case 0x2000:
  837. case 0x2001:
  838. case 0x2002:
  839. case 0x2003:
  840. case 0x2004:
  841. case 0x2005:
  842. case 0x2006:
  843. case 0x2007:
  844. case 0x2008:
  845. case 0x2009:
  846. case 0x200a:
  847. case 0x202f:
  848. case 0x205f:
  849. case 0x3000:
  850. case 0xfeff:
  851. return true;
  852. default:
  853. return false;
  854. }
  855. }
  856. class Position {
  857. constructor(line, col) {
  858. this.line = void 0;
  859. this.column = void 0;
  860. this.line = line;
  861. this.column = col;
  862. }
  863. }
  864. class SourceLocation {
  865. constructor(start, end) {
  866. this.start = void 0;
  867. this.end = void 0;
  868. this.filename = void 0;
  869. this.identifierName = void 0;
  870. this.start = start;
  871. this.end = end;
  872. }
  873. }
  874. function getLineInfo(input, offset) {
  875. let line = 1;
  876. let lineStart = 0;
  877. let match;
  878. lineBreakG.lastIndex = 0;
  879. while ((match = lineBreakG.exec(input)) && match.index < offset) {
  880. line++;
  881. lineStart = lineBreakG.lastIndex;
  882. }
  883. return new Position(line, offset - lineStart);
  884. }
  885. class BaseParser {
  886. constructor() {
  887. this.sawUnambiguousESM = false;
  888. this.ambiguousScriptDifferentAst = false;
  889. }
  890. hasPlugin(name) {
  891. return this.plugins.has(name);
  892. }
  893. getPluginOption(plugin, name) {
  894. if (this.hasPlugin(plugin)) return this.plugins.get(plugin)[name];
  895. }
  896. }
  897. function setTrailingComments(node, comments) {
  898. if (node.trailingComments === undefined) {
  899. node.trailingComments = comments;
  900. } else {
  901. node.trailingComments.unshift(...comments);
  902. }
  903. }
  904. function setLeadingComments(node, comments) {
  905. if (node.leadingComments === undefined) {
  906. node.leadingComments = comments;
  907. } else {
  908. node.leadingComments.unshift(...comments);
  909. }
  910. }
  911. function setInnerComments(node, comments) {
  912. if (node.innerComments === undefined) {
  913. node.innerComments = comments;
  914. } else {
  915. node.innerComments.unshift(...comments);
  916. }
  917. }
  918. function adjustInnerComments(node, elements, commentWS) {
  919. let lastElement = null;
  920. let i = elements.length;
  921. while (lastElement === null && i > 0) {
  922. lastElement = elements[--i];
  923. }
  924. if (lastElement === null || lastElement.start > commentWS.start) {
  925. setInnerComments(node, commentWS.comments);
  926. } else {
  927. setTrailingComments(lastElement, commentWS.comments);
  928. }
  929. }
  930. class CommentsParser extends BaseParser {
  931. addComment(comment) {
  932. if (this.filename) comment.loc.filename = this.filename;
  933. this.state.comments.push(comment);
  934. }
  935. processComment(node) {
  936. const {
  937. commentStack
  938. } = this.state;
  939. const commentStackLength = commentStack.length;
  940. if (commentStackLength === 0) return;
  941. let i = commentStackLength - 1;
  942. const lastCommentWS = commentStack[i];
  943. if (lastCommentWS.start === node.end) {
  944. lastCommentWS.leadingNode = node;
  945. i--;
  946. }
  947. const {
  948. start: nodeStart
  949. } = node;
  950. for (; i >= 0; i--) {
  951. const commentWS = commentStack[i];
  952. const commentEnd = commentWS.end;
  953. if (commentEnd > nodeStart) {
  954. commentWS.containingNode = node;
  955. this.finalizeComment(commentWS);
  956. commentStack.splice(i, 1);
  957. } else {
  958. if (commentEnd === nodeStart) {
  959. commentWS.trailingNode = node;
  960. }
  961. break;
  962. }
  963. }
  964. }
  965. finalizeComment(commentWS) {
  966. const {
  967. comments
  968. } = commentWS;
  969. if (commentWS.leadingNode !== null || commentWS.trailingNode !== null) {
  970. if (commentWS.leadingNode !== null) {
  971. setTrailingComments(commentWS.leadingNode, comments);
  972. }
  973. if (commentWS.trailingNode !== null) {
  974. setLeadingComments(commentWS.trailingNode, comments);
  975. }
  976. } else {
  977. const {
  978. containingNode: node,
  979. start: commentStart
  980. } = commentWS;
  981. if (this.input.charCodeAt(commentStart - 1) === 44) {
  982. switch (node.type) {
  983. case "ObjectExpression":
  984. case "ObjectPattern":
  985. case "RecordExpression":
  986. adjustInnerComments(node, node.properties, commentWS);
  987. break;
  988. case "CallExpression":
  989. case "OptionalCallExpression":
  990. adjustInnerComments(node, node.arguments, commentWS);
  991. break;
  992. case "FunctionDeclaration":
  993. case "FunctionExpression":
  994. case "ArrowFunctionExpression":
  995. case "ObjectMethod":
  996. case "ClassMethod":
  997. case "ClassPrivateMethod":
  998. adjustInnerComments(node, node.params, commentWS);
  999. break;
  1000. case "ArrayExpression":
  1001. case "ArrayPattern":
  1002. case "TupleExpression":
  1003. adjustInnerComments(node, node.elements, commentWS);
  1004. break;
  1005. case "ExportNamedDeclaration":
  1006. case "ImportDeclaration":
  1007. adjustInnerComments(node, node.specifiers, commentWS);
  1008. break;
  1009. default:
  1010. {
  1011. setInnerComments(node, comments);
  1012. }
  1013. }
  1014. } else {
  1015. setInnerComments(node, comments);
  1016. }
  1017. }
  1018. }
  1019. finalizeRemainingComments() {
  1020. const {
  1021. commentStack
  1022. } = this.state;
  1023. for (let i = commentStack.length - 1; i >= 0; i--) {
  1024. this.finalizeComment(commentStack[i]);
  1025. }
  1026. this.state.commentStack = [];
  1027. }
  1028. resetPreviousNodeTrailingComments(node) {
  1029. const {
  1030. commentStack
  1031. } = this.state;
  1032. const {
  1033. length
  1034. } = commentStack;
  1035. if (length === 0) return;
  1036. const commentWS = commentStack[length - 1];
  1037. if (commentWS.leadingNode === node) {
  1038. commentWS.leadingNode = null;
  1039. }
  1040. }
  1041. takeSurroundingComments(node, start, end) {
  1042. const {
  1043. commentStack
  1044. } = this.state;
  1045. const commentStackLength = commentStack.length;
  1046. if (commentStackLength === 0) return;
  1047. let i = commentStackLength - 1;
  1048. for (; i >= 0; i--) {
  1049. const commentWS = commentStack[i];
  1050. const commentEnd = commentWS.end;
  1051. const commentStart = commentWS.start;
  1052. if (commentStart === end) {
  1053. commentWS.leadingNode = node;
  1054. } else if (commentEnd === start) {
  1055. commentWS.trailingNode = node;
  1056. } else if (commentEnd < start) {
  1057. break;
  1058. }
  1059. }
  1060. }
  1061. }
  1062. const ErrorCodes = Object.freeze({
  1063. SyntaxError: "BABEL_PARSER_SYNTAX_ERROR",
  1064. SourceTypeModuleError: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  1065. });
  1066. const ErrorMessages = makeErrorTemplates({
  1067. AccessorIsGenerator: "A %0ter cannot be a generator.",
  1068. ArgumentsInClass: "'arguments' is only allowed in functions and class methods.",
  1069. AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block.",
  1070. AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function.",
  1071. AwaitBindingIdentifierInStaticBlock: "Can not use 'await' as identifier inside a static block.",
  1072. AwaitExpressionFormalParameter: "'await' is not allowed in async function parameters.",
  1073. AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules.",
  1074. AwaitNotInAsyncFunction: "'await' is only allowed within async functions.",
  1075. BadGetterArity: "A 'get' accesor must not have any formal parameters.",
  1076. BadSetterArity: "A 'set' accesor must have exactly one formal parameter.",
  1077. BadSetterRestParameter: "A 'set' accesor function argument must not be a rest parameter.",
  1078. ConstructorClassField: "Classes may not have a field named 'constructor'.",
  1079. ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'.",
  1080. ConstructorIsAccessor: "Class constructor may not be an accessor.",
  1081. ConstructorIsAsync: "Constructor can't be an async function.",
  1082. ConstructorIsGenerator: "Constructor can't be a generator.",
  1083. DeclarationMissingInitializer: "'%0' require an initialization value.",
  1084. DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. You can set the 'decoratorsBeforeExport' option to false to use the 'export @decorator class {}' syntax.",
  1085. DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",
  1086. DecoratorExportClass: "Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class` instead.",
  1087. DecoratorSemicolon: "Decorators must not be followed by a semicolon.",
  1088. DecoratorStaticBlock: "Decorators can't be used with a static block.",
  1089. DeletePrivateField: "Deleting a private field is not allowed.",
  1090. DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.",
  1091. DuplicateConstructor: "Duplicate constructor in the same class.",
  1092. DuplicateDefaultExport: "Only one default export allowed per module.",
  1093. DuplicateExport: "`%0` has already been exported. Exported identifiers must be unique.",
  1094. DuplicateProto: "Redefinition of __proto__ property.",
  1095. DuplicateRegExpFlags: "Duplicate regular expression flag.",
  1096. ElementAfterRest: "Rest element must be last element.",
  1097. EscapedCharNotAnIdentifier: "Invalid Unicode escape.",
  1098. ExportBindingIsString: "A string literal cannot be used as an exported binding without `from`.\n- Did you mean `export { '%0' as '%1' } from 'some-module'`?",
  1099. ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'.",
  1100. ForInOfLoopInitializer: "'%0' loop variable declaration may not have an initializer.",
  1101. ForOfAsync: "The left-hand side of a for-of loop may not be 'async'.",
  1102. ForOfLet: "The left-hand side of a for-of loop may not start with 'let'.",
  1103. GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block.",
  1104. IllegalBreakContinue: "Unsyntactic %0.",
  1105. IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list.",
  1106. IllegalReturn: "'return' outside of function.",
  1107. ImportBindingIsString: 'A string literal cannot be used as an imported binding.\n- Did you mean `import { "%0" as foo }`?',
  1108. ImportCallArgumentTrailingComma: "Trailing comma is disallowed inside import(...) arguments.",
  1109. ImportCallArity: "`import()` requires exactly %0.",
  1110. ImportCallNotNewExpression: "Cannot use new with import(...).",
  1111. ImportCallSpreadArgument: "`...` is not allowed in `import()`.",
  1112. InvalidBigIntLiteral: "Invalid BigIntLiteral.",
  1113. InvalidCodePoint: "Code point out of bounds.",
  1114. InvalidDecimal: "Invalid decimal.",
  1115. InvalidDigit: "Expected number in radix %0.",
  1116. InvalidEscapeSequence: "Bad character escape sequence.",
  1117. InvalidEscapeSequenceTemplate: "Invalid escape sequence in template.",
  1118. InvalidEscapedReservedWord: "Escape sequence in keyword %0.",
  1119. InvalidIdentifier: "Invalid identifier %0.",
  1120. InvalidLhs: "Invalid left-hand side in %0.",
  1121. InvalidLhsBinding: "Binding invalid left-hand side in %0.",
  1122. InvalidNumber: "Invalid number.",
  1123. InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'.",
  1124. InvalidOrUnexpectedToken: "Unexpected character '%0'.",
  1125. InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern.",
  1126. InvalidPrivateFieldResolution: "Private name #%0 is not defined.",
  1127. InvalidPropertyBindingPattern: "Binding member expression.",
  1128. InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions.",
  1129. InvalidRestAssignmentPattern: "Invalid rest operator's argument.",
  1130. LabelRedeclaration: "Label '%0' is already declared.",
  1131. LetInLexicalBinding: "'let' is not allowed to be used as a name in 'let' or 'const' declarations.",
  1132. LineTerminatorBeforeArrow: "No line break is allowed before '=>'.",
  1133. MalformedRegExpFlags: "Invalid regular expression flag.",
  1134. MissingClassName: "A class name is required.",
  1135. MissingEqInAssignment: "Only '=' operator can be used for specifying default value.",
  1136. MissingSemicolon: "Missing semicolon.",
  1137. MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX.",
  1138. MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators.",
  1139. ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`.",
  1140. ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values.",
  1141. ModuleAttributesWithDuplicateKeys: 'Duplicate key "%0" is not allowed in module attributes.',
  1142. ModuleExportNameHasLoneSurrogate: "An export name cannot include a lone surrogate, found '\\u%0'.",
  1143. ModuleExportUndefined: "Export '%0' is not defined.",
  1144. MultipleDefaultsInSwitch: "Multiple default clauses.",
  1145. NewlineAfterThrow: "Illegal newline after throw.",
  1146. NoCatchOrFinally: "Missing catch or finally clause.",
  1147. NumberIdentifier: "Identifier directly after number.",
  1148. NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.",
  1149. ObsoleteAwaitStar: "'await*' has been removed from the async functions proposal. Use Promise.all() instead.",
  1150. OptionalChainingNoNew: "Constructors in/after an Optional Chain are not allowed.",
  1151. OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain.",
  1152. OverrideOnConstructor: "'override' modifier cannot appear on a constructor declaration.",
  1153. ParamDupe: "Argument name clash.",
  1154. PatternHasAccessor: "Object pattern can't contain getter or setter.",
  1155. PatternHasMethod: "Object pattern can't contain methods.",
  1156. PipeBodyIsTighter: "Unexpected %0 after pipeline body; any %0 expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.",
  1157. PipeTopicRequiresHackPipes: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.',
  1158. PipeTopicUnbound: "Topic reference is unbound; it must be inside a pipe body.",
  1159. PipeTopicUnconfiguredToken: 'Invalid topic token %0. In order to use %0 as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "%0" }.',
  1160. PipeTopicUnused: "Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.",
  1161. PipeUnparenthesizedBody: "Hack-style pipe body cannot be an unparenthesized %0 expression; please wrap it in parentheses.",
  1162. PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized.',
  1163. PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression.",
  1164. PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression.",
  1165. PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference.",
  1166. PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding.",
  1167. PrimaryTopicRequiresSmartPipeline: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.',
  1168. PrivateInExpectedIn: "Private names are only allowed in property accesses (`obj.#%0`) or in `in` expressions (`#%0 in obj`).",
  1169. PrivateNameRedeclaration: "Duplicate private name #%0.",
  1170. RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  1171. RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  1172. RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",
  1173. RecordNoProto: "'__proto__' is not allowed in Record expressions.",
  1174. RestTrailingComma: "Unexpected trailing comma after rest element.",
  1175. SloppyFunction: "In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.",
  1176. StaticPrototype: "Classes may not have static property named prototype.",
  1177. StrictDelete: "Deleting local variable in strict mode.",
  1178. StrictEvalArguments: "Assigning to '%0' in strict mode.",
  1179. StrictEvalArgumentsBinding: "Binding '%0' in strict mode.",
  1180. StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block.",
  1181. StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'.",
  1182. StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode.",
  1183. StrictWith: "'with' in strict mode.",
  1184. SuperNotAllowed: "`super()` is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?",
  1185. SuperPrivateField: "Private fields can't be accessed on super.",
  1186. TrailingDecorator: "Decorators must be attached to a class element.",
  1187. TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  1188. TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  1189. TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",
  1190. UnexpectedArgumentPlaceholder: "Unexpected argument placeholder.",
  1191. UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal.',
  1192. UnexpectedDigitAfterHash: "Unexpected digit after hash token.",
  1193. UnexpectedImportExport: "'import' and 'export' may only appear at the top level.",
  1194. UnexpectedKeyword: "Unexpected keyword '%0'.",
  1195. UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration.",
  1196. UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context.",
  1197. UnexpectedNewTarget: "`new.target` can only be used in functions or class properties.",
  1198. UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits.",
  1199. UnexpectedPrivateField: "Private names can only be used as the name of a class element (i.e. class C { #p = 42; #m() {} } )\n or a property of member expression (i.e. this.#p).",
  1200. UnexpectedReservedWord: "Unexpected reserved word '%0'.",
  1201. UnexpectedSuper: "'super' is only allowed in object methods and classes.",
  1202. UnexpectedToken: "Unexpected token '%0'.",
  1203. UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",
  1204. UnsupportedBind: "Binding should be performed on object property.",
  1205. UnsupportedDecoratorExport: "A decorated export must export a class declaration.",
  1206. UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.",
  1207. UnsupportedImport: "`import` can only be used in `import()` or `import.meta`.",
  1208. UnsupportedMetaProperty: "The only valid meta property for %0 is %0.%1.",
  1209. UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters.",
  1210. UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties.",
  1211. UnsupportedSuper: "'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).",
  1212. UnterminatedComment: "Unterminated comment.",
  1213. UnterminatedRegExp: "Unterminated regular expression.",
  1214. UnterminatedString: "Unterminated string constant.",
  1215. UnterminatedTemplate: "Unterminated template.",
  1216. VarRedeclaration: "Identifier '%0' has already been declared.",
  1217. YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator.",
  1218. YieldInParameter: "Yield expression is not allowed in formal parameters.",
  1219. ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0."
  1220. }, ErrorCodes.SyntaxError);
  1221. const SourceTypeModuleErrorMessages = makeErrorTemplates({
  1222. ImportMetaOutsideModule: `import.meta may appear only with 'sourceType: "module"'`,
  1223. ImportOutsideModule: `'import' and 'export' may appear only with 'sourceType: "module"'`
  1224. }, ErrorCodes.SourceTypeModuleError);
  1225. function keepReasonCodeCompat(reasonCode, syntaxPlugin) {
  1226. {
  1227. if (syntaxPlugin === "flow" && reasonCode === "PatternIsOptional") {
  1228. return "OptionalBindingPattern";
  1229. }
  1230. }
  1231. return reasonCode;
  1232. }
  1233. function makeErrorTemplates(messages, code, syntaxPlugin) {
  1234. const templates = {};
  1235. Object.keys(messages).forEach(reasonCode => {
  1236. templates[reasonCode] = Object.freeze({
  1237. code,
  1238. reasonCode: keepReasonCodeCompat(reasonCode, syntaxPlugin),
  1239. template: messages[reasonCode]
  1240. });
  1241. });
  1242. return Object.freeze(templates);
  1243. }
  1244. class ParserError extends CommentsParser {
  1245. getLocationForPosition(pos) {
  1246. let loc;
  1247. if (pos === this.state.start) loc = this.state.startLoc;else if (pos === this.state.lastTokStart) loc = this.state.lastTokStartLoc;else if (pos === this.state.end) loc = this.state.endLoc;else if (pos === this.state.lastTokEnd) loc = this.state.lastTokEndLoc;else loc = getLineInfo(this.input, pos);
  1248. return loc;
  1249. }
  1250. raise(pos, {
  1251. code,
  1252. reasonCode,
  1253. template
  1254. }, ...params) {
  1255. return this.raiseWithData(pos, {
  1256. code,
  1257. reasonCode
  1258. }, template, ...params);
  1259. }
  1260. raiseOverwrite(pos, {
  1261. code,
  1262. template
  1263. }, ...params) {
  1264. const loc = this.getLocationForPosition(pos);
  1265. const message = template.replace(/%(\d+)/g, (_, i) => params[i]) + ` (${loc.line}:${loc.column})`;
  1266. if (this.options.errorRecovery) {
  1267. const errors = this.state.errors;
  1268. for (let i = errors.length - 1; i >= 0; i--) {
  1269. const error = errors[i];
  1270. if (error.pos === pos) {
  1271. return Object.assign(error, {
  1272. message
  1273. });
  1274. } else if (error.pos < pos) {
  1275. break;
  1276. }
  1277. }
  1278. }
  1279. return this._raise({
  1280. code,
  1281. loc,
  1282. pos
  1283. }, message);
  1284. }
  1285. raiseWithData(pos, data, errorTemplate, ...params) {
  1286. const loc = this.getLocationForPosition(pos);
  1287. const message = errorTemplate.replace(/%(\d+)/g, (_, i) => params[i]) + ` (${loc.line}:${loc.column})`;
  1288. return this._raise(Object.assign({
  1289. loc,
  1290. pos
  1291. }, data), message);
  1292. }
  1293. _raise(errorContext, message) {
  1294. const err = new SyntaxError(message);
  1295. Object.assign(err, errorContext);
  1296. if (this.options.errorRecovery) {
  1297. if (!this.isLookahead) this.state.errors.push(err);
  1298. return err;
  1299. } else {
  1300. throw err;
  1301. }
  1302. }
  1303. }
  1304. var estree = (superClass => class extends superClass {
  1305. parseRegExpLiteral({
  1306. pattern,
  1307. flags
  1308. }) {
  1309. let regex = null;
  1310. try {
  1311. regex = new RegExp(pattern, flags);
  1312. } catch (e) {}
  1313. const node = this.estreeParseLiteral(regex);
  1314. node.regex = {
  1315. pattern,
  1316. flags
  1317. };
  1318. return node;
  1319. }
  1320. parseBigIntLiteral(value) {
  1321. let bigInt;
  1322. try {
  1323. bigInt = BigInt(value);
  1324. } catch (_unused) {
  1325. bigInt = null;
  1326. }
  1327. const node = this.estreeParseLiteral(bigInt);
  1328. node.bigint = String(node.value || value);
  1329. return node;
  1330. }
  1331. parseDecimalLiteral(value) {
  1332. const decimal = null;
  1333. const node = this.estreeParseLiteral(decimal);
  1334. node.decimal = String(node.value || value);
  1335. return node;
  1336. }
  1337. estreeParseLiteral(value) {
  1338. return this.parseLiteral(value, "Literal");
  1339. }
  1340. parseStringLiteral(value) {
  1341. return this.estreeParseLiteral(value);
  1342. }
  1343. parseNumericLiteral(value) {
  1344. return this.estreeParseLiteral(value);
  1345. }
  1346. parseNullLiteral() {
  1347. return this.estreeParseLiteral(null);
  1348. }
  1349. parseBooleanLiteral(value) {
  1350. return this.estreeParseLiteral(value);
  1351. }
  1352. directiveToStmt(directive) {
  1353. const directiveLiteral = directive.value;
  1354. const stmt = this.startNodeAt(directive.start, directive.loc.start);
  1355. const expression = this.startNodeAt(directiveLiteral.start, directiveLiteral.loc.start);
  1356. expression.value = directiveLiteral.extra.expressionValue;
  1357. expression.raw = directiveLiteral.extra.raw;
  1358. stmt.expression = this.finishNodeAt(expression, "Literal", directiveLiteral.end, directiveLiteral.loc.end);
  1359. stmt.directive = directiveLiteral.extra.raw.slice(1, -1);
  1360. return this.finishNodeAt(stmt, "ExpressionStatement", directive.end, directive.loc.end);
  1361. }
  1362. initFunction(node, isAsync) {
  1363. super.initFunction(node, isAsync);
  1364. node.expression = false;
  1365. }
  1366. checkDeclaration(node) {
  1367. if (node != null && this.isObjectProperty(node)) {
  1368. this.checkDeclaration(node.value);
  1369. } else {
  1370. super.checkDeclaration(node);
  1371. }
  1372. }
  1373. getObjectOrClassMethodParams(method) {
  1374. return method.value.params;
  1375. }
  1376. isValidDirective(stmt) {
  1377. var _stmt$expression$extr;
  1378. return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && !((_stmt$expression$extr = stmt.expression.extra) != null && _stmt$expression$extr.parenthesized);
  1379. }
  1380. parseBlockBody(node, ...args) {
  1381. super.parseBlockBody(node, ...args);
  1382. const directiveStatements = node.directives.map(d => this.directiveToStmt(d));
  1383. node.body = directiveStatements.concat(node.body);
  1384. delete node.directives;
  1385. }
  1386. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  1387. this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true);
  1388. if (method.typeParameters) {
  1389. method.value.typeParameters = method.typeParameters;
  1390. delete method.typeParameters;
  1391. }
  1392. classBody.body.push(method);
  1393. }
  1394. parsePrivateName() {
  1395. const node = super.parsePrivateName();
  1396. {
  1397. if (!this.getPluginOption("estree", "classFeatures")) {
  1398. return node;
  1399. }
  1400. }
  1401. return this.convertPrivateNameToPrivateIdentifier(node);
  1402. }
  1403. convertPrivateNameToPrivateIdentifier(node) {
  1404. const name = super.getPrivateNameSV(node);
  1405. node = node;
  1406. delete node.id;
  1407. node.name = name;
  1408. node.type = "PrivateIdentifier";
  1409. return node;
  1410. }
  1411. isPrivateName(node) {
  1412. {
  1413. if (!this.getPluginOption("estree", "classFeatures")) {
  1414. return super.isPrivateName(node);
  1415. }
  1416. }
  1417. return node.type === "PrivateIdentifier";
  1418. }
  1419. getPrivateNameSV(node) {
  1420. {
  1421. if (!this.getPluginOption("estree", "classFeatures")) {
  1422. return super.getPrivateNameSV(node);
  1423. }
  1424. }
  1425. return node.name;
  1426. }
  1427. parseLiteral(value, type) {
  1428. const node = super.parseLiteral(value, type);
  1429. node.raw = node.extra.raw;
  1430. delete node.extra;
  1431. return node;
  1432. }
  1433. parseFunctionBody(node, allowExpression, isMethod = false) {
  1434. super.parseFunctionBody(node, allowExpression, isMethod);
  1435. node.expression = node.body.type !== "BlockStatement";
  1436. }
  1437. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  1438. let funcNode = this.startNode();
  1439. funcNode.kind = node.kind;
  1440. funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  1441. funcNode.type = "FunctionExpression";
  1442. delete funcNode.kind;
  1443. node.value = funcNode;
  1444. if (type === "ClassPrivateMethod") {
  1445. node.computed = false;
  1446. }
  1447. type = "MethodDefinition";
  1448. return this.finishNode(node, type);
  1449. }
  1450. parseClassProperty(...args) {
  1451. const propertyNode = super.parseClassProperty(...args);
  1452. {
  1453. if (!this.getPluginOption("estree", "classFeatures")) {
  1454. return propertyNode;
  1455. }
  1456. }
  1457. propertyNode.type = "PropertyDefinition";
  1458. return propertyNode;
  1459. }
  1460. parseClassPrivateProperty(...args) {
  1461. const propertyNode = super.parseClassPrivateProperty(...args);
  1462. {
  1463. if (!this.getPluginOption("estree", "classFeatures")) {
  1464. return propertyNode;
  1465. }
  1466. }
  1467. propertyNode.type = "PropertyDefinition";
  1468. propertyNode.computed = false;
  1469. return propertyNode;
  1470. }
  1471. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  1472. const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor);
  1473. if (node) {
  1474. node.type = "Property";
  1475. if (node.kind === "method") node.kind = "init";
  1476. node.shorthand = false;
  1477. }
  1478. return node;
  1479. }
  1480. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  1481. const node = super.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  1482. if (node) {
  1483. node.kind = "init";
  1484. node.type = "Property";
  1485. }
  1486. return node;
  1487. }
  1488. isAssignable(node, isBinding) {
  1489. if (node != null && this.isObjectProperty(node)) {
  1490. return this.isAssignable(node.value, isBinding);
  1491. }
  1492. return super.isAssignable(node, isBinding);
  1493. }
  1494. toAssignable(node, isLHS = false) {
  1495. if (node != null && this.isObjectProperty(node)) {
  1496. this.toAssignable(node.value, isLHS);
  1497. return node;
  1498. }
  1499. return super.toAssignable(node, isLHS);
  1500. }
  1501. toAssignableObjectExpressionProp(prop, ...args) {
  1502. if (prop.kind === "get" || prop.kind === "set") {
  1503. this.raise(prop.key.start, ErrorMessages.PatternHasAccessor);
  1504. } else if (prop.method) {
  1505. this.raise(prop.key.start, ErrorMessages.PatternHasMethod);
  1506. } else {
  1507. super.toAssignableObjectExpressionProp(prop, ...args);
  1508. }
  1509. }
  1510. finishCallExpression(node, optional) {
  1511. super.finishCallExpression(node, optional);
  1512. if (node.callee.type === "Import") {
  1513. node.type = "ImportExpression";
  1514. node.source = node.arguments[0];
  1515. if (this.hasPlugin("importAssertions")) {
  1516. var _node$arguments$;
  1517. node.attributes = (_node$arguments$ = node.arguments[1]) != null ? _node$arguments$ : null;
  1518. }
  1519. delete node.arguments;
  1520. delete node.callee;
  1521. }
  1522. return node;
  1523. }
  1524. toReferencedArguments(node) {
  1525. if (node.type === "ImportExpression") {
  1526. return;
  1527. }
  1528. super.toReferencedArguments(node);
  1529. }
  1530. parseExport(node) {
  1531. super.parseExport(node);
  1532. switch (node.type) {
  1533. case "ExportAllDeclaration":
  1534. node.exported = null;
  1535. break;
  1536. case "ExportNamedDeclaration":
  1537. if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") {
  1538. node.type = "ExportAllDeclaration";
  1539. node.exported = node.specifiers[0].exported;
  1540. delete node.specifiers;
  1541. }
  1542. break;
  1543. }
  1544. return node;
  1545. }
  1546. parseSubscript(base, startPos, startLoc, noCalls, state) {
  1547. const node = super.parseSubscript(base, startPos, startLoc, noCalls, state);
  1548. if (state.optionalChainMember) {
  1549. if (node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression") {
  1550. node.type = node.type.substring(8);
  1551. }
  1552. if (state.stop) {
  1553. const chain = this.startNodeAtNode(node);
  1554. chain.expression = node;
  1555. return this.finishNode(chain, "ChainExpression");
  1556. }
  1557. } else if (node.type === "MemberExpression" || node.type === "CallExpression") {
  1558. node.optional = false;
  1559. }
  1560. return node;
  1561. }
  1562. hasPropertyAsPrivateName(node) {
  1563. if (node.type === "ChainExpression") {
  1564. node = node.expression;
  1565. }
  1566. return super.hasPropertyAsPrivateName(node);
  1567. }
  1568. isOptionalChain(node) {
  1569. return node.type === "ChainExpression";
  1570. }
  1571. isObjectProperty(node) {
  1572. return node.type === "Property" && node.kind === "init" && !node.method;
  1573. }
  1574. isObjectMethod(node) {
  1575. return node.method || node.kind === "get" || node.kind === "set";
  1576. }
  1577. });
  1578. class TokContext {
  1579. constructor(token, preserveSpace) {
  1580. this.token = void 0;
  1581. this.preserveSpace = void 0;
  1582. this.token = token;
  1583. this.preserveSpace = !!preserveSpace;
  1584. }
  1585. }
  1586. const types$1 = {
  1587. brace: new TokContext("{"),
  1588. template: new TokContext("`", true)
  1589. };
  1590. const beforeExpr = true;
  1591. const startsExpr = true;
  1592. const isLoop = true;
  1593. const isAssign = true;
  1594. const prefix = true;
  1595. const postfix = true;
  1596. class ExportedTokenType {
  1597. constructor(label, conf = {}) {
  1598. this.label = void 0;
  1599. this.keyword = void 0;
  1600. this.beforeExpr = void 0;
  1601. this.startsExpr = void 0;
  1602. this.rightAssociative = void 0;
  1603. this.isLoop = void 0;
  1604. this.isAssign = void 0;
  1605. this.prefix = void 0;
  1606. this.postfix = void 0;
  1607. this.binop = void 0;
  1608. this.label = label;
  1609. this.keyword = conf.keyword;
  1610. this.beforeExpr = !!conf.beforeExpr;
  1611. this.startsExpr = !!conf.startsExpr;
  1612. this.rightAssociative = !!conf.rightAssociative;
  1613. this.isLoop = !!conf.isLoop;
  1614. this.isAssign = !!conf.isAssign;
  1615. this.prefix = !!conf.prefix;
  1616. this.postfix = !!conf.postfix;
  1617. this.binop = conf.binop != null ? conf.binop : null;
  1618. {
  1619. this.updateContext = null;
  1620. }
  1621. }
  1622. }
  1623. const keywords$1 = new Map();
  1624. function createKeyword(name, options = {}) {
  1625. options.keyword = name;
  1626. const token = createToken(name, options);
  1627. keywords$1.set(name, token);
  1628. return token;
  1629. }
  1630. function createBinop(name, binop) {
  1631. return createToken(name, {
  1632. beforeExpr,
  1633. binop
  1634. });
  1635. }
  1636. let tokenTypeCounter = -1;
  1637. const tokenTypes$1 = [];
  1638. const tokenLabels = [];
  1639. const tokenBinops = [];
  1640. const tokenBeforeExprs = [];
  1641. const tokenStartsExprs = [];
  1642. const tokenPrefixes = [];
  1643. function createToken(name, options = {}) {
  1644. var _options$binop, _options$beforeExpr, _options$startsExpr, _options$prefix;
  1645. ++tokenTypeCounter;
  1646. tokenLabels.push(name);
  1647. tokenBinops.push((_options$binop = options.binop) != null ? _options$binop : -1);
  1648. tokenBeforeExprs.push((_options$beforeExpr = options.beforeExpr) != null ? _options$beforeExpr : false);
  1649. tokenStartsExprs.push((_options$startsExpr = options.startsExpr) != null ? _options$startsExpr : false);
  1650. tokenPrefixes.push((_options$prefix = options.prefix) != null ? _options$prefix : false);
  1651. tokenTypes$1.push(new ExportedTokenType(name, options));
  1652. return tokenTypeCounter;
  1653. }
  1654. function createKeywordLike(name, options = {}) {
  1655. var _options$binop2, _options$beforeExpr2, _options$startsExpr2, _options$prefix2;
  1656. ++tokenTypeCounter;
  1657. keywords$1.set(name, tokenTypeCounter);
  1658. tokenLabels.push(name);
  1659. tokenBinops.push((_options$binop2 = options.binop) != null ? _options$binop2 : -1);
  1660. tokenBeforeExprs.push((_options$beforeExpr2 = options.beforeExpr) != null ? _options$beforeExpr2 : false);
  1661. tokenStartsExprs.push((_options$startsExpr2 = options.startsExpr) != null ? _options$startsExpr2 : false);
  1662. tokenPrefixes.push((_options$prefix2 = options.prefix) != null ? _options$prefix2 : false);
  1663. tokenTypes$1.push(new ExportedTokenType("name", options));
  1664. return tokenTypeCounter;
  1665. }
  1666. const tt = {
  1667. bracketL: createToken("[", {
  1668. beforeExpr,
  1669. startsExpr
  1670. }),
  1671. bracketHashL: createToken("#[", {
  1672. beforeExpr,
  1673. startsExpr
  1674. }),
  1675. bracketBarL: createToken("[|", {
  1676. beforeExpr,
  1677. startsExpr
  1678. }),
  1679. bracketR: createToken("]"),
  1680. bracketBarR: createToken("|]"),
  1681. braceL: createToken("{", {
  1682. beforeExpr,
  1683. startsExpr
  1684. }),
  1685. braceBarL: createToken("{|", {
  1686. beforeExpr,
  1687. startsExpr
  1688. }),
  1689. braceHashL: createToken("#{", {
  1690. beforeExpr,
  1691. startsExpr
  1692. }),
  1693. braceR: createToken("}", {
  1694. beforeExpr
  1695. }),
  1696. braceBarR: createToken("|}"),
  1697. parenL: createToken("(", {
  1698. beforeExpr,
  1699. startsExpr
  1700. }),
  1701. parenR: createToken(")"),
  1702. comma: createToken(",", {
  1703. beforeExpr
  1704. }),
  1705. semi: createToken(";", {
  1706. beforeExpr
  1707. }),
  1708. colon: createToken(":", {
  1709. beforeExpr
  1710. }),
  1711. doubleColon: createToken("::", {
  1712. beforeExpr
  1713. }),
  1714. dot: createToken("."),
  1715. question: createToken("?", {
  1716. beforeExpr
  1717. }),
  1718. questionDot: createToken("?."),
  1719. arrow: createToken("=>", {
  1720. beforeExpr
  1721. }),
  1722. template: createToken("template"),
  1723. ellipsis: createToken("...", {
  1724. beforeExpr
  1725. }),
  1726. backQuote: createToken("`", {
  1727. startsExpr
  1728. }),
  1729. dollarBraceL: createToken("${", {
  1730. beforeExpr,
  1731. startsExpr
  1732. }),
  1733. at: createToken("@"),
  1734. hash: createToken("#", {
  1735. startsExpr
  1736. }),
  1737. interpreterDirective: createToken("#!..."),
  1738. eq: createToken("=", {
  1739. beforeExpr,
  1740. isAssign
  1741. }),
  1742. assign: createToken("_=", {
  1743. beforeExpr,
  1744. isAssign
  1745. }),
  1746. slashAssign: createToken("_=", {
  1747. beforeExpr,
  1748. isAssign
  1749. }),
  1750. xorAssign: createToken("_=", {
  1751. beforeExpr,
  1752. isAssign
  1753. }),
  1754. moduloAssign: createToken("_=", {
  1755. beforeExpr,
  1756. isAssign
  1757. }),
  1758. incDec: createToken("++/--", {
  1759. prefix,
  1760. postfix,
  1761. startsExpr
  1762. }),
  1763. bang: createToken("!", {
  1764. beforeExpr,
  1765. prefix,
  1766. startsExpr
  1767. }),
  1768. tilde: createToken("~", {
  1769. beforeExpr,
  1770. prefix,
  1771. startsExpr
  1772. }),
  1773. pipeline: createBinop("|>", 0),
  1774. nullishCoalescing: createBinop("??", 1),
  1775. logicalOR: createBinop("||", 1),
  1776. logicalAND: createBinop("&&", 2),
  1777. bitwiseOR: createBinop("|", 3),
  1778. bitwiseXOR: createBinop("^", 4),
  1779. bitwiseAND: createBinop("&", 5),
  1780. equality: createBinop("==/!=/===/!==", 6),
  1781. lt: createBinop("</>/<=/>=", 7),
  1782. gt: createBinop("</>/<=/>=", 7),
  1783. relational: createBinop("</>/<=/>=", 7),
  1784. bitShift: createBinop("<</>>/>>>", 8),
  1785. plusMin: createToken("+/-", {
  1786. beforeExpr,
  1787. binop: 9,
  1788. prefix,
  1789. startsExpr
  1790. }),
  1791. modulo: createToken("%", {
  1792. binop: 10,
  1793. startsExpr
  1794. }),
  1795. star: createToken("*", {
  1796. binop: 10
  1797. }),
  1798. slash: createBinop("/", 10),
  1799. exponent: createToken("**", {
  1800. beforeExpr,
  1801. binop: 11,
  1802. rightAssociative: true
  1803. }),
  1804. _in: createKeyword("in", {
  1805. beforeExpr,
  1806. binop: 7
  1807. }),
  1808. _instanceof: createKeyword("instanceof", {
  1809. beforeExpr,
  1810. binop: 7
  1811. }),
  1812. _break: createKeyword("break"),
  1813. _case: createKeyword("case", {
  1814. beforeExpr
  1815. }),
  1816. _catch: createKeyword("catch"),
  1817. _continue: createKeyword("continue"),
  1818. _debugger: createKeyword("debugger"),
  1819. _default: createKeyword("default", {
  1820. beforeExpr
  1821. }),
  1822. _else: createKeyword("else", {
  1823. beforeExpr
  1824. }),
  1825. _finally: createKeyword("finally"),
  1826. _function: createKeyword("function", {
  1827. startsExpr
  1828. }),
  1829. _if: createKeyword("if"),
  1830. _return: createKeyword("return", {
  1831. beforeExpr
  1832. }),
  1833. _switch: createKeyword("switch"),
  1834. _throw: createKeyword("throw", {
  1835. beforeExpr,
  1836. prefix,
  1837. startsExpr
  1838. }),
  1839. _try: createKeyword("try"),
  1840. _var: createKeyword("var"),
  1841. _const: createKeyword("const"),
  1842. _with: createKeyword("with"),
  1843. _new: createKeyword("new", {
  1844. beforeExpr,
  1845. startsExpr
  1846. }),
  1847. _this: createKeyword("this", {
  1848. startsExpr
  1849. }),
  1850. _super: createKeyword("super", {
  1851. startsExpr
  1852. }),
  1853. _class: createKeyword("class", {
  1854. startsExpr
  1855. }),
  1856. _extends: createKeyword("extends", {
  1857. beforeExpr
  1858. }),
  1859. _export: createKeyword("export"),
  1860. _import: createKeyword("import", {
  1861. startsExpr
  1862. }),
  1863. _null: createKeyword("null", {
  1864. startsExpr
  1865. }),
  1866. _true: createKeyword("true", {
  1867. startsExpr
  1868. }),
  1869. _false: createKeyword("false", {
  1870. startsExpr
  1871. }),
  1872. _typeof: createKeyword("typeof", {
  1873. beforeExpr,
  1874. prefix,
  1875. startsExpr
  1876. }),
  1877. _void: createKeyword("void", {
  1878. beforeExpr,
  1879. prefix,
  1880. startsExpr
  1881. }),
  1882. _delete: createKeyword("delete", {
  1883. beforeExpr,
  1884. prefix,
  1885. startsExpr
  1886. }),
  1887. _do: createKeyword("do", {
  1888. isLoop,
  1889. beforeExpr
  1890. }),
  1891. _for: createKeyword("for", {
  1892. isLoop
  1893. }),
  1894. _while: createKeyword("while", {
  1895. isLoop
  1896. }),
  1897. _as: createKeywordLike("as", {
  1898. startsExpr
  1899. }),
  1900. _assert: createKeywordLike("assert", {
  1901. startsExpr
  1902. }),
  1903. _async: createKeywordLike("async", {
  1904. startsExpr
  1905. }),
  1906. _await: createKeywordLike("await", {
  1907. startsExpr
  1908. }),
  1909. _from: createKeywordLike("from", {
  1910. startsExpr
  1911. }),
  1912. _get: createKeywordLike("get", {
  1913. startsExpr
  1914. }),
  1915. _let: createKeywordLike("let", {
  1916. startsExpr
  1917. }),
  1918. _meta: createKeywordLike("meta", {
  1919. startsExpr
  1920. }),
  1921. _of: createKeywordLike("of", {
  1922. startsExpr
  1923. }),
  1924. _sent: createKeywordLike("sent", {
  1925. startsExpr
  1926. }),
  1927. _set: createKeywordLike("set", {
  1928. startsExpr
  1929. }),
  1930. _static: createKeywordLike("static", {
  1931. startsExpr
  1932. }),
  1933. _yield: createKeywordLike("yield", {
  1934. startsExpr
  1935. }),
  1936. _asserts: createKeywordLike("asserts", {
  1937. startsExpr
  1938. }),
  1939. _checks: createKeywordLike("checks", {
  1940. startsExpr
  1941. }),
  1942. _exports: createKeywordLike("exports", {
  1943. startsExpr
  1944. }),
  1945. _global: createKeywordLike("global", {
  1946. startsExpr
  1947. }),
  1948. _implements: createKeywordLike("implements", {
  1949. startsExpr
  1950. }),
  1951. _intrinsic: createKeywordLike("intrinsic", {
  1952. startsExpr
  1953. }),
  1954. _infer: createKeywordLike("infer", {
  1955. startsExpr
  1956. }),
  1957. _is: createKeywordLike("is", {
  1958. startsExpr
  1959. }),
  1960. _mixins: createKeywordLike("mixins", {
  1961. startsExpr
  1962. }),
  1963. _proto: createKeywordLike("proto", {
  1964. startsExpr
  1965. }),
  1966. _require: createKeywordLike("require", {
  1967. startsExpr
  1968. }),
  1969. _keyof: createKeywordLike("keyof", {
  1970. startsExpr
  1971. }),
  1972. _readonly: createKeywordLike("readonly", {
  1973. startsExpr
  1974. }),
  1975. _unique: createKeywordLike("unique", {
  1976. startsExpr
  1977. }),
  1978. _abstract: createKeywordLike("abstract", {
  1979. startsExpr
  1980. }),
  1981. _declare: createKeywordLike("declare", {
  1982. startsExpr
  1983. }),
  1984. _enum: createKeywordLike("enum", {
  1985. startsExpr
  1986. }),
  1987. _module: createKeywordLike("module", {
  1988. startsExpr
  1989. }),
  1990. _namespace: createKeywordLike("namespace", {
  1991. startsExpr
  1992. }),
  1993. _interface: createKeywordLike("interface", {
  1994. startsExpr
  1995. }),
  1996. _type: createKeywordLike("type", {
  1997. startsExpr
  1998. }),
  1999. _opaque: createKeywordLike("opaque", {
  2000. startsExpr
  2001. }),
  2002. name: createToken("name", {
  2003. startsExpr
  2004. }),
  2005. string: createToken("string", {
  2006. startsExpr
  2007. }),
  2008. num: createToken("num", {
  2009. startsExpr
  2010. }),
  2011. bigint: createToken("bigint", {
  2012. startsExpr
  2013. }),
  2014. decimal: createToken("decimal", {
  2015. startsExpr
  2016. }),
  2017. regexp: createToken("regexp", {
  2018. startsExpr
  2019. }),
  2020. privateName: createToken("#name", {
  2021. startsExpr
  2022. }),
  2023. eof: createToken("eof"),
  2024. jsxName: createToken("jsxName"),
  2025. jsxText: createToken("jsxText", {
  2026. beforeExpr: true
  2027. }),
  2028. jsxTagStart: createToken("jsxTagStart", {
  2029. startsExpr: true
  2030. }),
  2031. jsxTagEnd: createToken("jsxTagEnd"),
  2032. placeholder: createToken("%%", {
  2033. startsExpr: true
  2034. })
  2035. };
  2036. function tokenIsIdentifier(token) {
  2037. return token >= 87 && token <= 122;
  2038. }
  2039. function tokenKeywordOrIdentifierIsKeyword(token) {
  2040. return token <= 86;
  2041. }
  2042. function tokenIsKeywordOrIdentifier(token) {
  2043. return token >= 52 && token <= 122;
  2044. }
  2045. function tokenIsLiteralPropertyName(token) {
  2046. return token >= 52 && token <= 126;
  2047. }
  2048. function tokenComesBeforeExpression(token) {
  2049. return tokenBeforeExprs[token];
  2050. }
  2051. function tokenCanStartExpression(token) {
  2052. return tokenStartsExprs[token];
  2053. }
  2054. function tokenIsAssignment(token) {
  2055. return token >= 27 && token <= 31;
  2056. }
  2057. function tokenIsFlowInterfaceOrTypeOrOpaque(token) {
  2058. return token >= 119 && token <= 121;
  2059. }
  2060. function tokenIsLoop(token) {
  2061. return token >= 84 && token <= 86;
  2062. }
  2063. function tokenIsKeyword(token) {
  2064. return token >= 52 && token <= 86;
  2065. }
  2066. function tokenIsOperator(token) {
  2067. return token >= 35 && token <= 53;
  2068. }
  2069. function tokenIsPostfix(token) {
  2070. return token === 32;
  2071. }
  2072. function tokenIsPrefix(token) {
  2073. return tokenPrefixes[token];
  2074. }
  2075. function tokenIsTSTypeOperator(token) {
  2076. return token >= 111 && token <= 113;
  2077. }
  2078. function tokenIsTSDeclarationStart(token) {
  2079. return token >= 114 && token <= 120;
  2080. }
  2081. function tokenLabelName(token) {
  2082. return tokenLabels[token];
  2083. }
  2084. function tokenOperatorPrecedence(token) {
  2085. return tokenBinops[token];
  2086. }
  2087. function tokenIsRightAssociative(token) {
  2088. return token === 51;
  2089. }
  2090. function getExportedToken(token) {
  2091. return tokenTypes$1[token];
  2092. }
  2093. function isTokenType(obj) {
  2094. return typeof obj === "number";
  2095. }
  2096. {
  2097. tokenTypes$1[8].updateContext = context => {
  2098. context.pop();
  2099. };
  2100. tokenTypes$1[5].updateContext = tokenTypes$1[7].updateContext = tokenTypes$1[23].updateContext = context => {
  2101. context.push(types$1.brace);
  2102. };
  2103. tokenTypes$1[22].updateContext = context => {
  2104. if (context[context.length - 1] === types$1.template) {
  2105. context.pop();
  2106. } else {
  2107. context.push(types$1.template);
  2108. }
  2109. };
  2110. tokenTypes$1[132].updateContext = context => {
  2111. context.push(types$1.j_expr, types$1.j_oTag);
  2112. };
  2113. }
  2114. let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
  2115. let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
  2116. const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  2117. const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  2118. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  2119. const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1070, 4050, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 46, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 482, 44, 11, 6, 17, 0, 322, 29, 19, 43, 1269, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4152, 8, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938];
  2120. const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 357, 0, 62, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
  2121. function isInAstralSet(code, set) {
  2122. let pos = 0x10000;
  2123. for (let i = 0, length = set.length; i < length; i += 2) {
  2124. pos += set[i];
  2125. if (pos > code) return false;
  2126. pos += set[i + 1];
  2127. if (pos >= code) return true;
  2128. }
  2129. return false;
  2130. }
  2131. function isIdentifierStart(code) {
  2132. if (code < 65) return code === 36;
  2133. if (code <= 90) return true;
  2134. if (code < 97) return code === 95;
  2135. if (code <= 122) return true;
  2136. if (code <= 0xffff) {
  2137. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  2138. }
  2139. return isInAstralSet(code, astralIdentifierStartCodes);
  2140. }
  2141. function isIdentifierChar(code) {
  2142. if (code < 48) return code === 36;
  2143. if (code < 58) return true;
  2144. if (code < 65) return false;
  2145. if (code <= 90) return true;
  2146. if (code < 97) return code === 95;
  2147. if (code <= 122) return true;
  2148. if (code <= 0xffff) {
  2149. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  2150. }
  2151. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
  2152. }
  2153. const reservedWords = {
  2154. keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"],
  2155. strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
  2156. strictBind: ["eval", "arguments"]
  2157. };
  2158. const keywords = new Set(reservedWords.keyword);
  2159. const reservedWordsStrictSet = new Set(reservedWords.strict);
  2160. const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
  2161. function isReservedWord(word, inModule) {
  2162. return inModule && word === "await" || word === "enum";
  2163. }
  2164. function isStrictReservedWord(word, inModule) {
  2165. return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
  2166. }
  2167. function isStrictBindOnlyReservedWord(word) {
  2168. return reservedWordsStrictBindSet.has(word);
  2169. }
  2170. function isStrictBindReservedWord(word, inModule) {
  2171. return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
  2172. }
  2173. function isKeyword(word) {
  2174. return keywords.has(word);
  2175. }
  2176. function isIteratorStart(current, next) {
  2177. return current === 64 && next === 64;
  2178. }
  2179. const reservedWordLikeSet = new Set(["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete", "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield", "eval", "arguments", "enum", "await"]);
  2180. function canBeReservedWord(word) {
  2181. return reservedWordLikeSet.has(word);
  2182. }
  2183. const SCOPE_OTHER = 0b000000000,
  2184. SCOPE_PROGRAM = 0b000000001,
  2185. SCOPE_FUNCTION = 0b000000010,
  2186. SCOPE_ARROW = 0b000000100,
  2187. SCOPE_SIMPLE_CATCH = 0b000001000,
  2188. SCOPE_SUPER = 0b000010000,
  2189. SCOPE_DIRECT_SUPER = 0b000100000,
  2190. SCOPE_CLASS = 0b001000000,
  2191. SCOPE_STATIC_BLOCK = 0b010000000,
  2192. SCOPE_TS_MODULE = 0b100000000,
  2193. SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION | SCOPE_TS_MODULE;
  2194. const BIND_KIND_VALUE = 0b000000000001,
  2195. BIND_KIND_TYPE = 0b000000000010,
  2196. BIND_SCOPE_VAR = 0b000000000100,
  2197. BIND_SCOPE_LEXICAL = 0b000000001000,
  2198. BIND_SCOPE_FUNCTION = 0b000000010000,
  2199. BIND_FLAGS_NONE = 0b000001000000,
  2200. BIND_FLAGS_CLASS = 0b000010000000,
  2201. BIND_FLAGS_TS_ENUM = 0b000100000000,
  2202. BIND_FLAGS_TS_CONST_ENUM = 0b001000000000,
  2203. BIND_FLAGS_TS_EXPORT_ONLY = 0b010000000000,
  2204. BIND_FLAGS_FLOW_DECLARE_FN = 0b100000000000;
  2205. const BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS,
  2206. BIND_LEXICAL = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0,
  2207. BIND_VAR = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0,
  2208. BIND_FUNCTION = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0,
  2209. BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS,
  2210. BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0,
  2211. BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM,
  2212. BIND_TS_AMBIENT = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
  2213. BIND_NONE = 0 | 0 | 0 | BIND_FLAGS_NONE,
  2214. BIND_OUTSIDE = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE,
  2215. BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM,
  2216. BIND_TS_NAMESPACE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
  2217. BIND_FLOW_DECLARE_FN = BIND_FLAGS_FLOW_DECLARE_FN;
  2218. const CLASS_ELEMENT_FLAG_STATIC = 0b100,
  2219. CLASS_ELEMENT_KIND_GETTER = 0b010,
  2220. CLASS_ELEMENT_KIND_SETTER = 0b001,
  2221. CLASS_ELEMENT_KIND_ACCESSOR = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_KIND_SETTER;
  2222. const CLASS_ELEMENT_STATIC_GETTER = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_FLAG_STATIC,
  2223. CLASS_ELEMENT_STATIC_SETTER = CLASS_ELEMENT_KIND_SETTER | CLASS_ELEMENT_FLAG_STATIC,
  2224. CLASS_ELEMENT_INSTANCE_GETTER = CLASS_ELEMENT_KIND_GETTER,
  2225. CLASS_ELEMENT_INSTANCE_SETTER = CLASS_ELEMENT_KIND_SETTER,
  2226. CLASS_ELEMENT_OTHER = 0;
  2227. class Scope {
  2228. constructor(flags) {
  2229. this.var = new Set();
  2230. this.lexical = new Set();
  2231. this.functions = new Set();
  2232. this.flags = flags;
  2233. }
  2234. }
  2235. class ScopeHandler {
  2236. constructor(raise, inModule) {
  2237. this.scopeStack = [];
  2238. this.undefinedExports = new Map();
  2239. this.undefinedPrivateNames = new Map();
  2240. this.raise = raise;
  2241. this.inModule = inModule;
  2242. }
  2243. get inFunction() {
  2244. return (this.currentVarScopeFlags() & SCOPE_FUNCTION) > 0;
  2245. }
  2246. get allowSuper() {
  2247. return (this.currentThisScopeFlags() & SCOPE_SUPER) > 0;
  2248. }
  2249. get allowDirectSuper() {
  2250. return (this.currentThisScopeFlags() & SCOPE_DIRECT_SUPER) > 0;
  2251. }
  2252. get inClass() {
  2253. return (this.currentThisScopeFlags() & SCOPE_CLASS) > 0;
  2254. }
  2255. get inClassAndNotInNonArrowFunction() {
  2256. const flags = this.currentThisScopeFlags();
  2257. return (flags & SCOPE_CLASS) > 0 && (flags & SCOPE_FUNCTION) === 0;
  2258. }
  2259. get inStaticBlock() {
  2260. for (let i = this.scopeStack.length - 1;; i--) {
  2261. const {
  2262. flags
  2263. } = this.scopeStack[i];
  2264. if (flags & SCOPE_STATIC_BLOCK) {
  2265. return true;
  2266. }
  2267. if (flags & (SCOPE_VAR | SCOPE_CLASS)) {
  2268. return false;
  2269. }
  2270. }
  2271. }
  2272. get inNonArrowFunction() {
  2273. return (this.currentThisScopeFlags() & SCOPE_FUNCTION) > 0;
  2274. }
  2275. get treatFunctionsAsVar() {
  2276. return this.treatFunctionsAsVarInScope(this.currentScope());
  2277. }
  2278. createScope(flags) {
  2279. return new Scope(flags);
  2280. }
  2281. enter(flags) {
  2282. this.scopeStack.push(this.createScope(flags));
  2283. }
  2284. exit() {
  2285. this.scopeStack.pop();
  2286. }
  2287. treatFunctionsAsVarInScope(scope) {
  2288. return !!(scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_PROGRAM);
  2289. }
  2290. declareName(name, bindingType, pos) {
  2291. let scope = this.currentScope();
  2292. if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) {
  2293. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  2294. if (bindingType & BIND_SCOPE_FUNCTION) {
  2295. scope.functions.add(name);
  2296. } else {
  2297. scope.lexical.add(name);
  2298. }
  2299. if (bindingType & BIND_SCOPE_LEXICAL) {
  2300. this.maybeExportDefined(scope, name);
  2301. }
  2302. } else if (bindingType & BIND_SCOPE_VAR) {
  2303. for (let i = this.scopeStack.length - 1; i >= 0; --i) {
  2304. scope = this.scopeStack[i];
  2305. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  2306. scope.var.add(name);
  2307. this.maybeExportDefined(scope, name);
  2308. if (scope.flags & SCOPE_VAR) break;
  2309. }
  2310. }
  2311. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  2312. this.undefinedExports.delete(name);
  2313. }
  2314. }
  2315. maybeExportDefined(scope, name) {
  2316. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  2317. this.undefinedExports.delete(name);
  2318. }
  2319. }
  2320. checkRedeclarationInScope(scope, name, bindingType, pos) {
  2321. if (this.isRedeclaredInScope(scope, name, bindingType)) {
  2322. this.raise(pos, ErrorMessages.VarRedeclaration, name);
  2323. }
  2324. }
  2325. isRedeclaredInScope(scope, name, bindingType) {
  2326. if (!(bindingType & BIND_KIND_VALUE)) return false;
  2327. if (bindingType & BIND_SCOPE_LEXICAL) {
  2328. return scope.lexical.has(name) || scope.functions.has(name) || scope.var.has(name);
  2329. }
  2330. if (bindingType & BIND_SCOPE_FUNCTION) {
  2331. return scope.lexical.has(name) || !this.treatFunctionsAsVarInScope(scope) && scope.var.has(name);
  2332. }
  2333. return scope.lexical.has(name) && !(scope.flags & SCOPE_SIMPLE_CATCH && scope.lexical.values().next().value === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.has(name);
  2334. }
  2335. checkLocalExport(id) {
  2336. const {
  2337. name
  2338. } = id;
  2339. const topLevelScope = this.scopeStack[0];
  2340. if (!topLevelScope.lexical.has(name) && !topLevelScope.var.has(name) && !topLevelScope.functions.has(name)) {
  2341. this.undefinedExports.set(name, id.start);
  2342. }
  2343. }
  2344. currentScope() {
  2345. return this.scopeStack[this.scopeStack.length - 1];
  2346. }
  2347. currentVarScopeFlags() {
  2348. for (let i = this.scopeStack.length - 1;; i--) {
  2349. const {
  2350. flags
  2351. } = this.scopeStack[i];
  2352. if (flags & SCOPE_VAR) {
  2353. return flags;
  2354. }
  2355. }
  2356. }
  2357. currentThisScopeFlags() {
  2358. for (let i = this.scopeStack.length - 1;; i--) {
  2359. const {
  2360. flags
  2361. } = this.scopeStack[i];
  2362. if (flags & (SCOPE_VAR | SCOPE_CLASS) && !(flags & SCOPE_ARROW)) {
  2363. return flags;
  2364. }
  2365. }
  2366. }
  2367. }
  2368. class FlowScope extends Scope {
  2369. constructor(...args) {
  2370. super(...args);
  2371. this.declareFunctions = new Set();
  2372. }
  2373. }
  2374. class FlowScopeHandler extends ScopeHandler {
  2375. createScope(flags) {
  2376. return new FlowScope(flags);
  2377. }
  2378. declareName(name, bindingType, pos) {
  2379. const scope = this.currentScope();
  2380. if (bindingType & BIND_FLAGS_FLOW_DECLARE_FN) {
  2381. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  2382. this.maybeExportDefined(scope, name);
  2383. scope.declareFunctions.add(name);
  2384. return;
  2385. }
  2386. super.declareName(...arguments);
  2387. }
  2388. isRedeclaredInScope(scope, name, bindingType) {
  2389. if (super.isRedeclaredInScope(...arguments)) return true;
  2390. if (bindingType & BIND_FLAGS_FLOW_DECLARE_FN) {
  2391. return !scope.declareFunctions.has(name) && (scope.lexical.has(name) || scope.functions.has(name));
  2392. }
  2393. return false;
  2394. }
  2395. checkLocalExport(id) {
  2396. if (!this.scopeStack[0].declareFunctions.has(id.name)) {
  2397. super.checkLocalExport(id);
  2398. }
  2399. }
  2400. }
  2401. class State {
  2402. constructor() {
  2403. this.strict = void 0;
  2404. this.curLine = void 0;
  2405. this.lineStart = void 0;
  2406. this.startLoc = void 0;
  2407. this.endLoc = void 0;
  2408. this.errors = [];
  2409. this.potentialArrowAt = -1;
  2410. this.noArrowAt = [];
  2411. this.noArrowParamsConversionAt = [];
  2412. this.maybeInArrowParameters = false;
  2413. this.inType = false;
  2414. this.noAnonFunctionType = false;
  2415. this.hasFlowComment = false;
  2416. this.isAmbientContext = false;
  2417. this.inAbstractClass = false;
  2418. this.topicContext = {
  2419. maxNumOfResolvableTopics: 0,
  2420. maxTopicIndex: null
  2421. };
  2422. this.soloAwait = false;
  2423. this.inFSharpPipelineDirectBody = false;
  2424. this.labels = [];
  2425. this.decoratorStack = [[]];
  2426. this.comments = [];
  2427. this.commentStack = [];
  2428. this.pos = 0;
  2429. this.type = 129;
  2430. this.value = null;
  2431. this.start = 0;
  2432. this.end = 0;
  2433. this.lastTokEndLoc = null;
  2434. this.lastTokStartLoc = null;
  2435. this.lastTokStart = 0;
  2436. this.lastTokEnd = 0;
  2437. this.context = [types$1.brace];
  2438. this.canStartJSXElement = true;
  2439. this.containsEsc = false;
  2440. this.strictErrors = new Map();
  2441. this.tokensLength = 0;
  2442. }
  2443. init({
  2444. strictMode,
  2445. sourceType,
  2446. startLine,
  2447. startColumn
  2448. }) {
  2449. this.strict = strictMode === false ? false : strictMode === true ? true : sourceType === "module";
  2450. this.curLine = startLine;
  2451. this.lineStart = -startColumn;
  2452. this.startLoc = this.endLoc = new Position(startLine, startColumn);
  2453. }
  2454. curPosition() {
  2455. return new Position(this.curLine, this.pos - this.lineStart);
  2456. }
  2457. clone(skipArrays) {
  2458. const state = new State();
  2459. const keys = Object.keys(this);
  2460. for (let i = 0, length = keys.length; i < length; i++) {
  2461. const key = keys[i];
  2462. let val = this[key];
  2463. if (!skipArrays && Array.isArray(val)) {
  2464. val = val.slice();
  2465. }
  2466. state[key] = val;
  2467. }
  2468. return state;
  2469. }
  2470. }
  2471. var _isDigit = function isDigit(code) {
  2472. return code >= 48 && code <= 57;
  2473. };
  2474. const VALID_REGEX_FLAGS = new Set([103, 109, 115, 105, 121, 117, 100]);
  2475. const forbiddenNumericSeparatorSiblings = {
  2476. decBinOct: [46, 66, 69, 79, 95, 98, 101, 111],
  2477. hex: [46, 88, 95, 120]
  2478. };
  2479. const allowedNumericSeparatorSiblings = {};
  2480. allowedNumericSeparatorSiblings.bin = [48, 49];
  2481. allowedNumericSeparatorSiblings.oct = [...allowedNumericSeparatorSiblings.bin, 50, 51, 52, 53, 54, 55];
  2482. allowedNumericSeparatorSiblings.dec = [...allowedNumericSeparatorSiblings.oct, 56, 57];
  2483. allowedNumericSeparatorSiblings.hex = [...allowedNumericSeparatorSiblings.dec, 65, 66, 67, 68, 69, 70, 97, 98, 99, 100, 101, 102];
  2484. class Token {
  2485. constructor(state) {
  2486. this.type = state.type;
  2487. this.value = state.value;
  2488. this.start = state.start;
  2489. this.end = state.end;
  2490. this.loc = new SourceLocation(state.startLoc, state.endLoc);
  2491. }
  2492. }
  2493. class Tokenizer extends ParserError {
  2494. constructor(options, input) {
  2495. super();
  2496. this.isLookahead = void 0;
  2497. this.tokens = [];
  2498. this.state = new State();
  2499. this.state.init(options);
  2500. this.input = input;
  2501. this.length = input.length;
  2502. this.isLookahead = false;
  2503. }
  2504. pushToken(token) {
  2505. this.tokens.length = this.state.tokensLength;
  2506. this.tokens.push(token);
  2507. ++this.state.tokensLength;
  2508. }
  2509. next() {
  2510. this.checkKeywordEscapes();
  2511. if (this.options.tokens) {
  2512. this.pushToken(new Token(this.state));
  2513. }
  2514. this.state.lastTokEnd = this.state.end;
  2515. this.state.lastTokStart = this.state.start;
  2516. this.state.lastTokEndLoc = this.state.endLoc;
  2517. this.state.lastTokStartLoc = this.state.startLoc;
  2518. this.nextToken();
  2519. }
  2520. eat(type) {
  2521. if (this.match(type)) {
  2522. this.next();
  2523. return true;
  2524. } else {
  2525. return false;
  2526. }
  2527. }
  2528. match(type) {
  2529. return this.state.type === type;
  2530. }
  2531. createLookaheadState(state) {
  2532. return {
  2533. pos: state.pos,
  2534. value: null,
  2535. type: state.type,
  2536. start: state.start,
  2537. end: state.end,
  2538. lastTokEnd: state.end,
  2539. context: [this.curContext()],
  2540. inType: state.inType
  2541. };
  2542. }
  2543. lookahead() {
  2544. const old = this.state;
  2545. this.state = this.createLookaheadState(old);
  2546. this.isLookahead = true;
  2547. this.nextToken();
  2548. this.isLookahead = false;
  2549. const curr = this.state;
  2550. this.state = old;
  2551. return curr;
  2552. }
  2553. nextTokenStart() {
  2554. return this.nextTokenStartSince(this.state.pos);
  2555. }
  2556. nextTokenStartSince(pos) {
  2557. skipWhiteSpace.lastIndex = pos;
  2558. return skipWhiteSpace.test(this.input) ? skipWhiteSpace.lastIndex : pos;
  2559. }
  2560. lookaheadCharCode() {
  2561. return this.input.charCodeAt(this.nextTokenStart());
  2562. }
  2563. codePointAtPos(pos) {
  2564. let cp = this.input.charCodeAt(pos);
  2565. if ((cp & 0xfc00) === 0xd800 && ++pos < this.input.length) {
  2566. const trail = this.input.charCodeAt(pos);
  2567. if ((trail & 0xfc00) === 0xdc00) {
  2568. cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);
  2569. }
  2570. }
  2571. return cp;
  2572. }
  2573. setStrict(strict) {
  2574. this.state.strict = strict;
  2575. if (strict) {
  2576. this.state.strictErrors.forEach((message, pos) => this.raise(pos, message));
  2577. this.state.strictErrors.clear();
  2578. }
  2579. }
  2580. curContext() {
  2581. return this.state.context[this.state.context.length - 1];
  2582. }
  2583. nextToken() {
  2584. const curContext = this.curContext();
  2585. if (!curContext.preserveSpace) this.skipSpace();
  2586. this.state.start = this.state.pos;
  2587. if (!this.isLookahead) this.state.startLoc = this.state.curPosition();
  2588. if (this.state.pos >= this.length) {
  2589. this.finishToken(129);
  2590. return;
  2591. }
  2592. if (curContext === types$1.template) {
  2593. this.readTmplToken();
  2594. } else {
  2595. this.getTokenFromCode(this.codePointAtPos(this.state.pos));
  2596. }
  2597. }
  2598. skipBlockComment() {
  2599. let startLoc;
  2600. if (!this.isLookahead) startLoc = this.state.curPosition();
  2601. const start = this.state.pos;
  2602. const end = this.input.indexOf("*/", start + 2);
  2603. if (end === -1) throw this.raise(start, ErrorMessages.UnterminatedComment);
  2604. this.state.pos = end + 2;
  2605. lineBreakG.lastIndex = start + 2;
  2606. while (lineBreakG.test(this.input) && lineBreakG.lastIndex <= end) {
  2607. ++this.state.curLine;
  2608. this.state.lineStart = lineBreakG.lastIndex;
  2609. }
  2610. if (this.isLookahead) return;
  2611. const comment = {
  2612. type: "CommentBlock",
  2613. value: this.input.slice(start + 2, end),
  2614. start,
  2615. end: end + 2,
  2616. loc: new SourceLocation(startLoc, this.state.curPosition())
  2617. };
  2618. if (this.options.tokens) this.pushToken(comment);
  2619. return comment;
  2620. }
  2621. skipLineComment(startSkip) {
  2622. const start = this.state.pos;
  2623. let startLoc;
  2624. if (!this.isLookahead) startLoc = this.state.curPosition();
  2625. let ch = this.input.charCodeAt(this.state.pos += startSkip);
  2626. if (this.state.pos < this.length) {
  2627. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  2628. ch = this.input.charCodeAt(this.state.pos);
  2629. }
  2630. }
  2631. if (this.isLookahead) return;
  2632. const end = this.state.pos;
  2633. const value = this.input.slice(start + startSkip, end);
  2634. const comment = {
  2635. type: "CommentLine",
  2636. value,
  2637. start,
  2638. end,
  2639. loc: new SourceLocation(startLoc, this.state.curPosition())
  2640. };
  2641. if (this.options.tokens) this.pushToken(comment);
  2642. return comment;
  2643. }
  2644. skipSpace() {
  2645. const spaceStart = this.state.pos;
  2646. const comments = [];
  2647. loop: while (this.state.pos < this.length) {
  2648. const ch = this.input.charCodeAt(this.state.pos);
  2649. switch (ch) {
  2650. case 32:
  2651. case 160:
  2652. case 9:
  2653. ++this.state.pos;
  2654. break;
  2655. case 13:
  2656. if (this.input.charCodeAt(this.state.pos + 1) === 10) {
  2657. ++this.state.pos;
  2658. }
  2659. case 10:
  2660. case 8232:
  2661. case 8233:
  2662. ++this.state.pos;
  2663. ++this.state.curLine;
  2664. this.state.lineStart = this.state.pos;
  2665. break;
  2666. case 47:
  2667. switch (this.input.charCodeAt(this.state.pos + 1)) {
  2668. case 42:
  2669. {
  2670. const comment = this.skipBlockComment();
  2671. if (comment !== undefined) {
  2672. this.addComment(comment);
  2673. if (this.options.attachComment) comments.push(comment);
  2674. }
  2675. break;
  2676. }
  2677. case 47:
  2678. {
  2679. const comment = this.skipLineComment(2);
  2680. if (comment !== undefined) {
  2681. this.addComment(comment);
  2682. if (this.options.attachComment) comments.push(comment);
  2683. }
  2684. break;
  2685. }
  2686. default:
  2687. break loop;
  2688. }
  2689. break;
  2690. default:
  2691. if (isWhitespace(ch)) {
  2692. ++this.state.pos;
  2693. } else if (ch === 45 && !this.inModule) {
  2694. const pos = this.state.pos;
  2695. if (this.input.charCodeAt(pos + 1) === 45 && this.input.charCodeAt(pos + 2) === 62 && (spaceStart === 0 || this.state.lineStart > spaceStart)) {
  2696. const comment = this.skipLineComment(3);
  2697. if (comment !== undefined) {
  2698. this.addComment(comment);
  2699. if (this.options.attachComment) comments.push(comment);
  2700. }
  2701. } else {
  2702. break loop;
  2703. }
  2704. } else if (ch === 60 && !this.inModule) {
  2705. const pos = this.state.pos;
  2706. if (this.input.charCodeAt(pos + 1) === 33 && this.input.charCodeAt(pos + 2) === 45 && this.input.charCodeAt(pos + 3) === 45) {
  2707. const comment = this.skipLineComment(4);
  2708. if (comment !== undefined) {
  2709. this.addComment(comment);
  2710. if (this.options.attachComment) comments.push(comment);
  2711. }
  2712. } else {
  2713. break loop;
  2714. }
  2715. } else {
  2716. break loop;
  2717. }
  2718. }
  2719. }
  2720. if (comments.length > 0) {
  2721. const end = this.state.pos;
  2722. const CommentWhitespace = {
  2723. start: spaceStart,
  2724. end,
  2725. comments,
  2726. leadingNode: null,
  2727. trailingNode: null,
  2728. containingNode: null
  2729. };
  2730. this.state.commentStack.push(CommentWhitespace);
  2731. }
  2732. }
  2733. finishToken(type, val) {
  2734. this.state.end = this.state.pos;
  2735. const prevType = this.state.type;
  2736. this.state.type = type;
  2737. this.state.value = val;
  2738. if (!this.isLookahead) {
  2739. this.state.endLoc = this.state.curPosition();
  2740. this.updateContext(prevType);
  2741. }
  2742. }
  2743. replaceToken(type) {
  2744. this.state.type = type;
  2745. this.updateContext();
  2746. }
  2747. readToken_numberSign() {
  2748. if (this.state.pos === 0 && this.readToken_interpreter()) {
  2749. return;
  2750. }
  2751. const nextPos = this.state.pos + 1;
  2752. const next = this.codePointAtPos(nextPos);
  2753. if (next >= 48 && next <= 57) {
  2754. throw this.raise(this.state.pos, ErrorMessages.UnexpectedDigitAfterHash);
  2755. }
  2756. if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) {
  2757. this.expectPlugin("recordAndTuple");
  2758. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "hash") {
  2759. throw this.raise(this.state.pos, next === 123 ? ErrorMessages.RecordExpressionHashIncorrectStartSyntaxType : ErrorMessages.TupleExpressionHashIncorrectStartSyntaxType);
  2760. }
  2761. this.state.pos += 2;
  2762. if (next === 123) {
  2763. this.finishToken(7);
  2764. } else {
  2765. this.finishToken(1);
  2766. }
  2767. } else if (isIdentifierStart(next)) {
  2768. ++this.state.pos;
  2769. this.finishToken(128, this.readWord1(next));
  2770. } else if (next === 92) {
  2771. ++this.state.pos;
  2772. this.finishToken(128, this.readWord1());
  2773. } else {
  2774. this.finishOp(25, 1);
  2775. }
  2776. }
  2777. readToken_dot() {
  2778. const next = this.input.charCodeAt(this.state.pos + 1);
  2779. if (next >= 48 && next <= 57) {
  2780. this.readNumber(true);
  2781. return;
  2782. }
  2783. if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) {
  2784. this.state.pos += 3;
  2785. this.finishToken(21);
  2786. } else {
  2787. ++this.state.pos;
  2788. this.finishToken(16);
  2789. }
  2790. }
  2791. readToken_slash() {
  2792. const next = this.input.charCodeAt(this.state.pos + 1);
  2793. if (next === 61) {
  2794. this.finishOp(29, 2);
  2795. } else {
  2796. this.finishOp(50, 1);
  2797. }
  2798. }
  2799. readToken_interpreter() {
  2800. if (this.state.pos !== 0 || this.length < 2) return false;
  2801. let ch = this.input.charCodeAt(this.state.pos + 1);
  2802. if (ch !== 33) return false;
  2803. const start = this.state.pos;
  2804. this.state.pos += 1;
  2805. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  2806. ch = this.input.charCodeAt(this.state.pos);
  2807. }
  2808. const value = this.input.slice(start + 2, this.state.pos);
  2809. this.finishToken(26, value);
  2810. return true;
  2811. }
  2812. readToken_mult_modulo(code) {
  2813. let type = code === 42 ? 49 : 48;
  2814. let width = 1;
  2815. let next = this.input.charCodeAt(this.state.pos + 1);
  2816. if (code === 42 && next === 42) {
  2817. width++;
  2818. next = this.input.charCodeAt(this.state.pos + 2);
  2819. type = 51;
  2820. }
  2821. if (next === 61 && !this.state.inType) {
  2822. width++;
  2823. type = code === 37 ? 31 : 28;
  2824. }
  2825. this.finishOp(type, width);
  2826. }
  2827. readToken_pipe_amp(code) {
  2828. const next = this.input.charCodeAt(this.state.pos + 1);
  2829. if (next === code) {
  2830. if (this.input.charCodeAt(this.state.pos + 2) === 61) {
  2831. this.finishOp(28, 3);
  2832. } else {
  2833. this.finishOp(code === 124 ? 37 : 38, 2);
  2834. }
  2835. return;
  2836. }
  2837. if (code === 124) {
  2838. if (next === 62) {
  2839. this.finishOp(35, 2);
  2840. return;
  2841. }
  2842. if (this.hasPlugin("recordAndTuple") && next === 125) {
  2843. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2844. throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectEndSyntaxType);
  2845. }
  2846. this.state.pos += 2;
  2847. this.finishToken(9);
  2848. return;
  2849. }
  2850. if (this.hasPlugin("recordAndTuple") && next === 93) {
  2851. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2852. throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectEndSyntaxType);
  2853. }
  2854. this.state.pos += 2;
  2855. this.finishToken(4);
  2856. return;
  2857. }
  2858. }
  2859. if (next === 61) {
  2860. this.finishOp(28, 2);
  2861. return;
  2862. }
  2863. this.finishOp(code === 124 ? 39 : 41, 1);
  2864. }
  2865. readToken_caret() {
  2866. const next = this.input.charCodeAt(this.state.pos + 1);
  2867. if (next === 61 && !this.state.inType) {
  2868. this.finishOp(30, 2);
  2869. } else {
  2870. this.finishOp(40, 1);
  2871. }
  2872. }
  2873. readToken_plus_min(code) {
  2874. const next = this.input.charCodeAt(this.state.pos + 1);
  2875. if (next === code) {
  2876. this.finishOp(32, 2);
  2877. return;
  2878. }
  2879. if (next === 61) {
  2880. this.finishOp(28, 2);
  2881. } else {
  2882. this.finishOp(47, 1);
  2883. }
  2884. }
  2885. readToken_lt() {
  2886. const {
  2887. pos
  2888. } = this.state;
  2889. const next = this.input.charCodeAt(pos + 1);
  2890. if (next === 60) {
  2891. if (this.input.charCodeAt(pos + 2) === 61) {
  2892. this.finishOp(28, 3);
  2893. return;
  2894. }
  2895. this.finishOp(46, 2);
  2896. return;
  2897. }
  2898. if (next === 61) {
  2899. this.finishOp(45, 2);
  2900. return;
  2901. }
  2902. this.finishOp(43, 1);
  2903. }
  2904. readToken_gt() {
  2905. const {
  2906. pos
  2907. } = this.state;
  2908. const next = this.input.charCodeAt(pos + 1);
  2909. if (next === 62) {
  2910. const size = this.input.charCodeAt(pos + 2) === 62 ? 3 : 2;
  2911. if (this.input.charCodeAt(pos + size) === 61) {
  2912. this.finishOp(28, size + 1);
  2913. return;
  2914. }
  2915. this.finishOp(46, size);
  2916. return;
  2917. }
  2918. if (next === 61) {
  2919. this.finishOp(45, 2);
  2920. return;
  2921. }
  2922. this.finishOp(44, 1);
  2923. }
  2924. readToken_eq_excl(code) {
  2925. const next = this.input.charCodeAt(this.state.pos + 1);
  2926. if (next === 61) {
  2927. this.finishOp(42, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
  2928. return;
  2929. }
  2930. if (code === 61 && next === 62) {
  2931. this.state.pos += 2;
  2932. this.finishToken(19);
  2933. return;
  2934. }
  2935. this.finishOp(code === 61 ? 27 : 33, 1);
  2936. }
  2937. readToken_question() {
  2938. const next = this.input.charCodeAt(this.state.pos + 1);
  2939. const next2 = this.input.charCodeAt(this.state.pos + 2);
  2940. if (next === 63) {
  2941. if (next2 === 61) {
  2942. this.finishOp(28, 3);
  2943. } else {
  2944. this.finishOp(36, 2);
  2945. }
  2946. } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) {
  2947. this.state.pos += 2;
  2948. this.finishToken(18);
  2949. } else {
  2950. ++this.state.pos;
  2951. this.finishToken(17);
  2952. }
  2953. }
  2954. getTokenFromCode(code) {
  2955. switch (code) {
  2956. case 46:
  2957. this.readToken_dot();
  2958. return;
  2959. case 40:
  2960. ++this.state.pos;
  2961. this.finishToken(10);
  2962. return;
  2963. case 41:
  2964. ++this.state.pos;
  2965. this.finishToken(11);
  2966. return;
  2967. case 59:
  2968. ++this.state.pos;
  2969. this.finishToken(13);
  2970. return;
  2971. case 44:
  2972. ++this.state.pos;
  2973. this.finishToken(12);
  2974. return;
  2975. case 91:
  2976. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  2977. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2978. throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectStartSyntaxType);
  2979. }
  2980. this.state.pos += 2;
  2981. this.finishToken(2);
  2982. } else {
  2983. ++this.state.pos;
  2984. this.finishToken(0);
  2985. }
  2986. return;
  2987. case 93:
  2988. ++this.state.pos;
  2989. this.finishToken(3);
  2990. return;
  2991. case 123:
  2992. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  2993. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2994. throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectStartSyntaxType);
  2995. }
  2996. this.state.pos += 2;
  2997. this.finishToken(6);
  2998. } else {
  2999. ++this.state.pos;
  3000. this.finishToken(5);
  3001. }
  3002. return;
  3003. case 125:
  3004. ++this.state.pos;
  3005. this.finishToken(8);
  3006. return;
  3007. case 58:
  3008. if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
  3009. this.finishOp(15, 2);
  3010. } else {
  3011. ++this.state.pos;
  3012. this.finishToken(14);
  3013. }
  3014. return;
  3015. case 63:
  3016. this.readToken_question();
  3017. return;
  3018. case 96:
  3019. ++this.state.pos;
  3020. this.finishToken(22);
  3021. return;
  3022. case 48:
  3023. {
  3024. const next = this.input.charCodeAt(this.state.pos + 1);
  3025. if (next === 120 || next === 88) {
  3026. this.readRadixNumber(16);
  3027. return;
  3028. }
  3029. if (next === 111 || next === 79) {
  3030. this.readRadixNumber(8);
  3031. return;
  3032. }
  3033. if (next === 98 || next === 66) {
  3034. this.readRadixNumber(2);
  3035. return;
  3036. }
  3037. }
  3038. case 49:
  3039. case 50:
  3040. case 51:
  3041. case 52:
  3042. case 53:
  3043. case 54:
  3044. case 55:
  3045. case 56:
  3046. case 57:
  3047. this.readNumber(false);
  3048. return;
  3049. case 34:
  3050. case 39:
  3051. this.readString(code);
  3052. return;
  3053. case 47:
  3054. this.readToken_slash();
  3055. return;
  3056. case 37:
  3057. case 42:
  3058. this.readToken_mult_modulo(code);
  3059. return;
  3060. case 124:
  3061. case 38:
  3062. this.readToken_pipe_amp(code);
  3063. return;
  3064. case 94:
  3065. this.readToken_caret();
  3066. return;
  3067. case 43:
  3068. case 45:
  3069. this.readToken_plus_min(code);
  3070. return;
  3071. case 60:
  3072. this.readToken_lt();
  3073. return;
  3074. case 62:
  3075. this.readToken_gt();
  3076. return;
  3077. case 61:
  3078. case 33:
  3079. this.readToken_eq_excl(code);
  3080. return;
  3081. case 126:
  3082. this.finishOp(34, 1);
  3083. return;
  3084. case 64:
  3085. ++this.state.pos;
  3086. this.finishToken(24);
  3087. return;
  3088. case 35:
  3089. this.readToken_numberSign();
  3090. return;
  3091. case 92:
  3092. this.readWord();
  3093. return;
  3094. default:
  3095. if (isIdentifierStart(code)) {
  3096. this.readWord(code);
  3097. return;
  3098. }
  3099. }
  3100. throw this.raise(this.state.pos, ErrorMessages.InvalidOrUnexpectedToken, String.fromCodePoint(code));
  3101. }
  3102. finishOp(type, size) {
  3103. const str = this.input.slice(this.state.pos, this.state.pos + size);
  3104. this.state.pos += size;
  3105. this.finishToken(type, str);
  3106. }
  3107. readRegexp() {
  3108. const start = this.state.start + 1;
  3109. let escaped, inClass;
  3110. let {
  3111. pos
  3112. } = this.state;
  3113. for (;; ++pos) {
  3114. if (pos >= this.length) {
  3115. throw this.raise(start, ErrorMessages.UnterminatedRegExp);
  3116. }
  3117. const ch = this.input.charCodeAt(pos);
  3118. if (isNewLine(ch)) {
  3119. throw this.raise(start, ErrorMessages.UnterminatedRegExp);
  3120. }
  3121. if (escaped) {
  3122. escaped = false;
  3123. } else {
  3124. if (ch === 91) {
  3125. inClass = true;
  3126. } else if (ch === 93 && inClass) {
  3127. inClass = false;
  3128. } else if (ch === 47 && !inClass) {
  3129. break;
  3130. }
  3131. escaped = ch === 92;
  3132. }
  3133. }
  3134. const content = this.input.slice(start, pos);
  3135. ++pos;
  3136. let mods = "";
  3137. while (pos < this.length) {
  3138. const cp = this.codePointAtPos(pos);
  3139. const char = String.fromCharCode(cp);
  3140. if (VALID_REGEX_FLAGS.has(cp)) {
  3141. if (mods.includes(char)) {
  3142. this.raise(pos + 1, ErrorMessages.DuplicateRegExpFlags);
  3143. }
  3144. } else if (isIdentifierChar(cp) || cp === 92) {
  3145. this.raise(pos + 1, ErrorMessages.MalformedRegExpFlags);
  3146. } else {
  3147. break;
  3148. }
  3149. ++pos;
  3150. mods += char;
  3151. }
  3152. this.state.pos = pos;
  3153. this.finishToken(127, {
  3154. pattern: content,
  3155. flags: mods
  3156. });
  3157. }
  3158. readInt(radix, len, forceLen, allowNumSeparator = true) {
  3159. const start = this.state.pos;
  3160. const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct;
  3161. const allowedSiblings = radix === 16 ? allowedNumericSeparatorSiblings.hex : radix === 10 ? allowedNumericSeparatorSiblings.dec : radix === 8 ? allowedNumericSeparatorSiblings.oct : allowedNumericSeparatorSiblings.bin;
  3162. let invalid = false;
  3163. let total = 0;
  3164. for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  3165. const code = this.input.charCodeAt(this.state.pos);
  3166. let val;
  3167. if (code === 95) {
  3168. const prev = this.input.charCodeAt(this.state.pos - 1);
  3169. const next = this.input.charCodeAt(this.state.pos + 1);
  3170. if (allowedSiblings.indexOf(next) === -1) {
  3171. this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator);
  3172. } else if (forbiddenSiblings.indexOf(prev) > -1 || forbiddenSiblings.indexOf(next) > -1 || Number.isNaN(next)) {
  3173. this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator);
  3174. }
  3175. if (!allowNumSeparator) {
  3176. this.raise(this.state.pos, ErrorMessages.NumericSeparatorInEscapeSequence);
  3177. }
  3178. ++this.state.pos;
  3179. continue;
  3180. }
  3181. if (code >= 97) {
  3182. val = code - 97 + 10;
  3183. } else if (code >= 65) {
  3184. val = code - 65 + 10;
  3185. } else if (_isDigit(code)) {
  3186. val = code - 48;
  3187. } else {
  3188. val = Infinity;
  3189. }
  3190. if (val >= radix) {
  3191. if (this.options.errorRecovery && val <= 9) {
  3192. val = 0;
  3193. this.raise(this.state.start + i + 2, ErrorMessages.InvalidDigit, radix);
  3194. } else if (forceLen) {
  3195. val = 0;
  3196. invalid = true;
  3197. } else {
  3198. break;
  3199. }
  3200. }
  3201. ++this.state.pos;
  3202. total = total * radix + val;
  3203. }
  3204. if (this.state.pos === start || len != null && this.state.pos - start !== len || invalid) {
  3205. return null;
  3206. }
  3207. return total;
  3208. }
  3209. readRadixNumber(radix) {
  3210. const start = this.state.pos;
  3211. let isBigInt = false;
  3212. this.state.pos += 2;
  3213. const val = this.readInt(radix);
  3214. if (val == null) {
  3215. this.raise(this.state.start + 2, ErrorMessages.InvalidDigit, radix);
  3216. }
  3217. const next = this.input.charCodeAt(this.state.pos);
  3218. if (next === 110) {
  3219. ++this.state.pos;
  3220. isBigInt = true;
  3221. } else if (next === 109) {
  3222. throw this.raise(start, ErrorMessages.InvalidDecimal);
  3223. }
  3224. if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {
  3225. throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier);
  3226. }
  3227. if (isBigInt) {
  3228. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  3229. this.finishToken(125, str);
  3230. return;
  3231. }
  3232. this.finishToken(124, val);
  3233. }
  3234. readNumber(startsWithDot) {
  3235. const start = this.state.pos;
  3236. let isFloat = false;
  3237. let isBigInt = false;
  3238. let isDecimal = false;
  3239. let hasExponent = false;
  3240. let isOctal = false;
  3241. if (!startsWithDot && this.readInt(10) === null) {
  3242. this.raise(start, ErrorMessages.InvalidNumber);
  3243. }
  3244. const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  3245. if (hasLeadingZero) {
  3246. const integer = this.input.slice(start, this.state.pos);
  3247. this.recordStrictModeErrors(start, ErrorMessages.StrictOctalLiteral);
  3248. if (!this.state.strict) {
  3249. const underscorePos = integer.indexOf("_");
  3250. if (underscorePos > 0) {
  3251. this.raise(underscorePos + start, ErrorMessages.ZeroDigitNumericSeparator);
  3252. }
  3253. }
  3254. isOctal = hasLeadingZero && !/[89]/.test(integer);
  3255. }
  3256. let next = this.input.charCodeAt(this.state.pos);
  3257. if (next === 46 && !isOctal) {
  3258. ++this.state.pos;
  3259. this.readInt(10);
  3260. isFloat = true;
  3261. next = this.input.charCodeAt(this.state.pos);
  3262. }
  3263. if ((next === 69 || next === 101) && !isOctal) {
  3264. next = this.input.charCodeAt(++this.state.pos);
  3265. if (next === 43 || next === 45) {
  3266. ++this.state.pos;
  3267. }
  3268. if (this.readInt(10) === null) {
  3269. this.raise(start, ErrorMessages.InvalidOrMissingExponent);
  3270. }
  3271. isFloat = true;
  3272. hasExponent = true;
  3273. next = this.input.charCodeAt(this.state.pos);
  3274. }
  3275. if (next === 110) {
  3276. if (isFloat || hasLeadingZero) {
  3277. this.raise(start, ErrorMessages.InvalidBigIntLiteral);
  3278. }
  3279. ++this.state.pos;
  3280. isBigInt = true;
  3281. }
  3282. if (next === 109) {
  3283. this.expectPlugin("decimal", this.state.pos);
  3284. if (hasExponent || hasLeadingZero) {
  3285. this.raise(start, ErrorMessages.InvalidDecimal);
  3286. }
  3287. ++this.state.pos;
  3288. isDecimal = true;
  3289. }
  3290. if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {
  3291. throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier);
  3292. }
  3293. const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, "");
  3294. if (isBigInt) {
  3295. this.finishToken(125, str);
  3296. return;
  3297. }
  3298. if (isDecimal) {
  3299. this.finishToken(126, str);
  3300. return;
  3301. }
  3302. const val = isOctal ? parseInt(str, 8) : parseFloat(str);
  3303. this.finishToken(124, val);
  3304. }
  3305. readCodePoint(throwOnInvalid) {
  3306. const ch = this.input.charCodeAt(this.state.pos);
  3307. let code;
  3308. if (ch === 123) {
  3309. const codePos = ++this.state.pos;
  3310. code = this.readHexChar(this.input.indexOf("}", this.state.pos) - this.state.pos, true, throwOnInvalid);
  3311. ++this.state.pos;
  3312. if (code !== null && code > 0x10ffff) {
  3313. if (throwOnInvalid) {
  3314. this.raise(codePos, ErrorMessages.InvalidCodePoint);
  3315. } else {
  3316. return null;
  3317. }
  3318. }
  3319. } else {
  3320. code = this.readHexChar(4, false, throwOnInvalid);
  3321. }
  3322. return code;
  3323. }
  3324. readString(quote) {
  3325. let out = "",
  3326. chunkStart = ++this.state.pos;
  3327. for (;;) {
  3328. if (this.state.pos >= this.length) {
  3329. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  3330. }
  3331. const ch = this.input.charCodeAt(this.state.pos);
  3332. if (ch === quote) break;
  3333. if (ch === 92) {
  3334. out += this.input.slice(chunkStart, this.state.pos);
  3335. out += this.readEscapedChar(false);
  3336. chunkStart = this.state.pos;
  3337. } else if (ch === 8232 || ch === 8233) {
  3338. ++this.state.pos;
  3339. ++this.state.curLine;
  3340. this.state.lineStart = this.state.pos;
  3341. } else if (isNewLine(ch)) {
  3342. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  3343. } else {
  3344. ++this.state.pos;
  3345. }
  3346. }
  3347. out += this.input.slice(chunkStart, this.state.pos++);
  3348. this.finishToken(123, out);
  3349. }
  3350. readTmplToken() {
  3351. let out = "",
  3352. chunkStart = this.state.pos,
  3353. containsInvalid = false;
  3354. for (;;) {
  3355. if (this.state.pos >= this.length) {
  3356. throw this.raise(this.state.start, ErrorMessages.UnterminatedTemplate);
  3357. }
  3358. const ch = this.input.charCodeAt(this.state.pos);
  3359. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.state.pos + 1) === 123) {
  3360. if (this.state.pos === this.state.start && this.match(20)) {
  3361. if (ch === 36) {
  3362. this.state.pos += 2;
  3363. this.finishToken(23);
  3364. return;
  3365. } else {
  3366. ++this.state.pos;
  3367. this.finishToken(22);
  3368. return;
  3369. }
  3370. }
  3371. out += this.input.slice(chunkStart, this.state.pos);
  3372. this.finishToken(20, containsInvalid ? null : out);
  3373. return;
  3374. }
  3375. if (ch === 92) {
  3376. out += this.input.slice(chunkStart, this.state.pos);
  3377. const escaped = this.readEscapedChar(true);
  3378. if (escaped === null) {
  3379. containsInvalid = true;
  3380. } else {
  3381. out += escaped;
  3382. }
  3383. chunkStart = this.state.pos;
  3384. } else if (isNewLine(ch)) {
  3385. out += this.input.slice(chunkStart, this.state.pos);
  3386. ++this.state.pos;
  3387. switch (ch) {
  3388. case 13:
  3389. if (this.input.charCodeAt(this.state.pos) === 10) {
  3390. ++this.state.pos;
  3391. }
  3392. case 10:
  3393. out += "\n";
  3394. break;
  3395. default:
  3396. out += String.fromCharCode(ch);
  3397. break;
  3398. }
  3399. ++this.state.curLine;
  3400. this.state.lineStart = this.state.pos;
  3401. chunkStart = this.state.pos;
  3402. } else {
  3403. ++this.state.pos;
  3404. }
  3405. }
  3406. }
  3407. recordStrictModeErrors(pos, message) {
  3408. if (this.state.strict && !this.state.strictErrors.has(pos)) {
  3409. this.raise(pos, message);
  3410. } else {
  3411. this.state.strictErrors.set(pos, message);
  3412. }
  3413. }
  3414. readEscapedChar(inTemplate) {
  3415. const throwOnInvalid = !inTemplate;
  3416. const ch = this.input.charCodeAt(++this.state.pos);
  3417. ++this.state.pos;
  3418. switch (ch) {
  3419. case 110:
  3420. return "\n";
  3421. case 114:
  3422. return "\r";
  3423. case 120:
  3424. {
  3425. const code = this.readHexChar(2, false, throwOnInvalid);
  3426. return code === null ? null : String.fromCharCode(code);
  3427. }
  3428. case 117:
  3429. {
  3430. const code = this.readCodePoint(throwOnInvalid);
  3431. return code === null ? null : String.fromCodePoint(code);
  3432. }
  3433. case 116:
  3434. return "\t";
  3435. case 98:
  3436. return "\b";
  3437. case 118:
  3438. return "\u000b";
  3439. case 102:
  3440. return "\f";
  3441. case 13:
  3442. if (this.input.charCodeAt(this.state.pos) === 10) {
  3443. ++this.state.pos;
  3444. }
  3445. case 10:
  3446. this.state.lineStart = this.state.pos;
  3447. ++this.state.curLine;
  3448. case 8232:
  3449. case 8233:
  3450. return "";
  3451. case 56:
  3452. case 57:
  3453. if (inTemplate) {
  3454. return null;
  3455. } else {
  3456. this.recordStrictModeErrors(this.state.pos - 1, ErrorMessages.StrictNumericEscape);
  3457. }
  3458. default:
  3459. if (ch >= 48 && ch <= 55) {
  3460. const codePos = this.state.pos - 1;
  3461. const match = this.input.substr(this.state.pos - 1, 3).match(/^[0-7]+/);
  3462. let octalStr = match[0];
  3463. let octal = parseInt(octalStr, 8);
  3464. if (octal > 255) {
  3465. octalStr = octalStr.slice(0, -1);
  3466. octal = parseInt(octalStr, 8);
  3467. }
  3468. this.state.pos += octalStr.length - 1;
  3469. const next = this.input.charCodeAt(this.state.pos);
  3470. if (octalStr !== "0" || next === 56 || next === 57) {
  3471. if (inTemplate) {
  3472. return null;
  3473. } else {
  3474. this.recordStrictModeErrors(codePos, ErrorMessages.StrictNumericEscape);
  3475. }
  3476. }
  3477. return String.fromCharCode(octal);
  3478. }
  3479. return String.fromCharCode(ch);
  3480. }
  3481. }
  3482. readHexChar(len, forceLen, throwOnInvalid) {
  3483. const codePos = this.state.pos;
  3484. const n = this.readInt(16, len, forceLen, false);
  3485. if (n === null) {
  3486. if (throwOnInvalid) {
  3487. this.raise(codePos, ErrorMessages.InvalidEscapeSequence);
  3488. } else {
  3489. this.state.pos = codePos - 1;
  3490. }
  3491. }
  3492. return n;
  3493. }
  3494. readWord1(firstCode) {
  3495. this.state.containsEsc = false;
  3496. let word = "";
  3497. const start = this.state.pos;
  3498. let chunkStart = this.state.pos;
  3499. if (firstCode !== undefined) {
  3500. this.state.pos += firstCode <= 0xffff ? 1 : 2;
  3501. }
  3502. while (this.state.pos < this.length) {
  3503. const ch = this.codePointAtPos(this.state.pos);
  3504. if (isIdentifierChar(ch)) {
  3505. this.state.pos += ch <= 0xffff ? 1 : 2;
  3506. } else if (ch === 92) {
  3507. this.state.containsEsc = true;
  3508. word += this.input.slice(chunkStart, this.state.pos);
  3509. const escStart = this.state.pos;
  3510. const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar;
  3511. if (this.input.charCodeAt(++this.state.pos) !== 117) {
  3512. this.raise(this.state.pos, ErrorMessages.MissingUnicodeEscape);
  3513. chunkStart = this.state.pos - 1;
  3514. continue;
  3515. }
  3516. ++this.state.pos;
  3517. const esc = this.readCodePoint(true);
  3518. if (esc !== null) {
  3519. if (!identifierCheck(esc)) {
  3520. this.raise(escStart, ErrorMessages.EscapedCharNotAnIdentifier);
  3521. }
  3522. word += String.fromCodePoint(esc);
  3523. }
  3524. chunkStart = this.state.pos;
  3525. } else {
  3526. break;
  3527. }
  3528. }
  3529. return word + this.input.slice(chunkStart, this.state.pos);
  3530. }
  3531. readWord(firstCode) {
  3532. const word = this.readWord1(firstCode);
  3533. const type = keywords$1.get(word);
  3534. if (type !== undefined) {
  3535. this.finishToken(type, tokenLabelName(type));
  3536. } else {
  3537. this.finishToken(122, word);
  3538. }
  3539. }
  3540. checkKeywordEscapes() {
  3541. const {
  3542. type
  3543. } = this.state;
  3544. if (tokenIsKeyword(type) && this.state.containsEsc) {
  3545. this.raise(this.state.start, ErrorMessages.InvalidEscapedReservedWord, tokenLabelName(type));
  3546. }
  3547. }
  3548. updateContext(prevType) {
  3549. const {
  3550. context,
  3551. type
  3552. } = this.state;
  3553. switch (type) {
  3554. case 8:
  3555. context.pop();
  3556. break;
  3557. case 5:
  3558. case 7:
  3559. case 23:
  3560. context.push(types$1.brace);
  3561. break;
  3562. case 22:
  3563. if (context[context.length - 1] === types$1.template) {
  3564. context.pop();
  3565. } else {
  3566. context.push(types$1.template);
  3567. }
  3568. break;
  3569. }
  3570. }
  3571. }
  3572. class ClassScope {
  3573. constructor() {
  3574. this.privateNames = new Set();
  3575. this.loneAccessors = new Map();
  3576. this.undefinedPrivateNames = new Map();
  3577. }
  3578. }
  3579. class ClassScopeHandler {
  3580. constructor(raise) {
  3581. this.stack = [];
  3582. this.undefinedPrivateNames = new Map();
  3583. this.raise = raise;
  3584. }
  3585. current() {
  3586. return this.stack[this.stack.length - 1];
  3587. }
  3588. enter() {
  3589. this.stack.push(new ClassScope());
  3590. }
  3591. exit() {
  3592. const oldClassScope = this.stack.pop();
  3593. const current = this.current();
  3594. for (const [name, pos] of Array.from(oldClassScope.undefinedPrivateNames)) {
  3595. if (current) {
  3596. if (!current.undefinedPrivateNames.has(name)) {
  3597. current.undefinedPrivateNames.set(name, pos);
  3598. }
  3599. } else {
  3600. this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name);
  3601. }
  3602. }
  3603. }
  3604. declarePrivateName(name, elementType, pos) {
  3605. const classScope = this.current();
  3606. let redefined = classScope.privateNames.has(name);
  3607. if (elementType & CLASS_ELEMENT_KIND_ACCESSOR) {
  3608. const accessor = redefined && classScope.loneAccessors.get(name);
  3609. if (accessor) {
  3610. const oldStatic = accessor & CLASS_ELEMENT_FLAG_STATIC;
  3611. const newStatic = elementType & CLASS_ELEMENT_FLAG_STATIC;
  3612. const oldKind = accessor & CLASS_ELEMENT_KIND_ACCESSOR;
  3613. const newKind = elementType & CLASS_ELEMENT_KIND_ACCESSOR;
  3614. redefined = oldKind === newKind || oldStatic !== newStatic;
  3615. if (!redefined) classScope.loneAccessors.delete(name);
  3616. } else if (!redefined) {
  3617. classScope.loneAccessors.set(name, elementType);
  3618. }
  3619. }
  3620. if (redefined) {
  3621. this.raise(pos, ErrorMessages.PrivateNameRedeclaration, name);
  3622. }
  3623. classScope.privateNames.add(name);
  3624. classScope.undefinedPrivateNames.delete(name);
  3625. }
  3626. usePrivateName(name, pos) {
  3627. let classScope;
  3628. for (classScope of this.stack) {
  3629. if (classScope.privateNames.has(name)) return;
  3630. }
  3631. if (classScope) {
  3632. classScope.undefinedPrivateNames.set(name, pos);
  3633. } else {
  3634. this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name);
  3635. }
  3636. }
  3637. }
  3638. const kExpression = 0,
  3639. kMaybeArrowParameterDeclaration = 1,
  3640. kMaybeAsyncArrowParameterDeclaration = 2,
  3641. kParameterDeclaration = 3;
  3642. class ExpressionScope {
  3643. constructor(type = kExpression) {
  3644. this.type = void 0;
  3645. this.type = type;
  3646. }
  3647. canBeArrowParameterDeclaration() {
  3648. return this.type === kMaybeAsyncArrowParameterDeclaration || this.type === kMaybeArrowParameterDeclaration;
  3649. }
  3650. isCertainlyParameterDeclaration() {
  3651. return this.type === kParameterDeclaration;
  3652. }
  3653. }
  3654. class ArrowHeadParsingScope extends ExpressionScope {
  3655. constructor(type) {
  3656. super(type);
  3657. this.errors = new Map();
  3658. }
  3659. recordDeclarationError(pos, template) {
  3660. this.errors.set(pos, template);
  3661. }
  3662. clearDeclarationError(pos) {
  3663. this.errors.delete(pos);
  3664. }
  3665. iterateErrors(iterator) {
  3666. this.errors.forEach(iterator);
  3667. }
  3668. }
  3669. class ExpressionScopeHandler {
  3670. constructor(raise) {
  3671. this.stack = [new ExpressionScope()];
  3672. this.raise = raise;
  3673. }
  3674. enter(scope) {
  3675. this.stack.push(scope);
  3676. }
  3677. exit() {
  3678. this.stack.pop();
  3679. }
  3680. recordParameterInitializerError(pos, template) {
  3681. const {
  3682. stack
  3683. } = this;
  3684. let i = stack.length - 1;
  3685. let scope = stack[i];
  3686. while (!scope.isCertainlyParameterDeclaration()) {
  3687. if (scope.canBeArrowParameterDeclaration()) {
  3688. scope.recordDeclarationError(pos, template);
  3689. } else {
  3690. return;
  3691. }
  3692. scope = stack[--i];
  3693. }
  3694. this.raise(pos, template);
  3695. }
  3696. recordParenthesizedIdentifierError(pos, template) {
  3697. const {
  3698. stack
  3699. } = this;
  3700. const scope = stack[stack.length - 1];
  3701. if (scope.isCertainlyParameterDeclaration()) {
  3702. this.raise(pos, template);
  3703. } else if (scope.canBeArrowParameterDeclaration()) {
  3704. scope.recordDeclarationError(pos, template);
  3705. } else {
  3706. return;
  3707. }
  3708. }
  3709. recordAsyncArrowParametersError(pos, template) {
  3710. const {
  3711. stack
  3712. } = this;
  3713. let i = stack.length - 1;
  3714. let scope = stack[i];
  3715. while (scope.canBeArrowParameterDeclaration()) {
  3716. if (scope.type === kMaybeAsyncArrowParameterDeclaration) {
  3717. scope.recordDeclarationError(pos, template);
  3718. }
  3719. scope = stack[--i];
  3720. }
  3721. }
  3722. validateAsPattern() {
  3723. const {
  3724. stack
  3725. } = this;
  3726. const currentScope = stack[stack.length - 1];
  3727. if (!currentScope.canBeArrowParameterDeclaration()) return;
  3728. currentScope.iterateErrors((template, pos) => {
  3729. this.raise(pos, template);
  3730. let i = stack.length - 2;
  3731. let scope = stack[i];
  3732. while (scope.canBeArrowParameterDeclaration()) {
  3733. scope.clearDeclarationError(pos);
  3734. scope = stack[--i];
  3735. }
  3736. });
  3737. }
  3738. }
  3739. function newParameterDeclarationScope() {
  3740. return new ExpressionScope(kParameterDeclaration);
  3741. }
  3742. function newArrowHeadScope() {
  3743. return new ArrowHeadParsingScope(kMaybeArrowParameterDeclaration);
  3744. }
  3745. function newAsyncArrowScope() {
  3746. return new ArrowHeadParsingScope(kMaybeAsyncArrowParameterDeclaration);
  3747. }
  3748. function newExpressionScope() {
  3749. return new ExpressionScope();
  3750. }
  3751. const PARAM = 0b0000,
  3752. PARAM_YIELD = 0b0001,
  3753. PARAM_AWAIT = 0b0010,
  3754. PARAM_RETURN = 0b0100,
  3755. PARAM_IN = 0b1000;
  3756. class ProductionParameterHandler {
  3757. constructor() {
  3758. this.stacks = [];
  3759. }
  3760. enter(flags) {
  3761. this.stacks.push(flags);
  3762. }
  3763. exit() {
  3764. this.stacks.pop();
  3765. }
  3766. currentFlags() {
  3767. return this.stacks[this.stacks.length - 1];
  3768. }
  3769. get hasAwait() {
  3770. return (this.currentFlags() & PARAM_AWAIT) > 0;
  3771. }
  3772. get hasYield() {
  3773. return (this.currentFlags() & PARAM_YIELD) > 0;
  3774. }
  3775. get hasReturn() {
  3776. return (this.currentFlags() & PARAM_RETURN) > 0;
  3777. }
  3778. get hasIn() {
  3779. return (this.currentFlags() & PARAM_IN) > 0;
  3780. }
  3781. }
  3782. function functionFlags(isAsync, isGenerator) {
  3783. return (isAsync ? PARAM_AWAIT : 0) | (isGenerator ? PARAM_YIELD : 0);
  3784. }
  3785. class UtilParser extends Tokenizer {
  3786. addExtra(node, key, val) {
  3787. if (!node) return;
  3788. const extra = node.extra = node.extra || {};
  3789. extra[key] = val;
  3790. }
  3791. isContextual(token) {
  3792. return this.state.type === token && !this.state.containsEsc;
  3793. }
  3794. isUnparsedContextual(nameStart, name) {
  3795. const nameEnd = nameStart + name.length;
  3796. if (this.input.slice(nameStart, nameEnd) === name) {
  3797. const nextCh = this.input.charCodeAt(nameEnd);
  3798. return !(isIdentifierChar(nextCh) || (nextCh & 0xfc00) === 0xd800);
  3799. }
  3800. return false;
  3801. }
  3802. isLookaheadContextual(name) {
  3803. const next = this.nextTokenStart();
  3804. return this.isUnparsedContextual(next, name);
  3805. }
  3806. eatContextual(token) {
  3807. if (this.isContextual(token)) {
  3808. this.next();
  3809. return true;
  3810. }
  3811. return false;
  3812. }
  3813. expectContextual(token, template) {
  3814. if (!this.eatContextual(token)) this.unexpected(null, template);
  3815. }
  3816. canInsertSemicolon() {
  3817. return this.match(129) || this.match(8) || this.hasPrecedingLineBreak();
  3818. }
  3819. hasPrecedingLineBreak() {
  3820. return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
  3821. }
  3822. hasFollowingLineBreak() {
  3823. skipWhiteSpaceToLineBreak.lastIndex = this.state.end;
  3824. return skipWhiteSpaceToLineBreak.test(this.input);
  3825. }
  3826. isLineTerminator() {
  3827. return this.eat(13) || this.canInsertSemicolon();
  3828. }
  3829. semicolon(allowAsi = true) {
  3830. if (allowAsi ? this.isLineTerminator() : this.eat(13)) return;
  3831. this.raise(this.state.lastTokEnd, ErrorMessages.MissingSemicolon);
  3832. }
  3833. expect(type, pos) {
  3834. this.eat(type) || this.unexpected(pos, type);
  3835. }
  3836. assertNoSpace(message = "Unexpected space.") {
  3837. if (this.state.start > this.state.lastTokEnd) {
  3838. this.raise(this.state.lastTokEnd, {
  3839. code: ErrorCodes.SyntaxError,
  3840. reasonCode: "UnexpectedSpace",
  3841. template: message
  3842. });
  3843. }
  3844. }
  3845. unexpected(pos, messageOrType = {
  3846. code: ErrorCodes.SyntaxError,
  3847. reasonCode: "UnexpectedToken",
  3848. template: "Unexpected token"
  3849. }) {
  3850. if (isTokenType(messageOrType)) {
  3851. messageOrType = {
  3852. code: ErrorCodes.SyntaxError,
  3853. reasonCode: "UnexpectedToken",
  3854. template: `Unexpected token, expected "${tokenLabelName(messageOrType)}"`
  3855. };
  3856. }
  3857. throw this.raise(pos != null ? pos : this.state.start, messageOrType);
  3858. }
  3859. expectPlugin(name, pos) {
  3860. if (!this.hasPlugin(name)) {
  3861. throw this.raiseWithData(pos != null ? pos : this.state.start, {
  3862. missingPlugin: [name]
  3863. }, `This experimental syntax requires enabling the parser plugin: '${name}'`);
  3864. }
  3865. return true;
  3866. }
  3867. expectOnePlugin(names, pos) {
  3868. if (!names.some(n => this.hasPlugin(n))) {
  3869. throw this.raiseWithData(pos != null ? pos : this.state.start, {
  3870. missingPlugin: names
  3871. }, `This experimental syntax requires enabling one of the following parser plugin(s): '${names.join(", ")}'`);
  3872. }
  3873. }
  3874. tryParse(fn, oldState = this.state.clone()) {
  3875. const abortSignal = {
  3876. node: null
  3877. };
  3878. try {
  3879. const node = fn((node = null) => {
  3880. abortSignal.node = node;
  3881. throw abortSignal;
  3882. });
  3883. if (this.state.errors.length > oldState.errors.length) {
  3884. const failState = this.state;
  3885. this.state = oldState;
  3886. this.state.tokensLength = failState.tokensLength;
  3887. return {
  3888. node,
  3889. error: failState.errors[oldState.errors.length],
  3890. thrown: false,
  3891. aborted: false,
  3892. failState
  3893. };
  3894. }
  3895. return {
  3896. node,
  3897. error: null,
  3898. thrown: false,
  3899. aborted: false,
  3900. failState: null
  3901. };
  3902. } catch (error) {
  3903. const failState = this.state;
  3904. this.state = oldState;
  3905. if (error instanceof SyntaxError) {
  3906. return {
  3907. node: null,
  3908. error,
  3909. thrown: true,
  3910. aborted: false,
  3911. failState
  3912. };
  3913. }
  3914. if (error === abortSignal) {
  3915. return {
  3916. node: abortSignal.node,
  3917. error: null,
  3918. thrown: false,
  3919. aborted: true,
  3920. failState
  3921. };
  3922. }
  3923. throw error;
  3924. }
  3925. }
  3926. checkExpressionErrors(refExpressionErrors, andThrow) {
  3927. if (!refExpressionErrors) return false;
  3928. const {
  3929. shorthandAssign,
  3930. doubleProto,
  3931. optionalParameters
  3932. } = refExpressionErrors;
  3933. const hasErrors = shorthandAssign + doubleProto + optionalParameters > -3;
  3934. if (!andThrow) {
  3935. return hasErrors;
  3936. } else if (hasErrors) {
  3937. if (shorthandAssign >= 0) {
  3938. this.unexpected(shorthandAssign);
  3939. }
  3940. if (doubleProto >= 0) {
  3941. this.raise(doubleProto, ErrorMessages.DuplicateProto);
  3942. }
  3943. if (optionalParameters >= 0) {
  3944. this.unexpected(optionalParameters);
  3945. }
  3946. }
  3947. }
  3948. isLiteralPropertyName() {
  3949. return tokenIsLiteralPropertyName(this.state.type);
  3950. }
  3951. isPrivateName(node) {
  3952. return node.type === "PrivateName";
  3953. }
  3954. getPrivateNameSV(node) {
  3955. return node.id.name;
  3956. }
  3957. hasPropertyAsPrivateName(node) {
  3958. return (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") && this.isPrivateName(node.property);
  3959. }
  3960. isOptionalChain(node) {
  3961. return node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression";
  3962. }
  3963. isObjectProperty(node) {
  3964. return node.type === "ObjectProperty";
  3965. }
  3966. isObjectMethod(node) {
  3967. return node.type === "ObjectMethod";
  3968. }
  3969. initializeScopes(inModule = this.options.sourceType === "module") {
  3970. const oldLabels = this.state.labels;
  3971. this.state.labels = [];
  3972. const oldExportedIdentifiers = this.exportedIdentifiers;
  3973. this.exportedIdentifiers = new Set();
  3974. const oldInModule = this.inModule;
  3975. this.inModule = inModule;
  3976. const oldScope = this.scope;
  3977. const ScopeHandler = this.getScopeHandler();
  3978. this.scope = new ScopeHandler(this.raise.bind(this), this.inModule);
  3979. const oldProdParam = this.prodParam;
  3980. this.prodParam = new ProductionParameterHandler();
  3981. const oldClassScope = this.classScope;
  3982. this.classScope = new ClassScopeHandler(this.raise.bind(this));
  3983. const oldExpressionScope = this.expressionScope;
  3984. this.expressionScope = new ExpressionScopeHandler(this.raise.bind(this));
  3985. return () => {
  3986. this.state.labels = oldLabels;
  3987. this.exportedIdentifiers = oldExportedIdentifiers;
  3988. this.inModule = oldInModule;
  3989. this.scope = oldScope;
  3990. this.prodParam = oldProdParam;
  3991. this.classScope = oldClassScope;
  3992. this.expressionScope = oldExpressionScope;
  3993. };
  3994. }
  3995. enterInitialScopes() {
  3996. let paramFlags = PARAM;
  3997. if (this.inModule) {
  3998. paramFlags |= PARAM_AWAIT;
  3999. }
  4000. this.scope.enter(SCOPE_PROGRAM);
  4001. this.prodParam.enter(paramFlags);
  4002. }
  4003. }
  4004. class ExpressionErrors {
  4005. constructor() {
  4006. this.shorthandAssign = -1;
  4007. this.doubleProto = -1;
  4008. this.optionalParameters = -1;
  4009. }
  4010. }
  4011. let Node$5 = class Node {
  4012. constructor(parser, pos, loc) {
  4013. this.type = "";
  4014. this.start = pos;
  4015. this.end = 0;
  4016. this.loc = new SourceLocation(loc);
  4017. if (parser != null && parser.options.ranges) this.range = [pos, 0];
  4018. if (parser != null && parser.filename) this.loc.filename = parser.filename;
  4019. }
  4020. };
  4021. const NodePrototype = Node$5.prototype;
  4022. {
  4023. NodePrototype.__clone = function () {
  4024. const newNode = new Node$5();
  4025. const keys = Object.keys(this);
  4026. for (let i = 0, length = keys.length; i < length; i++) {
  4027. const key = keys[i];
  4028. if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") {
  4029. newNode[key] = this[key];
  4030. }
  4031. }
  4032. return newNode;
  4033. };
  4034. }
  4035. function clonePlaceholder(node) {
  4036. return cloneIdentifier(node);
  4037. }
  4038. function cloneIdentifier(node) {
  4039. const {
  4040. type,
  4041. start,
  4042. end,
  4043. loc,
  4044. range,
  4045. extra,
  4046. name
  4047. } = node;
  4048. const cloned = Object.create(NodePrototype);
  4049. cloned.type = type;
  4050. cloned.start = start;
  4051. cloned.end = end;
  4052. cloned.loc = loc;
  4053. cloned.range = range;
  4054. cloned.extra = extra;
  4055. cloned.name = name;
  4056. if (type === "Placeholder") {
  4057. cloned.expectedNode = node.expectedNode;
  4058. }
  4059. return cloned;
  4060. }
  4061. function cloneStringLiteral(node) {
  4062. const {
  4063. type,
  4064. start,
  4065. end,
  4066. loc,
  4067. range,
  4068. extra
  4069. } = node;
  4070. if (type === "Placeholder") {
  4071. return clonePlaceholder(node);
  4072. }
  4073. const cloned = Object.create(NodePrototype);
  4074. cloned.type = "StringLiteral";
  4075. cloned.start = start;
  4076. cloned.end = end;
  4077. cloned.loc = loc;
  4078. cloned.range = range;
  4079. cloned.extra = extra;
  4080. cloned.value = node.value;
  4081. return cloned;
  4082. }
  4083. class NodeUtils extends UtilParser {
  4084. startNode() {
  4085. return new Node$5(this, this.state.start, this.state.startLoc);
  4086. }
  4087. startNodeAt(pos, loc) {
  4088. return new Node$5(this, pos, loc);
  4089. }
  4090. startNodeAtNode(type) {
  4091. return this.startNodeAt(type.start, type.loc.start);
  4092. }
  4093. finishNode(node, type) {
  4094. return this.finishNodeAt(node, type, this.state.lastTokEnd, this.state.lastTokEndLoc);
  4095. }
  4096. finishNodeAt(node, type, pos, loc) {
  4097. node.type = type;
  4098. node.end = pos;
  4099. node.loc.end = loc;
  4100. if (this.options.ranges) node.range[1] = pos;
  4101. if (this.options.attachComment) this.processComment(node);
  4102. return node;
  4103. }
  4104. resetStartLocation(node, start, startLoc) {
  4105. node.start = start;
  4106. node.loc.start = startLoc;
  4107. if (this.options.ranges) node.range[0] = start;
  4108. }
  4109. resetEndLocation(node, end = this.state.lastTokEnd, endLoc = this.state.lastTokEndLoc) {
  4110. node.end = end;
  4111. node.loc.end = endLoc;
  4112. if (this.options.ranges) node.range[1] = end;
  4113. }
  4114. resetStartLocationFromNode(node, locationNode) {
  4115. this.resetStartLocation(node, locationNode.start, locationNode.loc.start);
  4116. }
  4117. }
  4118. const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]);
  4119. const FlowErrors = makeErrorTemplates({
  4120. AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",
  4121. AmbiguousDeclareModuleKind: "Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module.",
  4122. AssignReservedType: "Cannot overwrite reserved type %0.",
  4123. DeclareClassElement: "The `declare` modifier can only appear on class fields.",
  4124. DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.",
  4125. DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement.",
  4126. EnumBooleanMemberNotInitialized: "Boolean enum members need to be initialized. Use either `%0 = true,` or `%0 = false,` in enum `%1`.",
  4127. EnumDuplicateMemberName: "Enum member names need to be unique, but the name `%0` has already been used before in enum `%1`.",
  4128. EnumInconsistentMemberValues: "Enum `%0` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.",
  4129. EnumInvalidExplicitType: "Enum type `%1` is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  4130. EnumInvalidExplicitTypeUnknownSupplied: "Supplied enum type is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  4131. EnumInvalidMemberInitializerPrimaryType: "Enum `%0` has type `%2`, so the initializer of `%1` needs to be a %2 literal.",
  4132. EnumInvalidMemberInitializerSymbolType: "Symbol enum members cannot be initialized. Use `%1,` in enum `%0`.",
  4133. EnumInvalidMemberInitializerUnknownType: "The enum member initializer for `%1` needs to be a literal (either a boolean, number, or string) in enum `%0`.",
  4134. EnumInvalidMemberName: "Enum member names cannot start with lowercase 'a' through 'z'. Instead of using `%0`, consider using `%1`, in enum `%2`.",
  4135. EnumNumberMemberNotInitialized: "Number enum members need to be initialized, e.g. `%1 = 1` in enum `%0`.",
  4136. EnumStringMemberInconsistentlyInitailized: "String enum members need to consistently either all use initializers, or use no initializers, in enum `%0`.",
  4137. GetterMayNotHaveThisParam: "A getter cannot have a `this` parameter.",
  4138. ImportTypeShorthandOnlyInPureImport: "The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements.",
  4139. InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type.",
  4140. InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions.",
  4141. InexactVariance: "Explicit inexact syntax cannot have variance.",
  4142. InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`.",
  4143. MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",
  4144. NestedDeclareModule: "`declare module` cannot be used inside another `declare module`.",
  4145. NestedFlowComment: "Cannot have a flow comment inside another flow comment.",
  4146. PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.",
  4147. SetterMayNotHaveThisParam: "A setter cannot have a `this` parameter.",
  4148. SpreadVariance: "Spread properties cannot have variance.",
  4149. ThisParamAnnotationRequired: "A type annotation is required for the `this` parameter.",
  4150. ThisParamBannedInConstructor: "Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.",
  4151. ThisParamMayNotBeOptional: "The `this` parameter cannot be optional.",
  4152. ThisParamMustBeFirst: "The `this` parameter must be the first function parameter.",
  4153. ThisParamNoDefault: "The `this` parameter may not have a default value.",
  4154. TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",
  4155. TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis.",
  4156. UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object.",
  4157. UnexpectedReservedType: "Unexpected reserved type %0.",
  4158. UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new.",
  4159. UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.",
  4160. UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions.",
  4161. UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint".',
  4162. UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration.",
  4163. UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`.",
  4164. UnsupportedDeclareExportKind: "`declare export %0` is not supported. Use `%1` instead.",
  4165. UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module.",
  4166. UnterminatedFlowComment: "Unterminated flow-comment."
  4167. }, ErrorCodes.SyntaxError, "flow");
  4168. function isEsModuleType(bodyElement) {
  4169. return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration");
  4170. }
  4171. function hasTypeImportKind(node) {
  4172. return node.importKind === "type" || node.importKind === "typeof";
  4173. }
  4174. function isMaybeDefaultImport(type) {
  4175. return tokenIsKeywordOrIdentifier(type) && type !== 91;
  4176. }
  4177. const exportSuggestions = {
  4178. const: "declare export var",
  4179. let: "declare export var",
  4180. type: "export type",
  4181. interface: "export interface"
  4182. };
  4183. function partition(list, test) {
  4184. const list1 = [];
  4185. const list2 = [];
  4186. for (let i = 0; i < list.length; i++) {
  4187. (test(list[i], i, list) ? list1 : list2).push(list[i]);
  4188. }
  4189. return [list1, list2];
  4190. }
  4191. const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
  4192. var flow = (superClass => class extends superClass {
  4193. constructor(...args) {
  4194. super(...args);
  4195. this.flowPragma = undefined;
  4196. }
  4197. getScopeHandler() {
  4198. return FlowScopeHandler;
  4199. }
  4200. shouldParseTypes() {
  4201. return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
  4202. }
  4203. shouldParseEnums() {
  4204. return !!this.getPluginOption("flow", "enums");
  4205. }
  4206. finishToken(type, val) {
  4207. if (type !== 123 && type !== 13 && type !== 26) {
  4208. if (this.flowPragma === undefined) {
  4209. this.flowPragma = null;
  4210. }
  4211. }
  4212. return super.finishToken(type, val);
  4213. }
  4214. addComment(comment) {
  4215. if (this.flowPragma === undefined) {
  4216. const matches = FLOW_PRAGMA_REGEX.exec(comment.value);
  4217. if (!matches) ; else if (matches[1] === "flow") {
  4218. this.flowPragma = "flow";
  4219. } else if (matches[1] === "noflow") {
  4220. this.flowPragma = "noflow";
  4221. } else {
  4222. throw new Error("Unexpected flow pragma");
  4223. }
  4224. }
  4225. return super.addComment(comment);
  4226. }
  4227. flowParseTypeInitialiser(tok) {
  4228. const oldInType = this.state.inType;
  4229. this.state.inType = true;
  4230. this.expect(tok || 14);
  4231. const type = this.flowParseType();
  4232. this.state.inType = oldInType;
  4233. return type;
  4234. }
  4235. flowParsePredicate() {
  4236. const node = this.startNode();
  4237. const moduloPos = this.state.start;
  4238. this.next();
  4239. this.expectContextual(101);
  4240. if (this.state.lastTokStart > moduloPos + 1) {
  4241. this.raise(moduloPos, FlowErrors.UnexpectedSpaceBetweenModuloChecks);
  4242. }
  4243. if (this.eat(10)) {
  4244. node.value = this.parseExpression();
  4245. this.expect(11);
  4246. return this.finishNode(node, "DeclaredPredicate");
  4247. } else {
  4248. return this.finishNode(node, "InferredPredicate");
  4249. }
  4250. }
  4251. flowParseTypeAndPredicateInitialiser() {
  4252. const oldInType = this.state.inType;
  4253. this.state.inType = true;
  4254. this.expect(14);
  4255. let type = null;
  4256. let predicate = null;
  4257. if (this.match(48)) {
  4258. this.state.inType = oldInType;
  4259. predicate = this.flowParsePredicate();
  4260. } else {
  4261. type = this.flowParseType();
  4262. this.state.inType = oldInType;
  4263. if (this.match(48)) {
  4264. predicate = this.flowParsePredicate();
  4265. }
  4266. }
  4267. return [type, predicate];
  4268. }
  4269. flowParseDeclareClass(node) {
  4270. this.next();
  4271. this.flowParseInterfaceish(node, true);
  4272. return this.finishNode(node, "DeclareClass");
  4273. }
  4274. flowParseDeclareFunction(node) {
  4275. this.next();
  4276. const id = node.id = this.parseIdentifier();
  4277. const typeNode = this.startNode();
  4278. const typeContainer = this.startNode();
  4279. if (this.match(43)) {
  4280. typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
  4281. } else {
  4282. typeNode.typeParameters = null;
  4283. }
  4284. this.expect(10);
  4285. const tmp = this.flowParseFunctionTypeParams();
  4286. typeNode.params = tmp.params;
  4287. typeNode.rest = tmp.rest;
  4288. typeNode.this = tmp._this;
  4289. this.expect(11);
  4290. [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  4291. typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
  4292. id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
  4293. this.resetEndLocation(id);
  4294. this.semicolon();
  4295. this.scope.declareName(node.id.name, BIND_FLOW_DECLARE_FN, node.id.start);
  4296. return this.finishNode(node, "DeclareFunction");
  4297. }
  4298. flowParseDeclare(node, insideModule) {
  4299. if (this.match(74)) {
  4300. return this.flowParseDeclareClass(node);
  4301. } else if (this.match(62)) {
  4302. return this.flowParseDeclareFunction(node);
  4303. } else if (this.match(68)) {
  4304. return this.flowParseDeclareVariable(node);
  4305. } else if (this.eatContextual(117)) {
  4306. if (this.match(16)) {
  4307. return this.flowParseDeclareModuleExports(node);
  4308. } else {
  4309. if (insideModule) {
  4310. this.raise(this.state.lastTokStart, FlowErrors.NestedDeclareModule);
  4311. }
  4312. return this.flowParseDeclareModule(node);
  4313. }
  4314. } else if (this.isContextual(120)) {
  4315. return this.flowParseDeclareTypeAlias(node);
  4316. } else if (this.isContextual(121)) {
  4317. return this.flowParseDeclareOpaqueType(node);
  4318. } else if (this.isContextual(119)) {
  4319. return this.flowParseDeclareInterface(node);
  4320. } else if (this.match(76)) {
  4321. return this.flowParseDeclareExportDeclaration(node, insideModule);
  4322. } else {
  4323. throw this.unexpected();
  4324. }
  4325. }
  4326. flowParseDeclareVariable(node) {
  4327. this.next();
  4328. node.id = this.flowParseTypeAnnotatableIdentifier(true);
  4329. this.scope.declareName(node.id.name, BIND_VAR, node.id.start);
  4330. this.semicolon();
  4331. return this.finishNode(node, "DeclareVariable");
  4332. }
  4333. flowParseDeclareModule(node) {
  4334. this.scope.enter(SCOPE_OTHER);
  4335. if (this.match(123)) {
  4336. node.id = this.parseExprAtom();
  4337. } else {
  4338. node.id = this.parseIdentifier();
  4339. }
  4340. const bodyNode = node.body = this.startNode();
  4341. const body = bodyNode.body = [];
  4342. this.expect(5);
  4343. while (!this.match(8)) {
  4344. let bodyNode = this.startNode();
  4345. if (this.match(77)) {
  4346. this.next();
  4347. if (!this.isContextual(120) && !this.match(81)) {
  4348. this.raise(this.state.lastTokStart, FlowErrors.InvalidNonTypeImportInDeclareModule);
  4349. }
  4350. this.parseImport(bodyNode);
  4351. } else {
  4352. this.expectContextual(115, FlowErrors.UnsupportedStatementInDeclareModule);
  4353. bodyNode = this.flowParseDeclare(bodyNode, true);
  4354. }
  4355. body.push(bodyNode);
  4356. }
  4357. this.scope.exit();
  4358. this.expect(8);
  4359. this.finishNode(bodyNode, "BlockStatement");
  4360. let kind = null;
  4361. let hasModuleExport = false;
  4362. body.forEach(bodyElement => {
  4363. if (isEsModuleType(bodyElement)) {
  4364. if (kind === "CommonJS") {
  4365. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  4366. }
  4367. kind = "ES";
  4368. } else if (bodyElement.type === "DeclareModuleExports") {
  4369. if (hasModuleExport) {
  4370. this.raise(bodyElement.start, FlowErrors.DuplicateDeclareModuleExports);
  4371. }
  4372. if (kind === "ES") {
  4373. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  4374. }
  4375. kind = "CommonJS";
  4376. hasModuleExport = true;
  4377. }
  4378. });
  4379. node.kind = kind || "CommonJS";
  4380. return this.finishNode(node, "DeclareModule");
  4381. }
  4382. flowParseDeclareExportDeclaration(node, insideModule) {
  4383. this.expect(76);
  4384. if (this.eat(59)) {
  4385. if (this.match(62) || this.match(74)) {
  4386. node.declaration = this.flowParseDeclare(this.startNode());
  4387. } else {
  4388. node.declaration = this.flowParseType();
  4389. this.semicolon();
  4390. }
  4391. node.default = true;
  4392. return this.finishNode(node, "DeclareExportDeclaration");
  4393. } else {
  4394. if (this.match(69) || this.isLet() || (this.isContextual(120) || this.isContextual(119)) && !insideModule) {
  4395. const label = this.state.value;
  4396. const suggestion = exportSuggestions[label];
  4397. throw this.raise(this.state.start, FlowErrors.UnsupportedDeclareExportKind, label, suggestion);
  4398. }
  4399. if (this.match(68) || this.match(62) || this.match(74) || this.isContextual(121)) {
  4400. node.declaration = this.flowParseDeclare(this.startNode());
  4401. node.default = false;
  4402. return this.finishNode(node, "DeclareExportDeclaration");
  4403. } else if (this.match(49) || this.match(5) || this.isContextual(119) || this.isContextual(120) || this.isContextual(121)) {
  4404. node = this.parseExport(node);
  4405. if (node.type === "ExportNamedDeclaration") {
  4406. node.type = "ExportDeclaration";
  4407. node.default = false;
  4408. delete node.exportKind;
  4409. }
  4410. node.type = "Declare" + node.type;
  4411. return node;
  4412. }
  4413. }
  4414. throw this.unexpected();
  4415. }
  4416. flowParseDeclareModuleExports(node) {
  4417. this.next();
  4418. this.expectContextual(102);
  4419. node.typeAnnotation = this.flowParseTypeAnnotation();
  4420. this.semicolon();
  4421. return this.finishNode(node, "DeclareModuleExports");
  4422. }
  4423. flowParseDeclareTypeAlias(node) {
  4424. this.next();
  4425. this.flowParseTypeAlias(node);
  4426. node.type = "DeclareTypeAlias";
  4427. return node;
  4428. }
  4429. flowParseDeclareOpaqueType(node) {
  4430. this.next();
  4431. this.flowParseOpaqueType(node, true);
  4432. node.type = "DeclareOpaqueType";
  4433. return node;
  4434. }
  4435. flowParseDeclareInterface(node) {
  4436. this.next();
  4437. this.flowParseInterfaceish(node);
  4438. return this.finishNode(node, "DeclareInterface");
  4439. }
  4440. flowParseInterfaceish(node, isClass = false) {
  4441. node.id = this.flowParseRestrictedIdentifier(!isClass, true);
  4442. this.scope.declareName(node.id.name, isClass ? BIND_FUNCTION : BIND_LEXICAL, node.id.start);
  4443. if (this.match(43)) {
  4444. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4445. } else {
  4446. node.typeParameters = null;
  4447. }
  4448. node.extends = [];
  4449. node.implements = [];
  4450. node.mixins = [];
  4451. if (this.eat(75)) {
  4452. do {
  4453. node.extends.push(this.flowParseInterfaceExtends());
  4454. } while (!isClass && this.eat(12));
  4455. }
  4456. if (this.isContextual(108)) {
  4457. this.next();
  4458. do {
  4459. node.mixins.push(this.flowParseInterfaceExtends());
  4460. } while (this.eat(12));
  4461. }
  4462. if (this.isContextual(104)) {
  4463. this.next();
  4464. do {
  4465. node.implements.push(this.flowParseInterfaceExtends());
  4466. } while (this.eat(12));
  4467. }
  4468. node.body = this.flowParseObjectType({
  4469. allowStatic: isClass,
  4470. allowExact: false,
  4471. allowSpread: false,
  4472. allowProto: isClass,
  4473. allowInexact: false
  4474. });
  4475. }
  4476. flowParseInterfaceExtends() {
  4477. const node = this.startNode();
  4478. node.id = this.flowParseQualifiedTypeIdentifier();
  4479. if (this.match(43)) {
  4480. node.typeParameters = this.flowParseTypeParameterInstantiation();
  4481. } else {
  4482. node.typeParameters = null;
  4483. }
  4484. return this.finishNode(node, "InterfaceExtends");
  4485. }
  4486. flowParseInterface(node) {
  4487. this.flowParseInterfaceish(node);
  4488. return this.finishNode(node, "InterfaceDeclaration");
  4489. }
  4490. checkNotUnderscore(word) {
  4491. if (word === "_") {
  4492. this.raise(this.state.start, FlowErrors.UnexpectedReservedUnderscore);
  4493. }
  4494. }
  4495. checkReservedType(word, startLoc, declaration) {
  4496. if (!reservedTypes.has(word)) return;
  4497. this.raise(startLoc, declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, word);
  4498. }
  4499. flowParseRestrictedIdentifier(liberal, declaration) {
  4500. this.checkReservedType(this.state.value, this.state.start, declaration);
  4501. return this.parseIdentifier(liberal);
  4502. }
  4503. flowParseTypeAlias(node) {
  4504. node.id = this.flowParseRestrictedIdentifier(false, true);
  4505. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  4506. if (this.match(43)) {
  4507. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4508. } else {
  4509. node.typeParameters = null;
  4510. }
  4511. node.right = this.flowParseTypeInitialiser(27);
  4512. this.semicolon();
  4513. return this.finishNode(node, "TypeAlias");
  4514. }
  4515. flowParseOpaqueType(node, declare) {
  4516. this.expectContextual(120);
  4517. node.id = this.flowParseRestrictedIdentifier(true, true);
  4518. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  4519. if (this.match(43)) {
  4520. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4521. } else {
  4522. node.typeParameters = null;
  4523. }
  4524. node.supertype = null;
  4525. if (this.match(14)) {
  4526. node.supertype = this.flowParseTypeInitialiser(14);
  4527. }
  4528. node.impltype = null;
  4529. if (!declare) {
  4530. node.impltype = this.flowParseTypeInitialiser(27);
  4531. }
  4532. this.semicolon();
  4533. return this.finishNode(node, "OpaqueType");
  4534. }
  4535. flowParseTypeParameter(requireDefault = false) {
  4536. const nodeStart = this.state.start;
  4537. const node = this.startNode();
  4538. const variance = this.flowParseVariance();
  4539. const ident = this.flowParseTypeAnnotatableIdentifier();
  4540. node.name = ident.name;
  4541. node.variance = variance;
  4542. node.bound = ident.typeAnnotation;
  4543. if (this.match(27)) {
  4544. this.eat(27);
  4545. node.default = this.flowParseType();
  4546. } else {
  4547. if (requireDefault) {
  4548. this.raise(nodeStart, FlowErrors.MissingTypeParamDefault);
  4549. }
  4550. }
  4551. return this.finishNode(node, "TypeParameter");
  4552. }
  4553. flowParseTypeParameterDeclaration() {
  4554. const oldInType = this.state.inType;
  4555. const node = this.startNode();
  4556. node.params = [];
  4557. this.state.inType = true;
  4558. if (this.match(43) || this.match(132)) {
  4559. this.next();
  4560. } else {
  4561. this.unexpected();
  4562. }
  4563. let defaultRequired = false;
  4564. do {
  4565. const typeParameter = this.flowParseTypeParameter(defaultRequired);
  4566. node.params.push(typeParameter);
  4567. if (typeParameter.default) {
  4568. defaultRequired = true;
  4569. }
  4570. if (!this.match(44)) {
  4571. this.expect(12);
  4572. }
  4573. } while (!this.match(44));
  4574. this.expect(44);
  4575. this.state.inType = oldInType;
  4576. return this.finishNode(node, "TypeParameterDeclaration");
  4577. }
  4578. flowParseTypeParameterInstantiation() {
  4579. const node = this.startNode();
  4580. const oldInType = this.state.inType;
  4581. node.params = [];
  4582. this.state.inType = true;
  4583. this.expect(43);
  4584. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  4585. this.state.noAnonFunctionType = false;
  4586. while (!this.match(44)) {
  4587. node.params.push(this.flowParseType());
  4588. if (!this.match(44)) {
  4589. this.expect(12);
  4590. }
  4591. }
  4592. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  4593. this.expect(44);
  4594. this.state.inType = oldInType;
  4595. return this.finishNode(node, "TypeParameterInstantiation");
  4596. }
  4597. flowParseTypeParameterInstantiationCallOrNew() {
  4598. const node = this.startNode();
  4599. const oldInType = this.state.inType;
  4600. node.params = [];
  4601. this.state.inType = true;
  4602. this.expect(43);
  4603. while (!this.match(44)) {
  4604. node.params.push(this.flowParseTypeOrImplicitInstantiation());
  4605. if (!this.match(44)) {
  4606. this.expect(12);
  4607. }
  4608. }
  4609. this.expect(44);
  4610. this.state.inType = oldInType;
  4611. return this.finishNode(node, "TypeParameterInstantiation");
  4612. }
  4613. flowParseInterfaceType() {
  4614. const node = this.startNode();
  4615. this.expectContextual(119);
  4616. node.extends = [];
  4617. if (this.eat(75)) {
  4618. do {
  4619. node.extends.push(this.flowParseInterfaceExtends());
  4620. } while (this.eat(12));
  4621. }
  4622. node.body = this.flowParseObjectType({
  4623. allowStatic: false,
  4624. allowExact: false,
  4625. allowSpread: false,
  4626. allowProto: false,
  4627. allowInexact: false
  4628. });
  4629. return this.finishNode(node, "InterfaceTypeAnnotation");
  4630. }
  4631. flowParseObjectPropertyKey() {
  4632. return this.match(124) || this.match(123) ? this.parseExprAtom() : this.parseIdentifier(true);
  4633. }
  4634. flowParseObjectTypeIndexer(node, isStatic, variance) {
  4635. node.static = isStatic;
  4636. if (this.lookahead().type === 14) {
  4637. node.id = this.flowParseObjectPropertyKey();
  4638. node.key = this.flowParseTypeInitialiser();
  4639. } else {
  4640. node.id = null;
  4641. node.key = this.flowParseType();
  4642. }
  4643. this.expect(3);
  4644. node.value = this.flowParseTypeInitialiser();
  4645. node.variance = variance;
  4646. return this.finishNode(node, "ObjectTypeIndexer");
  4647. }
  4648. flowParseObjectTypeInternalSlot(node, isStatic) {
  4649. node.static = isStatic;
  4650. node.id = this.flowParseObjectPropertyKey();
  4651. this.expect(3);
  4652. this.expect(3);
  4653. if (this.match(43) || this.match(10)) {
  4654. node.method = true;
  4655. node.optional = false;
  4656. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  4657. } else {
  4658. node.method = false;
  4659. if (this.eat(17)) {
  4660. node.optional = true;
  4661. }
  4662. node.value = this.flowParseTypeInitialiser();
  4663. }
  4664. return this.finishNode(node, "ObjectTypeInternalSlot");
  4665. }
  4666. flowParseObjectTypeMethodish(node) {
  4667. node.params = [];
  4668. node.rest = null;
  4669. node.typeParameters = null;
  4670. node.this = null;
  4671. if (this.match(43)) {
  4672. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4673. }
  4674. this.expect(10);
  4675. if (this.match(72)) {
  4676. node.this = this.flowParseFunctionTypeParam(true);
  4677. node.this.name = null;
  4678. if (!this.match(11)) {
  4679. this.expect(12);
  4680. }
  4681. }
  4682. while (!this.match(11) && !this.match(21)) {
  4683. node.params.push(this.flowParseFunctionTypeParam(false));
  4684. if (!this.match(11)) {
  4685. this.expect(12);
  4686. }
  4687. }
  4688. if (this.eat(21)) {
  4689. node.rest = this.flowParseFunctionTypeParam(false);
  4690. }
  4691. this.expect(11);
  4692. node.returnType = this.flowParseTypeInitialiser();
  4693. return this.finishNode(node, "FunctionTypeAnnotation");
  4694. }
  4695. flowParseObjectTypeCallProperty(node, isStatic) {
  4696. const valueNode = this.startNode();
  4697. node.static = isStatic;
  4698. node.value = this.flowParseObjectTypeMethodish(valueNode);
  4699. return this.finishNode(node, "ObjectTypeCallProperty");
  4700. }
  4701. flowParseObjectType({
  4702. allowStatic,
  4703. allowExact,
  4704. allowSpread,
  4705. allowProto,
  4706. allowInexact
  4707. }) {
  4708. const oldInType = this.state.inType;
  4709. this.state.inType = true;
  4710. const nodeStart = this.startNode();
  4711. nodeStart.callProperties = [];
  4712. nodeStart.properties = [];
  4713. nodeStart.indexers = [];
  4714. nodeStart.internalSlots = [];
  4715. let endDelim;
  4716. let exact;
  4717. let inexact = false;
  4718. if (allowExact && this.match(6)) {
  4719. this.expect(6);
  4720. endDelim = 9;
  4721. exact = true;
  4722. } else {
  4723. this.expect(5);
  4724. endDelim = 8;
  4725. exact = false;
  4726. }
  4727. nodeStart.exact = exact;
  4728. while (!this.match(endDelim)) {
  4729. let isStatic = false;
  4730. let protoStart = null;
  4731. let inexactStart = null;
  4732. const node = this.startNode();
  4733. if (allowProto && this.isContextual(109)) {
  4734. const lookahead = this.lookahead();
  4735. if (lookahead.type !== 14 && lookahead.type !== 17) {
  4736. this.next();
  4737. protoStart = this.state.start;
  4738. allowStatic = false;
  4739. }
  4740. }
  4741. if (allowStatic && this.isContextual(98)) {
  4742. const lookahead = this.lookahead();
  4743. if (lookahead.type !== 14 && lookahead.type !== 17) {
  4744. this.next();
  4745. isStatic = true;
  4746. }
  4747. }
  4748. const variance = this.flowParseVariance();
  4749. if (this.eat(0)) {
  4750. if (protoStart != null) {
  4751. this.unexpected(protoStart);
  4752. }
  4753. if (this.eat(0)) {
  4754. if (variance) {
  4755. this.unexpected(variance.start);
  4756. }
  4757. nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic));
  4758. } else {
  4759. nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance));
  4760. }
  4761. } else if (this.match(10) || this.match(43)) {
  4762. if (protoStart != null) {
  4763. this.unexpected(protoStart);
  4764. }
  4765. if (variance) {
  4766. this.unexpected(variance.start);
  4767. }
  4768. nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic));
  4769. } else {
  4770. let kind = "init";
  4771. if (this.isContextual(92) || this.isContextual(97)) {
  4772. const lookahead = this.lookahead();
  4773. if (tokenIsLiteralPropertyName(lookahead.type)) {
  4774. kind = this.state.value;
  4775. this.next();
  4776. }
  4777. }
  4778. const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact);
  4779. if (propOrInexact === null) {
  4780. inexact = true;
  4781. inexactStart = this.state.lastTokStart;
  4782. } else {
  4783. nodeStart.properties.push(propOrInexact);
  4784. }
  4785. }
  4786. this.flowObjectTypeSemicolon();
  4787. if (inexactStart && !this.match(8) && !this.match(9)) {
  4788. this.raise(inexactStart, FlowErrors.UnexpectedExplicitInexactInObject);
  4789. }
  4790. }
  4791. this.expect(endDelim);
  4792. if (allowSpread) {
  4793. nodeStart.inexact = inexact;
  4794. }
  4795. const out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
  4796. this.state.inType = oldInType;
  4797. return out;
  4798. }
  4799. flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact) {
  4800. if (this.eat(21)) {
  4801. const isInexactToken = this.match(12) || this.match(13) || this.match(8) || this.match(9);
  4802. if (isInexactToken) {
  4803. if (!allowSpread) {
  4804. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideNonObject);
  4805. } else if (!allowInexact) {
  4806. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideExact);
  4807. }
  4808. if (variance) {
  4809. this.raise(variance.start, FlowErrors.InexactVariance);
  4810. }
  4811. return null;
  4812. }
  4813. if (!allowSpread) {
  4814. this.raise(this.state.lastTokStart, FlowErrors.UnexpectedSpreadType);
  4815. }
  4816. if (protoStart != null) {
  4817. this.unexpected(protoStart);
  4818. }
  4819. if (variance) {
  4820. this.raise(variance.start, FlowErrors.SpreadVariance);
  4821. }
  4822. node.argument = this.flowParseType();
  4823. return this.finishNode(node, "ObjectTypeSpreadProperty");
  4824. } else {
  4825. node.key = this.flowParseObjectPropertyKey();
  4826. node.static = isStatic;
  4827. node.proto = protoStart != null;
  4828. node.kind = kind;
  4829. let optional = false;
  4830. if (this.match(43) || this.match(10)) {
  4831. node.method = true;
  4832. if (protoStart != null) {
  4833. this.unexpected(protoStart);
  4834. }
  4835. if (variance) {
  4836. this.unexpected(variance.start);
  4837. }
  4838. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  4839. if (kind === "get" || kind === "set") {
  4840. this.flowCheckGetterSetterParams(node);
  4841. }
  4842. if (!allowSpread && node.key.name === "constructor" && node.value.this) {
  4843. this.raise(node.value.this.start, FlowErrors.ThisParamBannedInConstructor);
  4844. }
  4845. } else {
  4846. if (kind !== "init") this.unexpected();
  4847. node.method = false;
  4848. if (this.eat(17)) {
  4849. optional = true;
  4850. }
  4851. node.value = this.flowParseTypeInitialiser();
  4852. node.variance = variance;
  4853. }
  4854. node.optional = optional;
  4855. return this.finishNode(node, "ObjectTypeProperty");
  4856. }
  4857. }
  4858. flowCheckGetterSetterParams(property) {
  4859. const paramCount = property.kind === "get" ? 0 : 1;
  4860. const start = property.start;
  4861. const length = property.value.params.length + (property.value.rest ? 1 : 0);
  4862. if (property.value.this) {
  4863. this.raise(property.value.this.start, property.kind === "get" ? FlowErrors.GetterMayNotHaveThisParam : FlowErrors.SetterMayNotHaveThisParam);
  4864. }
  4865. if (length !== paramCount) {
  4866. if (property.kind === "get") {
  4867. this.raise(start, ErrorMessages.BadGetterArity);
  4868. } else {
  4869. this.raise(start, ErrorMessages.BadSetterArity);
  4870. }
  4871. }
  4872. if (property.kind === "set" && property.value.rest) {
  4873. this.raise(start, ErrorMessages.BadSetterRestParameter);
  4874. }
  4875. }
  4876. flowObjectTypeSemicolon() {
  4877. if (!this.eat(13) && !this.eat(12) && !this.match(8) && !this.match(9)) {
  4878. this.unexpected();
  4879. }
  4880. }
  4881. flowParseQualifiedTypeIdentifier(startPos, startLoc, id) {
  4882. startPos = startPos || this.state.start;
  4883. startLoc = startLoc || this.state.startLoc;
  4884. let node = id || this.flowParseRestrictedIdentifier(true);
  4885. while (this.eat(16)) {
  4886. const node2 = this.startNodeAt(startPos, startLoc);
  4887. node2.qualification = node;
  4888. node2.id = this.flowParseRestrictedIdentifier(true);
  4889. node = this.finishNode(node2, "QualifiedTypeIdentifier");
  4890. }
  4891. return node;
  4892. }
  4893. flowParseGenericType(startPos, startLoc, id) {
  4894. const node = this.startNodeAt(startPos, startLoc);
  4895. node.typeParameters = null;
  4896. node.id = this.flowParseQualifiedTypeIdentifier(startPos, startLoc, id);
  4897. if (this.match(43)) {
  4898. node.typeParameters = this.flowParseTypeParameterInstantiation();
  4899. }
  4900. return this.finishNode(node, "GenericTypeAnnotation");
  4901. }
  4902. flowParseTypeofType() {
  4903. const node = this.startNode();
  4904. this.expect(81);
  4905. node.argument = this.flowParsePrimaryType();
  4906. return this.finishNode(node, "TypeofTypeAnnotation");
  4907. }
  4908. flowParseTupleType() {
  4909. const node = this.startNode();
  4910. node.types = [];
  4911. this.expect(0);
  4912. while (this.state.pos < this.length && !this.match(3)) {
  4913. node.types.push(this.flowParseType());
  4914. if (this.match(3)) break;
  4915. this.expect(12);
  4916. }
  4917. this.expect(3);
  4918. return this.finishNode(node, "TupleTypeAnnotation");
  4919. }
  4920. flowParseFunctionTypeParam(first) {
  4921. let name = null;
  4922. let optional = false;
  4923. let typeAnnotation = null;
  4924. const node = this.startNode();
  4925. const lh = this.lookahead();
  4926. const isThis = this.state.type === 72;
  4927. if (lh.type === 14 || lh.type === 17) {
  4928. if (isThis && !first) {
  4929. this.raise(node.start, FlowErrors.ThisParamMustBeFirst);
  4930. }
  4931. name = this.parseIdentifier(isThis);
  4932. if (this.eat(17)) {
  4933. optional = true;
  4934. if (isThis) {
  4935. this.raise(node.start, FlowErrors.ThisParamMayNotBeOptional);
  4936. }
  4937. }
  4938. typeAnnotation = this.flowParseTypeInitialiser();
  4939. } else {
  4940. typeAnnotation = this.flowParseType();
  4941. }
  4942. node.name = name;
  4943. node.optional = optional;
  4944. node.typeAnnotation = typeAnnotation;
  4945. return this.finishNode(node, "FunctionTypeParam");
  4946. }
  4947. reinterpretTypeAsFunctionTypeParam(type) {
  4948. const node = this.startNodeAt(type.start, type.loc.start);
  4949. node.name = null;
  4950. node.optional = false;
  4951. node.typeAnnotation = type;
  4952. return this.finishNode(node, "FunctionTypeParam");
  4953. }
  4954. flowParseFunctionTypeParams(params = []) {
  4955. let rest = null;
  4956. let _this = null;
  4957. if (this.match(72)) {
  4958. _this = this.flowParseFunctionTypeParam(true);
  4959. _this.name = null;
  4960. if (!this.match(11)) {
  4961. this.expect(12);
  4962. }
  4963. }
  4964. while (!this.match(11) && !this.match(21)) {
  4965. params.push(this.flowParseFunctionTypeParam(false));
  4966. if (!this.match(11)) {
  4967. this.expect(12);
  4968. }
  4969. }
  4970. if (this.eat(21)) {
  4971. rest = this.flowParseFunctionTypeParam(false);
  4972. }
  4973. return {
  4974. params,
  4975. rest,
  4976. _this
  4977. };
  4978. }
  4979. flowIdentToTypeAnnotation(startPos, startLoc, node, id) {
  4980. switch (id.name) {
  4981. case "any":
  4982. return this.finishNode(node, "AnyTypeAnnotation");
  4983. case "bool":
  4984. case "boolean":
  4985. return this.finishNode(node, "BooleanTypeAnnotation");
  4986. case "mixed":
  4987. return this.finishNode(node, "MixedTypeAnnotation");
  4988. case "empty":
  4989. return this.finishNode(node, "EmptyTypeAnnotation");
  4990. case "number":
  4991. return this.finishNode(node, "NumberTypeAnnotation");
  4992. case "string":
  4993. return this.finishNode(node, "StringTypeAnnotation");
  4994. case "symbol":
  4995. return this.finishNode(node, "SymbolTypeAnnotation");
  4996. default:
  4997. this.checkNotUnderscore(id.name);
  4998. return this.flowParseGenericType(startPos, startLoc, id);
  4999. }
  5000. }
  5001. flowParsePrimaryType() {
  5002. const startPos = this.state.start;
  5003. const startLoc = this.state.startLoc;
  5004. const node = this.startNode();
  5005. let tmp;
  5006. let type;
  5007. let isGroupedType = false;
  5008. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  5009. switch (this.state.type) {
  5010. case 5:
  5011. return this.flowParseObjectType({
  5012. allowStatic: false,
  5013. allowExact: false,
  5014. allowSpread: true,
  5015. allowProto: false,
  5016. allowInexact: true
  5017. });
  5018. case 6:
  5019. return this.flowParseObjectType({
  5020. allowStatic: false,
  5021. allowExact: true,
  5022. allowSpread: true,
  5023. allowProto: false,
  5024. allowInexact: false
  5025. });
  5026. case 0:
  5027. this.state.noAnonFunctionType = false;
  5028. type = this.flowParseTupleType();
  5029. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  5030. return type;
  5031. case 43:
  5032. node.typeParameters = this.flowParseTypeParameterDeclaration();
  5033. this.expect(10);
  5034. tmp = this.flowParseFunctionTypeParams();
  5035. node.params = tmp.params;
  5036. node.rest = tmp.rest;
  5037. node.this = tmp._this;
  5038. this.expect(11);
  5039. this.expect(19);
  5040. node.returnType = this.flowParseType();
  5041. return this.finishNode(node, "FunctionTypeAnnotation");
  5042. case 10:
  5043. this.next();
  5044. if (!this.match(11) && !this.match(21)) {
  5045. if (tokenIsIdentifier(this.state.type) || this.match(72)) {
  5046. const token = this.lookahead().type;
  5047. isGroupedType = token !== 17 && token !== 14;
  5048. } else {
  5049. isGroupedType = true;
  5050. }
  5051. }
  5052. if (isGroupedType) {
  5053. this.state.noAnonFunctionType = false;
  5054. type = this.flowParseType();
  5055. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  5056. if (this.state.noAnonFunctionType || !(this.match(12) || this.match(11) && this.lookahead().type === 19)) {
  5057. this.expect(11);
  5058. return type;
  5059. } else {
  5060. this.eat(12);
  5061. }
  5062. }
  5063. if (type) {
  5064. tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
  5065. } else {
  5066. tmp = this.flowParseFunctionTypeParams();
  5067. }
  5068. node.params = tmp.params;
  5069. node.rest = tmp.rest;
  5070. node.this = tmp._this;
  5071. this.expect(11);
  5072. this.expect(19);
  5073. node.returnType = this.flowParseType();
  5074. node.typeParameters = null;
  5075. return this.finishNode(node, "FunctionTypeAnnotation");
  5076. case 123:
  5077. return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
  5078. case 79:
  5079. case 80:
  5080. node.value = this.match(79);
  5081. this.next();
  5082. return this.finishNode(node, "BooleanLiteralTypeAnnotation");
  5083. case 47:
  5084. if (this.state.value === "-") {
  5085. this.next();
  5086. if (this.match(124)) {
  5087. return this.parseLiteralAtNode(-this.state.value, "NumberLiteralTypeAnnotation", node);
  5088. }
  5089. if (this.match(125)) {
  5090. return this.parseLiteralAtNode(-this.state.value, "BigIntLiteralTypeAnnotation", node);
  5091. }
  5092. throw this.raise(this.state.start, FlowErrors.UnexpectedSubtractionOperand);
  5093. }
  5094. throw this.unexpected();
  5095. case 124:
  5096. return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
  5097. case 125:
  5098. return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation");
  5099. case 82:
  5100. this.next();
  5101. return this.finishNode(node, "VoidTypeAnnotation");
  5102. case 78:
  5103. this.next();
  5104. return this.finishNode(node, "NullLiteralTypeAnnotation");
  5105. case 72:
  5106. this.next();
  5107. return this.finishNode(node, "ThisTypeAnnotation");
  5108. case 49:
  5109. this.next();
  5110. return this.finishNode(node, "ExistsTypeAnnotation");
  5111. case 81:
  5112. return this.flowParseTypeofType();
  5113. default:
  5114. if (tokenIsKeyword(this.state.type)) {
  5115. const label = tokenLabelName(this.state.type);
  5116. this.next();
  5117. return super.createIdentifier(node, label);
  5118. } else if (tokenIsIdentifier(this.state.type)) {
  5119. if (this.isContextual(119)) {
  5120. return this.flowParseInterfaceType();
  5121. }
  5122. return this.flowIdentToTypeAnnotation(startPos, startLoc, node, this.parseIdentifier());
  5123. }
  5124. }
  5125. throw this.unexpected();
  5126. }
  5127. flowParsePostfixType() {
  5128. const startPos = this.state.start;
  5129. const startLoc = this.state.startLoc;
  5130. let type = this.flowParsePrimaryType();
  5131. let seenOptionalIndexedAccess = false;
  5132. while ((this.match(0) || this.match(18)) && !this.canInsertSemicolon()) {
  5133. const node = this.startNodeAt(startPos, startLoc);
  5134. const optional = this.eat(18);
  5135. seenOptionalIndexedAccess = seenOptionalIndexedAccess || optional;
  5136. this.expect(0);
  5137. if (!optional && this.match(3)) {
  5138. node.elementType = type;
  5139. this.next();
  5140. type = this.finishNode(node, "ArrayTypeAnnotation");
  5141. } else {
  5142. node.objectType = type;
  5143. node.indexType = this.flowParseType();
  5144. this.expect(3);
  5145. if (seenOptionalIndexedAccess) {
  5146. node.optional = optional;
  5147. type = this.finishNode(node, "OptionalIndexedAccessType");
  5148. } else {
  5149. type = this.finishNode(node, "IndexedAccessType");
  5150. }
  5151. }
  5152. }
  5153. return type;
  5154. }
  5155. flowParsePrefixType() {
  5156. const node = this.startNode();
  5157. if (this.eat(17)) {
  5158. node.typeAnnotation = this.flowParsePrefixType();
  5159. return this.finishNode(node, "NullableTypeAnnotation");
  5160. } else {
  5161. return this.flowParsePostfixType();
  5162. }
  5163. }
  5164. flowParseAnonFunctionWithoutParens() {
  5165. const param = this.flowParsePrefixType();
  5166. if (!this.state.noAnonFunctionType && this.eat(19)) {
  5167. const node = this.startNodeAt(param.start, param.loc.start);
  5168. node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
  5169. node.rest = null;
  5170. node.this = null;
  5171. node.returnType = this.flowParseType();
  5172. node.typeParameters = null;
  5173. return this.finishNode(node, "FunctionTypeAnnotation");
  5174. }
  5175. return param;
  5176. }
  5177. flowParseIntersectionType() {
  5178. const node = this.startNode();
  5179. this.eat(41);
  5180. const type = this.flowParseAnonFunctionWithoutParens();
  5181. node.types = [type];
  5182. while (this.eat(41)) {
  5183. node.types.push(this.flowParseAnonFunctionWithoutParens());
  5184. }
  5185. return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
  5186. }
  5187. flowParseUnionType() {
  5188. const node = this.startNode();
  5189. this.eat(39);
  5190. const type = this.flowParseIntersectionType();
  5191. node.types = [type];
  5192. while (this.eat(39)) {
  5193. node.types.push(this.flowParseIntersectionType());
  5194. }
  5195. return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
  5196. }
  5197. flowParseType() {
  5198. const oldInType = this.state.inType;
  5199. this.state.inType = true;
  5200. const type = this.flowParseUnionType();
  5201. this.state.inType = oldInType;
  5202. return type;
  5203. }
  5204. flowParseTypeOrImplicitInstantiation() {
  5205. if (this.state.type === 122 && this.state.value === "_") {
  5206. const startPos = this.state.start;
  5207. const startLoc = this.state.startLoc;
  5208. const node = this.parseIdentifier();
  5209. return this.flowParseGenericType(startPos, startLoc, node);
  5210. } else {
  5211. return this.flowParseType();
  5212. }
  5213. }
  5214. flowParseTypeAnnotation() {
  5215. const node = this.startNode();
  5216. node.typeAnnotation = this.flowParseTypeInitialiser();
  5217. return this.finishNode(node, "TypeAnnotation");
  5218. }
  5219. flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) {
  5220. const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier();
  5221. if (this.match(14)) {
  5222. ident.typeAnnotation = this.flowParseTypeAnnotation();
  5223. this.resetEndLocation(ident);
  5224. }
  5225. return ident;
  5226. }
  5227. typeCastToParameter(node) {
  5228. node.expression.typeAnnotation = node.typeAnnotation;
  5229. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  5230. return node.expression;
  5231. }
  5232. flowParseVariance() {
  5233. let variance = null;
  5234. if (this.match(47)) {
  5235. variance = this.startNode();
  5236. if (this.state.value === "+") {
  5237. variance.kind = "plus";
  5238. } else {
  5239. variance.kind = "minus";
  5240. }
  5241. this.next();
  5242. this.finishNode(variance, "Variance");
  5243. }
  5244. return variance;
  5245. }
  5246. parseFunctionBody(node, allowExpressionBody, isMethod = false) {
  5247. if (allowExpressionBody) {
  5248. return this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod));
  5249. }
  5250. return super.parseFunctionBody(node, false, isMethod);
  5251. }
  5252. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  5253. if (this.match(14)) {
  5254. const typeNode = this.startNode();
  5255. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  5256. node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
  5257. }
  5258. super.parseFunctionBodyAndFinish(node, type, isMethod);
  5259. }
  5260. parseStatement(context, topLevel) {
  5261. if (this.state.strict && this.isContextual(119)) {
  5262. const lookahead = this.lookahead();
  5263. if (tokenIsKeywordOrIdentifier(lookahead.type)) {
  5264. const node = this.startNode();
  5265. this.next();
  5266. return this.flowParseInterface(node);
  5267. }
  5268. } else if (this.shouldParseEnums() && this.isContextual(116)) {
  5269. const node = this.startNode();
  5270. this.next();
  5271. return this.flowParseEnumDeclaration(node);
  5272. }
  5273. const stmt = super.parseStatement(context, topLevel);
  5274. if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {
  5275. this.flowPragma = null;
  5276. }
  5277. return stmt;
  5278. }
  5279. parseExpressionStatement(node, expr) {
  5280. if (expr.type === "Identifier") {
  5281. if (expr.name === "declare") {
  5282. if (this.match(74) || tokenIsIdentifier(this.state.type) || this.match(62) || this.match(68) || this.match(76)) {
  5283. return this.flowParseDeclare(node);
  5284. }
  5285. } else if (tokenIsIdentifier(this.state.type)) {
  5286. if (expr.name === "interface") {
  5287. return this.flowParseInterface(node);
  5288. } else if (expr.name === "type") {
  5289. return this.flowParseTypeAlias(node);
  5290. } else if (expr.name === "opaque") {
  5291. return this.flowParseOpaqueType(node, false);
  5292. }
  5293. }
  5294. }
  5295. return super.parseExpressionStatement(node, expr);
  5296. }
  5297. shouldParseExportDeclaration() {
  5298. const {
  5299. type
  5300. } = this.state;
  5301. if (tokenIsFlowInterfaceOrTypeOrOpaque(type) || this.shouldParseEnums() && type === 116) {
  5302. return !this.state.containsEsc;
  5303. }
  5304. return super.shouldParseExportDeclaration();
  5305. }
  5306. isExportDefaultSpecifier() {
  5307. const {
  5308. type
  5309. } = this.state;
  5310. if (tokenIsFlowInterfaceOrTypeOrOpaque(type) || this.shouldParseEnums() && type === 116) {
  5311. return this.state.containsEsc;
  5312. }
  5313. return super.isExportDefaultSpecifier();
  5314. }
  5315. parseExportDefaultExpression() {
  5316. if (this.shouldParseEnums() && this.isContextual(116)) {
  5317. const node = this.startNode();
  5318. this.next();
  5319. return this.flowParseEnumDeclaration(node);
  5320. }
  5321. return super.parseExportDefaultExpression();
  5322. }
  5323. parseConditional(expr, startPos, startLoc, refExpressionErrors) {
  5324. if (!this.match(17)) return expr;
  5325. if (this.state.maybeInArrowParameters) {
  5326. const nextCh = this.lookaheadCharCode();
  5327. if (nextCh === 44 || nextCh === 61 || nextCh === 58 || nextCh === 41) {
  5328. this.setOptionalParametersError(refExpressionErrors);
  5329. return expr;
  5330. }
  5331. }
  5332. this.expect(17);
  5333. const state = this.state.clone();
  5334. const originalNoArrowAt = this.state.noArrowAt;
  5335. const node = this.startNodeAt(startPos, startLoc);
  5336. let {
  5337. consequent,
  5338. failed
  5339. } = this.tryParseConditionalConsequent();
  5340. let [valid, invalid] = this.getArrowLikeExpressions(consequent);
  5341. if (failed || invalid.length > 0) {
  5342. const noArrowAt = [...originalNoArrowAt];
  5343. if (invalid.length > 0) {
  5344. this.state = state;
  5345. this.state.noArrowAt = noArrowAt;
  5346. for (let i = 0; i < invalid.length; i++) {
  5347. noArrowAt.push(invalid[i].start);
  5348. }
  5349. ({
  5350. consequent,
  5351. failed
  5352. } = this.tryParseConditionalConsequent());
  5353. [valid, invalid] = this.getArrowLikeExpressions(consequent);
  5354. }
  5355. if (failed && valid.length > 1) {
  5356. this.raise(state.start, FlowErrors.AmbiguousConditionalArrow);
  5357. }
  5358. if (failed && valid.length === 1) {
  5359. this.state = state;
  5360. noArrowAt.push(valid[0].start);
  5361. this.state.noArrowAt = noArrowAt;
  5362. ({
  5363. consequent,
  5364. failed
  5365. } = this.tryParseConditionalConsequent());
  5366. }
  5367. }
  5368. this.getArrowLikeExpressions(consequent, true);
  5369. this.state.noArrowAt = originalNoArrowAt;
  5370. this.expect(14);
  5371. node.test = expr;
  5372. node.consequent = consequent;
  5373. node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(undefined, undefined));
  5374. return this.finishNode(node, "ConditionalExpression");
  5375. }
  5376. tryParseConditionalConsequent() {
  5377. this.state.noArrowParamsConversionAt.push(this.state.start);
  5378. const consequent = this.parseMaybeAssignAllowIn();
  5379. const failed = !this.match(14);
  5380. this.state.noArrowParamsConversionAt.pop();
  5381. return {
  5382. consequent,
  5383. failed
  5384. };
  5385. }
  5386. getArrowLikeExpressions(node, disallowInvalid) {
  5387. const stack = [node];
  5388. const arrows = [];
  5389. while (stack.length !== 0) {
  5390. const node = stack.pop();
  5391. if (node.type === "ArrowFunctionExpression") {
  5392. if (node.typeParameters || !node.returnType) {
  5393. this.finishArrowValidation(node);
  5394. } else {
  5395. arrows.push(node);
  5396. }
  5397. stack.push(node.body);
  5398. } else if (node.type === "ConditionalExpression") {
  5399. stack.push(node.consequent);
  5400. stack.push(node.alternate);
  5401. }
  5402. }
  5403. if (disallowInvalid) {
  5404. arrows.forEach(node => this.finishArrowValidation(node));
  5405. return [arrows, []];
  5406. }
  5407. return partition(arrows, node => node.params.every(param => this.isAssignable(param, true)));
  5408. }
  5409. finishArrowValidation(node) {
  5410. var _node$extra;
  5411. this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingComma, false);
  5412. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  5413. super.checkParams(node, false, true);
  5414. this.scope.exit();
  5415. }
  5416. forwardNoArrowParamsConversionAt(node, parse) {
  5417. let result;
  5418. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  5419. this.state.noArrowParamsConversionAt.push(this.state.start);
  5420. result = parse();
  5421. this.state.noArrowParamsConversionAt.pop();
  5422. } else {
  5423. result = parse();
  5424. }
  5425. return result;
  5426. }
  5427. parseParenItem(node, startPos, startLoc) {
  5428. node = super.parseParenItem(node, startPos, startLoc);
  5429. if (this.eat(17)) {
  5430. node.optional = true;
  5431. this.resetEndLocation(node);
  5432. }
  5433. if (this.match(14)) {
  5434. const typeCastNode = this.startNodeAt(startPos, startLoc);
  5435. typeCastNode.expression = node;
  5436. typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
  5437. return this.finishNode(typeCastNode, "TypeCastExpression");
  5438. }
  5439. return node;
  5440. }
  5441. assertModuleNodeAllowed(node) {
  5442. if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") {
  5443. return;
  5444. }
  5445. super.assertModuleNodeAllowed(node);
  5446. }
  5447. parseExport(node) {
  5448. const decl = super.parseExport(node);
  5449. if (decl.type === "ExportNamedDeclaration" || decl.type === "ExportAllDeclaration") {
  5450. decl.exportKind = decl.exportKind || "value";
  5451. }
  5452. return decl;
  5453. }
  5454. parseExportDeclaration(node) {
  5455. if (this.isContextual(120)) {
  5456. node.exportKind = "type";
  5457. const declarationNode = this.startNode();
  5458. this.next();
  5459. if (this.match(5)) {
  5460. node.specifiers = this.parseExportSpecifiers(true);
  5461. this.parseExportFrom(node);
  5462. return null;
  5463. } else {
  5464. return this.flowParseTypeAlias(declarationNode);
  5465. }
  5466. } else if (this.isContextual(121)) {
  5467. node.exportKind = "type";
  5468. const declarationNode = this.startNode();
  5469. this.next();
  5470. return this.flowParseOpaqueType(declarationNode, false);
  5471. } else if (this.isContextual(119)) {
  5472. node.exportKind = "type";
  5473. const declarationNode = this.startNode();
  5474. this.next();
  5475. return this.flowParseInterface(declarationNode);
  5476. } else if (this.shouldParseEnums() && this.isContextual(116)) {
  5477. node.exportKind = "value";
  5478. const declarationNode = this.startNode();
  5479. this.next();
  5480. return this.flowParseEnumDeclaration(declarationNode);
  5481. } else {
  5482. return super.parseExportDeclaration(node);
  5483. }
  5484. }
  5485. eatExportStar(node) {
  5486. if (super.eatExportStar(...arguments)) return true;
  5487. if (this.isContextual(120) && this.lookahead().type === 49) {
  5488. node.exportKind = "type";
  5489. this.next();
  5490. this.next();
  5491. return true;
  5492. }
  5493. return false;
  5494. }
  5495. maybeParseExportNamespaceSpecifier(node) {
  5496. const pos = this.state.start;
  5497. const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);
  5498. if (hasNamespace && node.exportKind === "type") {
  5499. this.unexpected(pos);
  5500. }
  5501. return hasNamespace;
  5502. }
  5503. parseClassId(node, isStatement, optionalId) {
  5504. super.parseClassId(node, isStatement, optionalId);
  5505. if (this.match(43)) {
  5506. node.typeParameters = this.flowParseTypeParameterDeclaration();
  5507. }
  5508. }
  5509. parseClassMember(classBody, member, state) {
  5510. const pos = this.state.start;
  5511. if (this.isContextual(115)) {
  5512. if (this.parseClassMemberFromModifier(classBody, member)) {
  5513. return;
  5514. }
  5515. member.declare = true;
  5516. }
  5517. super.parseClassMember(classBody, member, state);
  5518. if (member.declare) {
  5519. if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty" && member.type !== "PropertyDefinition") {
  5520. this.raise(pos, FlowErrors.DeclareClassElement);
  5521. } else if (member.value) {
  5522. this.raise(member.value.start, FlowErrors.DeclareClassFieldInitializer);
  5523. }
  5524. }
  5525. }
  5526. isIterator(word) {
  5527. return word === "iterator" || word === "asyncIterator";
  5528. }
  5529. readIterator() {
  5530. const word = super.readWord1();
  5531. const fullWord = "@@" + word;
  5532. if (!this.isIterator(word) || !this.state.inType) {
  5533. this.raise(this.state.pos, ErrorMessages.InvalidIdentifier, fullWord);
  5534. }
  5535. this.finishToken(122, fullWord);
  5536. }
  5537. getTokenFromCode(code) {
  5538. const next = this.input.charCodeAt(this.state.pos + 1);
  5539. if (code === 123 && next === 124) {
  5540. return this.finishOp(6, 2);
  5541. } else if (this.state.inType && (code === 62 || code === 60)) {
  5542. return this.finishOp(code === 62 ? 44 : 43, 1);
  5543. } else if (this.state.inType && code === 63) {
  5544. if (next === 46) {
  5545. return this.finishOp(18, 2);
  5546. }
  5547. return this.finishOp(17, 1);
  5548. } else if (isIteratorStart(code, next)) {
  5549. this.state.pos += 2;
  5550. return this.readIterator();
  5551. } else {
  5552. return super.getTokenFromCode(code);
  5553. }
  5554. }
  5555. isAssignable(node, isBinding) {
  5556. if (node.type === "TypeCastExpression") {
  5557. return this.isAssignable(node.expression, isBinding);
  5558. } else {
  5559. return super.isAssignable(node, isBinding);
  5560. }
  5561. }
  5562. toAssignable(node, isLHS = false) {
  5563. if (node.type === "TypeCastExpression") {
  5564. return super.toAssignable(this.typeCastToParameter(node), isLHS);
  5565. } else {
  5566. return super.toAssignable(node, isLHS);
  5567. }
  5568. }
  5569. toAssignableList(exprList, trailingCommaPos, isLHS) {
  5570. for (let i = 0; i < exprList.length; i++) {
  5571. const expr = exprList[i];
  5572. if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") {
  5573. exprList[i] = this.typeCastToParameter(expr);
  5574. }
  5575. }
  5576. return super.toAssignableList(exprList, trailingCommaPos, isLHS);
  5577. }
  5578. toReferencedList(exprList, isParenthesizedExpr) {
  5579. for (let i = 0; i < exprList.length; i++) {
  5580. var _expr$extra;
  5581. const expr = exprList[i];
  5582. if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) != null && _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) {
  5583. this.raise(expr.typeAnnotation.start, FlowErrors.TypeCastInPattern);
  5584. }
  5585. }
  5586. return exprList;
  5587. }
  5588. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  5589. const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors);
  5590. if (canBePattern && !this.state.maybeInArrowParameters) {
  5591. this.toReferencedList(node.elements);
  5592. }
  5593. return node;
  5594. }
  5595. checkLVal(expr, ...args) {
  5596. if (expr.type !== "TypeCastExpression") {
  5597. return super.checkLVal(expr, ...args);
  5598. }
  5599. }
  5600. parseClassProperty(node) {
  5601. if (this.match(14)) {
  5602. node.typeAnnotation = this.flowParseTypeAnnotation();
  5603. }
  5604. return super.parseClassProperty(node);
  5605. }
  5606. parseClassPrivateProperty(node) {
  5607. if (this.match(14)) {
  5608. node.typeAnnotation = this.flowParseTypeAnnotation();
  5609. }
  5610. return super.parseClassPrivateProperty(node);
  5611. }
  5612. isClassMethod() {
  5613. return this.match(43) || super.isClassMethod();
  5614. }
  5615. isClassProperty() {
  5616. return this.match(14) || super.isClassProperty();
  5617. }
  5618. isNonstaticConstructor(method) {
  5619. return !this.match(14) && super.isNonstaticConstructor(method);
  5620. }
  5621. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  5622. if (method.variance) {
  5623. this.unexpected(method.variance.start);
  5624. }
  5625. delete method.variance;
  5626. if (this.match(43)) {
  5627. method.typeParameters = this.flowParseTypeParameterDeclaration();
  5628. }
  5629. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  5630. if (method.params && isConstructor) {
  5631. const params = method.params;
  5632. if (params.length > 0 && this.isThisParam(params[0])) {
  5633. this.raise(method.start, FlowErrors.ThisParamBannedInConstructor);
  5634. }
  5635. } else if (method.type === "MethodDefinition" && isConstructor && method.value.params) {
  5636. const params = method.value.params;
  5637. if (params.length > 0 && this.isThisParam(params[0])) {
  5638. this.raise(method.start, FlowErrors.ThisParamBannedInConstructor);
  5639. }
  5640. }
  5641. }
  5642. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  5643. if (method.variance) {
  5644. this.unexpected(method.variance.start);
  5645. }
  5646. delete method.variance;
  5647. if (this.match(43)) {
  5648. method.typeParameters = this.flowParseTypeParameterDeclaration();
  5649. }
  5650. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  5651. }
  5652. parseClassSuper(node) {
  5653. super.parseClassSuper(node);
  5654. if (node.superClass && this.match(43)) {
  5655. node.superTypeParameters = this.flowParseTypeParameterInstantiation();
  5656. }
  5657. if (this.isContextual(104)) {
  5658. this.next();
  5659. const implemented = node.implements = [];
  5660. do {
  5661. const node = this.startNode();
  5662. node.id = this.flowParseRestrictedIdentifier(true);
  5663. if (this.match(43)) {
  5664. node.typeParameters = this.flowParseTypeParameterInstantiation();
  5665. } else {
  5666. node.typeParameters = null;
  5667. }
  5668. implemented.push(this.finishNode(node, "ClassImplements"));
  5669. } while (this.eat(12));
  5670. }
  5671. }
  5672. checkGetterSetterParams(method) {
  5673. super.checkGetterSetterParams(method);
  5674. const params = this.getObjectOrClassMethodParams(method);
  5675. if (params.length > 0) {
  5676. const param = params[0];
  5677. if (this.isThisParam(param) && method.kind === "get") {
  5678. this.raise(param.start, FlowErrors.GetterMayNotHaveThisParam);
  5679. } else if (this.isThisParam(param)) {
  5680. this.raise(param.start, FlowErrors.SetterMayNotHaveThisParam);
  5681. }
  5682. }
  5683. }
  5684. parsePropertyNamePrefixOperator(node) {
  5685. node.variance = this.flowParseVariance();
  5686. }
  5687. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  5688. if (prop.variance) {
  5689. this.unexpected(prop.variance.start);
  5690. }
  5691. delete prop.variance;
  5692. let typeParameters;
  5693. if (this.match(43) && !isAccessor) {
  5694. typeParameters = this.flowParseTypeParameterDeclaration();
  5695. if (!this.match(10)) this.unexpected();
  5696. }
  5697. super.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  5698. if (typeParameters) {
  5699. (prop.value || prop).typeParameters = typeParameters;
  5700. }
  5701. }
  5702. parseAssignableListItemTypes(param) {
  5703. if (this.eat(17)) {
  5704. if (param.type !== "Identifier") {
  5705. this.raise(param.start, FlowErrors.PatternIsOptional);
  5706. }
  5707. if (this.isThisParam(param)) {
  5708. this.raise(param.start, FlowErrors.ThisParamMayNotBeOptional);
  5709. }
  5710. param.optional = true;
  5711. }
  5712. if (this.match(14)) {
  5713. param.typeAnnotation = this.flowParseTypeAnnotation();
  5714. } else if (this.isThisParam(param)) {
  5715. this.raise(param.start, FlowErrors.ThisParamAnnotationRequired);
  5716. }
  5717. if (this.match(27) && this.isThisParam(param)) {
  5718. this.raise(param.start, FlowErrors.ThisParamNoDefault);
  5719. }
  5720. this.resetEndLocation(param);
  5721. return param;
  5722. }
  5723. parseMaybeDefault(startPos, startLoc, left) {
  5724. const node = super.parseMaybeDefault(startPos, startLoc, left);
  5725. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  5726. this.raise(node.typeAnnotation.start, FlowErrors.TypeBeforeInitializer);
  5727. }
  5728. return node;
  5729. }
  5730. shouldParseDefaultImport(node) {
  5731. if (!hasTypeImportKind(node)) {
  5732. return super.shouldParseDefaultImport(node);
  5733. }
  5734. return isMaybeDefaultImport(this.state.type);
  5735. }
  5736. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  5737. specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier();
  5738. this.checkLVal(specifier.local, contextDescription, BIND_LEXICAL);
  5739. node.specifiers.push(this.finishNode(specifier, type));
  5740. }
  5741. maybeParseDefaultImportSpecifier(node) {
  5742. node.importKind = "value";
  5743. let kind = null;
  5744. if (this.match(81)) {
  5745. kind = "typeof";
  5746. } else if (this.isContextual(120)) {
  5747. kind = "type";
  5748. }
  5749. if (kind) {
  5750. const lh = this.lookahead();
  5751. const {
  5752. type
  5753. } = lh;
  5754. if (kind === "type" && type === 49) {
  5755. this.unexpected(lh.start);
  5756. }
  5757. if (isMaybeDefaultImport(type) || type === 5 || type === 49) {
  5758. this.next();
  5759. node.importKind = kind;
  5760. }
  5761. }
  5762. return super.maybeParseDefaultImportSpecifier(node);
  5763. }
  5764. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly) {
  5765. const firstIdent = specifier.imported;
  5766. let specifierTypeKind = null;
  5767. if (firstIdent.type === "Identifier") {
  5768. if (firstIdent.name === "type") {
  5769. specifierTypeKind = "type";
  5770. } else if (firstIdent.name === "typeof") {
  5771. specifierTypeKind = "typeof";
  5772. }
  5773. }
  5774. let isBinding = false;
  5775. if (this.isContextual(87) && !this.isLookaheadContextual("as")) {
  5776. const as_ident = this.parseIdentifier(true);
  5777. if (specifierTypeKind !== null && !tokenIsKeywordOrIdentifier(this.state.type)) {
  5778. specifier.imported = as_ident;
  5779. specifier.importKind = specifierTypeKind;
  5780. specifier.local = cloneIdentifier(as_ident);
  5781. } else {
  5782. specifier.imported = firstIdent;
  5783. specifier.importKind = null;
  5784. specifier.local = this.parseIdentifier();
  5785. }
  5786. } else {
  5787. if (specifierTypeKind !== null && tokenIsKeywordOrIdentifier(this.state.type)) {
  5788. specifier.imported = this.parseIdentifier(true);
  5789. specifier.importKind = specifierTypeKind;
  5790. } else {
  5791. if (importedIsString) {
  5792. throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, firstIdent.value);
  5793. }
  5794. specifier.imported = firstIdent;
  5795. specifier.importKind = null;
  5796. }
  5797. if (this.eatContextual(87)) {
  5798. specifier.local = this.parseIdentifier();
  5799. } else {
  5800. isBinding = true;
  5801. specifier.local = cloneIdentifier(specifier.imported);
  5802. }
  5803. }
  5804. const specifierIsTypeImport = hasTypeImportKind(specifier);
  5805. if (isInTypeOnlyImport && specifierIsTypeImport) {
  5806. this.raise(specifier.start, FlowErrors.ImportTypeShorthandOnlyInPureImport);
  5807. }
  5808. if (isInTypeOnlyImport || specifierIsTypeImport) {
  5809. this.checkReservedType(specifier.local.name, specifier.local.start, true);
  5810. }
  5811. if (isBinding && !isInTypeOnlyImport && !specifierIsTypeImport) {
  5812. this.checkReservedWord(specifier.local.name, specifier.start, true, true);
  5813. }
  5814. this.checkLVal(specifier.local, "import specifier", BIND_LEXICAL);
  5815. return this.finishNode(specifier, "ImportSpecifier");
  5816. }
  5817. parseBindingAtom() {
  5818. switch (this.state.type) {
  5819. case 72:
  5820. return this.parseIdentifier(true);
  5821. default:
  5822. return super.parseBindingAtom();
  5823. }
  5824. }
  5825. parseFunctionParams(node, allowModifiers) {
  5826. const kind = node.kind;
  5827. if (kind !== "get" && kind !== "set" && this.match(43)) {
  5828. node.typeParameters = this.flowParseTypeParameterDeclaration();
  5829. }
  5830. super.parseFunctionParams(node, allowModifiers);
  5831. }
  5832. parseVarId(decl, kind) {
  5833. super.parseVarId(decl, kind);
  5834. if (this.match(14)) {
  5835. decl.id.typeAnnotation = this.flowParseTypeAnnotation();
  5836. this.resetEndLocation(decl.id);
  5837. }
  5838. }
  5839. parseAsyncArrowFromCallExpression(node, call) {
  5840. if (this.match(14)) {
  5841. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  5842. this.state.noAnonFunctionType = true;
  5843. node.returnType = this.flowParseTypeAnnotation();
  5844. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  5845. }
  5846. return super.parseAsyncArrowFromCallExpression(node, call);
  5847. }
  5848. shouldParseAsyncArrow() {
  5849. return this.match(14) || super.shouldParseAsyncArrow();
  5850. }
  5851. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  5852. var _jsx;
  5853. let state = null;
  5854. let jsx;
  5855. if (this.hasPlugin("jsx") && (this.match(132) || this.match(43))) {
  5856. state = this.state.clone();
  5857. jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
  5858. if (!jsx.error) return jsx.node;
  5859. const {
  5860. context
  5861. } = this.state;
  5862. const curContext = context[context.length - 1];
  5863. if (curContext === types$1.j_oTag) {
  5864. context.length -= 2;
  5865. } else if (curContext === types$1.j_expr) {
  5866. context.length -= 1;
  5867. }
  5868. }
  5869. if ((_jsx = jsx) != null && _jsx.error || this.match(43)) {
  5870. var _jsx2, _jsx3;
  5871. state = state || this.state.clone();
  5872. let typeParameters;
  5873. const arrow = this.tryParse(abort => {
  5874. var _arrowExpression$extr;
  5875. typeParameters = this.flowParseTypeParameterDeclaration();
  5876. const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => {
  5877. const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  5878. this.resetStartLocationFromNode(result, typeParameters);
  5879. return result;
  5880. });
  5881. if ((_arrowExpression$extr = arrowExpression.extra) != null && _arrowExpression$extr.parenthesized) abort();
  5882. const expr = this.maybeUnwrapTypeCastExpression(arrowExpression);
  5883. if (expr.type !== "ArrowFunctionExpression") abort();
  5884. expr.typeParameters = typeParameters;
  5885. this.resetStartLocationFromNode(expr, typeParameters);
  5886. return arrowExpression;
  5887. }, state);
  5888. let arrowExpression = null;
  5889. if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") {
  5890. if (!arrow.error && !arrow.aborted) {
  5891. if (arrow.node.async) {
  5892. this.raise(typeParameters.start, FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction);
  5893. }
  5894. return arrow.node;
  5895. }
  5896. arrowExpression = arrow.node;
  5897. }
  5898. if ((_jsx2 = jsx) != null && _jsx2.node) {
  5899. this.state = jsx.failState;
  5900. return jsx.node;
  5901. }
  5902. if (arrowExpression) {
  5903. this.state = arrow.failState;
  5904. return arrowExpression;
  5905. }
  5906. if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error;
  5907. if (arrow.thrown) throw arrow.error;
  5908. throw this.raise(typeParameters.start, FlowErrors.UnexpectedTokenAfterTypeParameter);
  5909. }
  5910. return super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  5911. }
  5912. parseArrow(node) {
  5913. if (this.match(14)) {
  5914. const result = this.tryParse(() => {
  5915. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  5916. this.state.noAnonFunctionType = true;
  5917. const typeNode = this.startNode();
  5918. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  5919. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  5920. if (this.canInsertSemicolon()) this.unexpected();
  5921. if (!this.match(19)) this.unexpected();
  5922. return typeNode;
  5923. });
  5924. if (result.thrown) return null;
  5925. if (result.error) this.state = result.failState;
  5926. node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null;
  5927. }
  5928. return super.parseArrow(node);
  5929. }
  5930. shouldParseArrow(params) {
  5931. return this.match(14) || super.shouldParseArrow(params);
  5932. }
  5933. setArrowFunctionParameters(node, params) {
  5934. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  5935. node.params = params;
  5936. } else {
  5937. super.setArrowFunctionParameters(node, params);
  5938. }
  5939. }
  5940. checkParams(node, allowDuplicates, isArrowFunction) {
  5941. if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  5942. return;
  5943. }
  5944. for (let i = 0; i < node.params.length; i++) {
  5945. if (this.isThisParam(node.params[i]) && i > 0) {
  5946. this.raise(node.params[i].start, FlowErrors.ThisParamMustBeFirst);
  5947. }
  5948. }
  5949. return super.checkParams(...arguments);
  5950. }
  5951. parseParenAndDistinguishExpression(canBeArrow) {
  5952. return super.parseParenAndDistinguishExpression(canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1);
  5953. }
  5954. parseSubscripts(base, startPos, startLoc, noCalls) {
  5955. if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.indexOf(startPos) !== -1) {
  5956. this.next();
  5957. const node = this.startNodeAt(startPos, startLoc);
  5958. node.callee = base;
  5959. node.arguments = this.parseCallExpressionArguments(11, false);
  5960. base = this.finishNode(node, "CallExpression");
  5961. } else if (base.type === "Identifier" && base.name === "async" && this.match(43)) {
  5962. const state = this.state.clone();
  5963. const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startPos, startLoc) || abort(), state);
  5964. if (!arrow.error && !arrow.aborted) return arrow.node;
  5965. const result = this.tryParse(() => super.parseSubscripts(base, startPos, startLoc, noCalls), state);
  5966. if (result.node && !result.error) return result.node;
  5967. if (arrow.node) {
  5968. this.state = arrow.failState;
  5969. return arrow.node;
  5970. }
  5971. if (result.node) {
  5972. this.state = result.failState;
  5973. return result.node;
  5974. }
  5975. throw arrow.error || result.error;
  5976. }
  5977. return super.parseSubscripts(base, startPos, startLoc, noCalls);
  5978. }
  5979. parseSubscript(base, startPos, startLoc, noCalls, subscriptState) {
  5980. if (this.match(18) && this.isLookaheadToken_lt()) {
  5981. subscriptState.optionalChainMember = true;
  5982. if (noCalls) {
  5983. subscriptState.stop = true;
  5984. return base;
  5985. }
  5986. this.next();
  5987. const node = this.startNodeAt(startPos, startLoc);
  5988. node.callee = base;
  5989. node.typeArguments = this.flowParseTypeParameterInstantiation();
  5990. this.expect(10);
  5991. node.arguments = this.parseCallExpressionArguments(11, false);
  5992. node.optional = true;
  5993. return this.finishCallExpression(node, true);
  5994. } else if (!noCalls && this.shouldParseTypes() && this.match(43)) {
  5995. const node = this.startNodeAt(startPos, startLoc);
  5996. node.callee = base;
  5997. const result = this.tryParse(() => {
  5998. node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew();
  5999. this.expect(10);
  6000. node.arguments = this.parseCallExpressionArguments(11, false);
  6001. if (subscriptState.optionalChainMember) node.optional = false;
  6002. return this.finishCallExpression(node, subscriptState.optionalChainMember);
  6003. });
  6004. if (result.node) {
  6005. if (result.error) this.state = result.failState;
  6006. return result.node;
  6007. }
  6008. }
  6009. return super.parseSubscript(base, startPos, startLoc, noCalls, subscriptState);
  6010. }
  6011. parseNewArguments(node) {
  6012. let targs = null;
  6013. if (this.shouldParseTypes() && this.match(43)) {
  6014. targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node;
  6015. }
  6016. node.typeArguments = targs;
  6017. super.parseNewArguments(node);
  6018. }
  6019. parseAsyncArrowWithTypeParameters(startPos, startLoc) {
  6020. const node = this.startNodeAt(startPos, startLoc);
  6021. this.parseFunctionParams(node);
  6022. if (!this.parseArrow(node)) return;
  6023. return this.parseArrowExpression(node, undefined, true);
  6024. }
  6025. readToken_mult_modulo(code) {
  6026. const next = this.input.charCodeAt(this.state.pos + 1);
  6027. if (code === 42 && next === 47 && this.state.hasFlowComment) {
  6028. this.state.hasFlowComment = false;
  6029. this.state.pos += 2;
  6030. this.nextToken();
  6031. return;
  6032. }
  6033. super.readToken_mult_modulo(code);
  6034. }
  6035. readToken_pipe_amp(code) {
  6036. const next = this.input.charCodeAt(this.state.pos + 1);
  6037. if (code === 124 && next === 125) {
  6038. this.finishOp(9, 2);
  6039. return;
  6040. }
  6041. super.readToken_pipe_amp(code);
  6042. }
  6043. parseTopLevel(file, program) {
  6044. const fileNode = super.parseTopLevel(file, program);
  6045. if (this.state.hasFlowComment) {
  6046. this.raise(this.state.pos, FlowErrors.UnterminatedFlowComment);
  6047. }
  6048. return fileNode;
  6049. }
  6050. skipBlockComment() {
  6051. if (this.hasPlugin("flowComments") && this.skipFlowComment()) {
  6052. if (this.state.hasFlowComment) {
  6053. this.unexpected(null, FlowErrors.NestedFlowComment);
  6054. }
  6055. this.hasFlowCommentCompletion();
  6056. this.state.pos += this.skipFlowComment();
  6057. this.state.hasFlowComment = true;
  6058. return;
  6059. }
  6060. if (this.state.hasFlowComment) {
  6061. const end = this.input.indexOf("*-/", this.state.pos += 2);
  6062. if (end === -1) {
  6063. throw this.raise(this.state.pos - 2, ErrorMessages.UnterminatedComment);
  6064. }
  6065. this.state.pos = end + 3;
  6066. return;
  6067. }
  6068. return super.skipBlockComment();
  6069. }
  6070. skipFlowComment() {
  6071. const {
  6072. pos
  6073. } = this.state;
  6074. let shiftToFirstNonWhiteSpace = 2;
  6075. while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) {
  6076. shiftToFirstNonWhiteSpace++;
  6077. }
  6078. const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);
  6079. const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);
  6080. if (ch2 === 58 && ch3 === 58) {
  6081. return shiftToFirstNonWhiteSpace + 2;
  6082. }
  6083. if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") {
  6084. return shiftToFirstNonWhiteSpace + 12;
  6085. }
  6086. if (ch2 === 58 && ch3 !== 58) {
  6087. return shiftToFirstNonWhiteSpace;
  6088. }
  6089. return false;
  6090. }
  6091. hasFlowCommentCompletion() {
  6092. const end = this.input.indexOf("*/", this.state.pos);
  6093. if (end === -1) {
  6094. throw this.raise(this.state.pos, ErrorMessages.UnterminatedComment);
  6095. }
  6096. }
  6097. flowEnumErrorBooleanMemberNotInitialized(pos, {
  6098. enumName,
  6099. memberName
  6100. }) {
  6101. this.raise(pos, FlowErrors.EnumBooleanMemberNotInitialized, memberName, enumName);
  6102. }
  6103. flowEnumErrorInvalidMemberName(pos, {
  6104. enumName,
  6105. memberName
  6106. }) {
  6107. const suggestion = memberName[0].toUpperCase() + memberName.slice(1);
  6108. this.raise(pos, FlowErrors.EnumInvalidMemberName, memberName, suggestion, enumName);
  6109. }
  6110. flowEnumErrorDuplicateMemberName(pos, {
  6111. enumName,
  6112. memberName
  6113. }) {
  6114. this.raise(pos, FlowErrors.EnumDuplicateMemberName, memberName, enumName);
  6115. }
  6116. flowEnumErrorInconsistentMemberValues(pos, {
  6117. enumName
  6118. }) {
  6119. this.raise(pos, FlowErrors.EnumInconsistentMemberValues, enumName);
  6120. }
  6121. flowEnumErrorInvalidExplicitType(pos, {
  6122. enumName,
  6123. suppliedType
  6124. }) {
  6125. return this.raise(pos, suppliedType === null ? FlowErrors.EnumInvalidExplicitTypeUnknownSupplied : FlowErrors.EnumInvalidExplicitType, enumName, suppliedType);
  6126. }
  6127. flowEnumErrorInvalidMemberInitializer(pos, {
  6128. enumName,
  6129. explicitType,
  6130. memberName
  6131. }) {
  6132. let message = null;
  6133. switch (explicitType) {
  6134. case "boolean":
  6135. case "number":
  6136. case "string":
  6137. message = FlowErrors.EnumInvalidMemberInitializerPrimaryType;
  6138. break;
  6139. case "symbol":
  6140. message = FlowErrors.EnumInvalidMemberInitializerSymbolType;
  6141. break;
  6142. default:
  6143. message = FlowErrors.EnumInvalidMemberInitializerUnknownType;
  6144. }
  6145. return this.raise(pos, message, enumName, memberName, explicitType);
  6146. }
  6147. flowEnumErrorNumberMemberNotInitialized(pos, {
  6148. enumName,
  6149. memberName
  6150. }) {
  6151. this.raise(pos, FlowErrors.EnumNumberMemberNotInitialized, enumName, memberName);
  6152. }
  6153. flowEnumErrorStringMemberInconsistentlyInitailized(pos, {
  6154. enumName
  6155. }) {
  6156. this.raise(pos, FlowErrors.EnumStringMemberInconsistentlyInitailized, enumName);
  6157. }
  6158. flowEnumMemberInit() {
  6159. const startPos = this.state.start;
  6160. const endOfInit = () => this.match(12) || this.match(8);
  6161. switch (this.state.type) {
  6162. case 124:
  6163. {
  6164. const literal = this.parseNumericLiteral(this.state.value);
  6165. if (endOfInit()) {
  6166. return {
  6167. type: "number",
  6168. pos: literal.start,
  6169. value: literal
  6170. };
  6171. }
  6172. return {
  6173. type: "invalid",
  6174. pos: startPos
  6175. };
  6176. }
  6177. case 123:
  6178. {
  6179. const literal = this.parseStringLiteral(this.state.value);
  6180. if (endOfInit()) {
  6181. return {
  6182. type: "string",
  6183. pos: literal.start,
  6184. value: literal
  6185. };
  6186. }
  6187. return {
  6188. type: "invalid",
  6189. pos: startPos
  6190. };
  6191. }
  6192. case 79:
  6193. case 80:
  6194. {
  6195. const literal = this.parseBooleanLiteral(this.match(79));
  6196. if (endOfInit()) {
  6197. return {
  6198. type: "boolean",
  6199. pos: literal.start,
  6200. value: literal
  6201. };
  6202. }
  6203. return {
  6204. type: "invalid",
  6205. pos: startPos
  6206. };
  6207. }
  6208. default:
  6209. return {
  6210. type: "invalid",
  6211. pos: startPos
  6212. };
  6213. }
  6214. }
  6215. flowEnumMemberRaw() {
  6216. const pos = this.state.start;
  6217. const id = this.parseIdentifier(true);
  6218. const init = this.eat(27) ? this.flowEnumMemberInit() : {
  6219. type: "none",
  6220. pos
  6221. };
  6222. return {
  6223. id,
  6224. init
  6225. };
  6226. }
  6227. flowEnumCheckExplicitTypeMismatch(pos, context, expectedType) {
  6228. const {
  6229. explicitType
  6230. } = context;
  6231. if (explicitType === null) {
  6232. return;
  6233. }
  6234. if (explicitType !== expectedType) {
  6235. this.flowEnumErrorInvalidMemberInitializer(pos, context);
  6236. }
  6237. }
  6238. flowEnumMembers({
  6239. enumName,
  6240. explicitType
  6241. }) {
  6242. const seenNames = new Set();
  6243. const members = {
  6244. booleanMembers: [],
  6245. numberMembers: [],
  6246. stringMembers: [],
  6247. defaultedMembers: []
  6248. };
  6249. let hasUnknownMembers = false;
  6250. while (!this.match(8)) {
  6251. if (this.eat(21)) {
  6252. hasUnknownMembers = true;
  6253. break;
  6254. }
  6255. const memberNode = this.startNode();
  6256. const {
  6257. id,
  6258. init
  6259. } = this.flowEnumMemberRaw();
  6260. const memberName = id.name;
  6261. if (memberName === "") {
  6262. continue;
  6263. }
  6264. if (/^[a-z]/.test(memberName)) {
  6265. this.flowEnumErrorInvalidMemberName(id.start, {
  6266. enumName,
  6267. memberName
  6268. });
  6269. }
  6270. if (seenNames.has(memberName)) {
  6271. this.flowEnumErrorDuplicateMemberName(id.start, {
  6272. enumName,
  6273. memberName
  6274. });
  6275. }
  6276. seenNames.add(memberName);
  6277. const context = {
  6278. enumName,
  6279. explicitType,
  6280. memberName
  6281. };
  6282. memberNode.id = id;
  6283. switch (init.type) {
  6284. case "boolean":
  6285. {
  6286. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "boolean");
  6287. memberNode.init = init.value;
  6288. members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember"));
  6289. break;
  6290. }
  6291. case "number":
  6292. {
  6293. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "number");
  6294. memberNode.init = init.value;
  6295. members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember"));
  6296. break;
  6297. }
  6298. case "string":
  6299. {
  6300. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "string");
  6301. memberNode.init = init.value;
  6302. members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember"));
  6303. break;
  6304. }
  6305. case "invalid":
  6306. {
  6307. throw this.flowEnumErrorInvalidMemberInitializer(init.pos, context);
  6308. }
  6309. case "none":
  6310. {
  6311. switch (explicitType) {
  6312. case "boolean":
  6313. this.flowEnumErrorBooleanMemberNotInitialized(init.pos, context);
  6314. break;
  6315. case "number":
  6316. this.flowEnumErrorNumberMemberNotInitialized(init.pos, context);
  6317. break;
  6318. default:
  6319. members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember"));
  6320. }
  6321. }
  6322. }
  6323. if (!this.match(8)) {
  6324. this.expect(12);
  6325. }
  6326. }
  6327. return {
  6328. members,
  6329. hasUnknownMembers
  6330. };
  6331. }
  6332. flowEnumStringMembers(initializedMembers, defaultedMembers, {
  6333. enumName
  6334. }) {
  6335. if (initializedMembers.length === 0) {
  6336. return defaultedMembers;
  6337. } else if (defaultedMembers.length === 0) {
  6338. return initializedMembers;
  6339. } else if (defaultedMembers.length > initializedMembers.length) {
  6340. for (const member of initializedMembers) {
  6341. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  6342. enumName
  6343. });
  6344. }
  6345. return defaultedMembers;
  6346. } else {
  6347. for (const member of defaultedMembers) {
  6348. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  6349. enumName
  6350. });
  6351. }
  6352. return initializedMembers;
  6353. }
  6354. }
  6355. flowEnumParseExplicitType({
  6356. enumName
  6357. }) {
  6358. if (this.eatContextual(95)) {
  6359. if (!tokenIsIdentifier(this.state.type)) {
  6360. throw this.flowEnumErrorInvalidExplicitType(this.state.start, {
  6361. enumName,
  6362. suppliedType: null
  6363. });
  6364. }
  6365. const {
  6366. value
  6367. } = this.state;
  6368. this.next();
  6369. if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") {
  6370. this.flowEnumErrorInvalidExplicitType(this.state.start, {
  6371. enumName,
  6372. suppliedType: value
  6373. });
  6374. }
  6375. return value;
  6376. }
  6377. return null;
  6378. }
  6379. flowEnumBody(node, {
  6380. enumName,
  6381. nameLoc
  6382. }) {
  6383. const explicitType = this.flowEnumParseExplicitType({
  6384. enumName
  6385. });
  6386. this.expect(5);
  6387. const {
  6388. members,
  6389. hasUnknownMembers
  6390. } = this.flowEnumMembers({
  6391. enumName,
  6392. explicitType
  6393. });
  6394. node.hasUnknownMembers = hasUnknownMembers;
  6395. switch (explicitType) {
  6396. case "boolean":
  6397. node.explicitType = true;
  6398. node.members = members.booleanMembers;
  6399. this.expect(8);
  6400. return this.finishNode(node, "EnumBooleanBody");
  6401. case "number":
  6402. node.explicitType = true;
  6403. node.members = members.numberMembers;
  6404. this.expect(8);
  6405. return this.finishNode(node, "EnumNumberBody");
  6406. case "string":
  6407. node.explicitType = true;
  6408. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  6409. enumName
  6410. });
  6411. this.expect(8);
  6412. return this.finishNode(node, "EnumStringBody");
  6413. case "symbol":
  6414. node.members = members.defaultedMembers;
  6415. this.expect(8);
  6416. return this.finishNode(node, "EnumSymbolBody");
  6417. default:
  6418. {
  6419. const empty = () => {
  6420. node.members = [];
  6421. this.expect(8);
  6422. return this.finishNode(node, "EnumStringBody");
  6423. };
  6424. node.explicitType = false;
  6425. const boolsLen = members.booleanMembers.length;
  6426. const numsLen = members.numberMembers.length;
  6427. const strsLen = members.stringMembers.length;
  6428. const defaultedLen = members.defaultedMembers.length;
  6429. if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {
  6430. return empty();
  6431. } else if (!boolsLen && !numsLen) {
  6432. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  6433. enumName
  6434. });
  6435. this.expect(8);
  6436. return this.finishNode(node, "EnumStringBody");
  6437. } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {
  6438. for (const member of members.defaultedMembers) {
  6439. this.flowEnumErrorBooleanMemberNotInitialized(member.start, {
  6440. enumName,
  6441. memberName: member.id.name
  6442. });
  6443. }
  6444. node.members = members.booleanMembers;
  6445. this.expect(8);
  6446. return this.finishNode(node, "EnumBooleanBody");
  6447. } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {
  6448. for (const member of members.defaultedMembers) {
  6449. this.flowEnumErrorNumberMemberNotInitialized(member.start, {
  6450. enumName,
  6451. memberName: member.id.name
  6452. });
  6453. }
  6454. node.members = members.numberMembers;
  6455. this.expect(8);
  6456. return this.finishNode(node, "EnumNumberBody");
  6457. } else {
  6458. this.flowEnumErrorInconsistentMemberValues(nameLoc, {
  6459. enumName
  6460. });
  6461. return empty();
  6462. }
  6463. }
  6464. }
  6465. }
  6466. flowParseEnumDeclaration(node) {
  6467. const id = this.parseIdentifier();
  6468. node.id = id;
  6469. node.body = this.flowEnumBody(this.startNode(), {
  6470. enumName: id.name,
  6471. nameLoc: id.start
  6472. });
  6473. return this.finishNode(node, "EnumDeclaration");
  6474. }
  6475. isLookaheadToken_lt() {
  6476. const next = this.nextTokenStart();
  6477. if (this.input.charCodeAt(next) === 60) {
  6478. const afterNext = this.input.charCodeAt(next + 1);
  6479. return afterNext !== 60 && afterNext !== 61;
  6480. }
  6481. return false;
  6482. }
  6483. maybeUnwrapTypeCastExpression(node) {
  6484. return node.type === "TypeCastExpression" ? node.expression : node;
  6485. }
  6486. });
  6487. const entities = {
  6488. quot: "\u0022",
  6489. amp: "&",
  6490. apos: "\u0027",
  6491. lt: "<",
  6492. gt: ">",
  6493. nbsp: "\u00A0",
  6494. iexcl: "\u00A1",
  6495. cent: "\u00A2",
  6496. pound: "\u00A3",
  6497. curren: "\u00A4",
  6498. yen: "\u00A5",
  6499. brvbar: "\u00A6",
  6500. sect: "\u00A7",
  6501. uml: "\u00A8",
  6502. copy: "\u00A9",
  6503. ordf: "\u00AA",
  6504. laquo: "\u00AB",
  6505. not: "\u00AC",
  6506. shy: "\u00AD",
  6507. reg: "\u00AE",
  6508. macr: "\u00AF",
  6509. deg: "\u00B0",
  6510. plusmn: "\u00B1",
  6511. sup2: "\u00B2",
  6512. sup3: "\u00B3",
  6513. acute: "\u00B4",
  6514. micro: "\u00B5",
  6515. para: "\u00B6",
  6516. middot: "\u00B7",
  6517. cedil: "\u00B8",
  6518. sup1: "\u00B9",
  6519. ordm: "\u00BA",
  6520. raquo: "\u00BB",
  6521. frac14: "\u00BC",
  6522. frac12: "\u00BD",
  6523. frac34: "\u00BE",
  6524. iquest: "\u00BF",
  6525. Agrave: "\u00C0",
  6526. Aacute: "\u00C1",
  6527. Acirc: "\u00C2",
  6528. Atilde: "\u00C3",
  6529. Auml: "\u00C4",
  6530. Aring: "\u00C5",
  6531. AElig: "\u00C6",
  6532. Ccedil: "\u00C7",
  6533. Egrave: "\u00C8",
  6534. Eacute: "\u00C9",
  6535. Ecirc: "\u00CA",
  6536. Euml: "\u00CB",
  6537. Igrave: "\u00CC",
  6538. Iacute: "\u00CD",
  6539. Icirc: "\u00CE",
  6540. Iuml: "\u00CF",
  6541. ETH: "\u00D0",
  6542. Ntilde: "\u00D1",
  6543. Ograve: "\u00D2",
  6544. Oacute: "\u00D3",
  6545. Ocirc: "\u00D4",
  6546. Otilde: "\u00D5",
  6547. Ouml: "\u00D6",
  6548. times: "\u00D7",
  6549. Oslash: "\u00D8",
  6550. Ugrave: "\u00D9",
  6551. Uacute: "\u00DA",
  6552. Ucirc: "\u00DB",
  6553. Uuml: "\u00DC",
  6554. Yacute: "\u00DD",
  6555. THORN: "\u00DE",
  6556. szlig: "\u00DF",
  6557. agrave: "\u00E0",
  6558. aacute: "\u00E1",
  6559. acirc: "\u00E2",
  6560. atilde: "\u00E3",
  6561. auml: "\u00E4",
  6562. aring: "\u00E5",
  6563. aelig: "\u00E6",
  6564. ccedil: "\u00E7",
  6565. egrave: "\u00E8",
  6566. eacute: "\u00E9",
  6567. ecirc: "\u00EA",
  6568. euml: "\u00EB",
  6569. igrave: "\u00EC",
  6570. iacute: "\u00ED",
  6571. icirc: "\u00EE",
  6572. iuml: "\u00EF",
  6573. eth: "\u00F0",
  6574. ntilde: "\u00F1",
  6575. ograve: "\u00F2",
  6576. oacute: "\u00F3",
  6577. ocirc: "\u00F4",
  6578. otilde: "\u00F5",
  6579. ouml: "\u00F6",
  6580. divide: "\u00F7",
  6581. oslash: "\u00F8",
  6582. ugrave: "\u00F9",
  6583. uacute: "\u00FA",
  6584. ucirc: "\u00FB",
  6585. uuml: "\u00FC",
  6586. yacute: "\u00FD",
  6587. thorn: "\u00FE",
  6588. yuml: "\u00FF",
  6589. OElig: "\u0152",
  6590. oelig: "\u0153",
  6591. Scaron: "\u0160",
  6592. scaron: "\u0161",
  6593. Yuml: "\u0178",
  6594. fnof: "\u0192",
  6595. circ: "\u02C6",
  6596. tilde: "\u02DC",
  6597. Alpha: "\u0391",
  6598. Beta: "\u0392",
  6599. Gamma: "\u0393",
  6600. Delta: "\u0394",
  6601. Epsilon: "\u0395",
  6602. Zeta: "\u0396",
  6603. Eta: "\u0397",
  6604. Theta: "\u0398",
  6605. Iota: "\u0399",
  6606. Kappa: "\u039A",
  6607. Lambda: "\u039B",
  6608. Mu: "\u039C",
  6609. Nu: "\u039D",
  6610. Xi: "\u039E",
  6611. Omicron: "\u039F",
  6612. Pi: "\u03A0",
  6613. Rho: "\u03A1",
  6614. Sigma: "\u03A3",
  6615. Tau: "\u03A4",
  6616. Upsilon: "\u03A5",
  6617. Phi: "\u03A6",
  6618. Chi: "\u03A7",
  6619. Psi: "\u03A8",
  6620. Omega: "\u03A9",
  6621. alpha: "\u03B1",
  6622. beta: "\u03B2",
  6623. gamma: "\u03B3",
  6624. delta: "\u03B4",
  6625. epsilon: "\u03B5",
  6626. zeta: "\u03B6",
  6627. eta: "\u03B7",
  6628. theta: "\u03B8",
  6629. iota: "\u03B9",
  6630. kappa: "\u03BA",
  6631. lambda: "\u03BB",
  6632. mu: "\u03BC",
  6633. nu: "\u03BD",
  6634. xi: "\u03BE",
  6635. omicron: "\u03BF",
  6636. pi: "\u03C0",
  6637. rho: "\u03C1",
  6638. sigmaf: "\u03C2",
  6639. sigma: "\u03C3",
  6640. tau: "\u03C4",
  6641. upsilon: "\u03C5",
  6642. phi: "\u03C6",
  6643. chi: "\u03C7",
  6644. psi: "\u03C8",
  6645. omega: "\u03C9",
  6646. thetasym: "\u03D1",
  6647. upsih: "\u03D2",
  6648. piv: "\u03D6",
  6649. ensp: "\u2002",
  6650. emsp: "\u2003",
  6651. thinsp: "\u2009",
  6652. zwnj: "\u200C",
  6653. zwj: "\u200D",
  6654. lrm: "\u200E",
  6655. rlm: "\u200F",
  6656. ndash: "\u2013",
  6657. mdash: "\u2014",
  6658. lsquo: "\u2018",
  6659. rsquo: "\u2019",
  6660. sbquo: "\u201A",
  6661. ldquo: "\u201C",
  6662. rdquo: "\u201D",
  6663. bdquo: "\u201E",
  6664. dagger: "\u2020",
  6665. Dagger: "\u2021",
  6666. bull: "\u2022",
  6667. hellip: "\u2026",
  6668. permil: "\u2030",
  6669. prime: "\u2032",
  6670. Prime: "\u2033",
  6671. lsaquo: "\u2039",
  6672. rsaquo: "\u203A",
  6673. oline: "\u203E",
  6674. frasl: "\u2044",
  6675. euro: "\u20AC",
  6676. image: "\u2111",
  6677. weierp: "\u2118",
  6678. real: "\u211C",
  6679. trade: "\u2122",
  6680. alefsym: "\u2135",
  6681. larr: "\u2190",
  6682. uarr: "\u2191",
  6683. rarr: "\u2192",
  6684. darr: "\u2193",
  6685. harr: "\u2194",
  6686. crarr: "\u21B5",
  6687. lArr: "\u21D0",
  6688. uArr: "\u21D1",
  6689. rArr: "\u21D2",
  6690. dArr: "\u21D3",
  6691. hArr: "\u21D4",
  6692. forall: "\u2200",
  6693. part: "\u2202",
  6694. exist: "\u2203",
  6695. empty: "\u2205",
  6696. nabla: "\u2207",
  6697. isin: "\u2208",
  6698. notin: "\u2209",
  6699. ni: "\u220B",
  6700. prod: "\u220F",
  6701. sum: "\u2211",
  6702. minus: "\u2212",
  6703. lowast: "\u2217",
  6704. radic: "\u221A",
  6705. prop: "\u221D",
  6706. infin: "\u221E",
  6707. ang: "\u2220",
  6708. and: "\u2227",
  6709. or: "\u2228",
  6710. cap: "\u2229",
  6711. cup: "\u222A",
  6712. int: "\u222B",
  6713. there4: "\u2234",
  6714. sim: "\u223C",
  6715. cong: "\u2245",
  6716. asymp: "\u2248",
  6717. ne: "\u2260",
  6718. equiv: "\u2261",
  6719. le: "\u2264",
  6720. ge: "\u2265",
  6721. sub: "\u2282",
  6722. sup: "\u2283",
  6723. nsub: "\u2284",
  6724. sube: "\u2286",
  6725. supe: "\u2287",
  6726. oplus: "\u2295",
  6727. otimes: "\u2297",
  6728. perp: "\u22A5",
  6729. sdot: "\u22C5",
  6730. lceil: "\u2308",
  6731. rceil: "\u2309",
  6732. lfloor: "\u230A",
  6733. rfloor: "\u230B",
  6734. lang: "\u2329",
  6735. rang: "\u232A",
  6736. loz: "\u25CA",
  6737. spades: "\u2660",
  6738. clubs: "\u2663",
  6739. hearts: "\u2665",
  6740. diams: "\u2666"
  6741. };
  6742. const HEX_NUMBER = /^[\da-fA-F]+$/;
  6743. const DECIMAL_NUMBER = /^\d+$/;
  6744. const JsxErrors = makeErrorTemplates({
  6745. AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression.",
  6746. MissingClosingTagElement: "Expected corresponding JSX closing tag for <%0>.",
  6747. MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>.",
  6748. UnexpectedSequenceExpression: "Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?",
  6749. UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text.",
  6750. UnterminatedJsxContent: "Unterminated JSX contents.",
  6751. UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"
  6752. }, ErrorCodes.SyntaxError, "jsx");
  6753. types$1.j_oTag = new TokContext("<tag");
  6754. types$1.j_cTag = new TokContext("</tag");
  6755. types$1.j_expr = new TokContext("<tag>...</tag>", true);
  6756. function isFragment(object) {
  6757. return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false;
  6758. }
  6759. function getQualifiedJSXName(object) {
  6760. if (object.type === "JSXIdentifier") {
  6761. return object.name;
  6762. }
  6763. if (object.type === "JSXNamespacedName") {
  6764. return object.namespace.name + ":" + object.name.name;
  6765. }
  6766. if (object.type === "JSXMemberExpression") {
  6767. return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property);
  6768. }
  6769. throw new Error("Node had unexpected type: " + object.type);
  6770. }
  6771. var jsx = (superClass => class extends superClass {
  6772. jsxReadToken() {
  6773. let out = "";
  6774. let chunkStart = this.state.pos;
  6775. for (;;) {
  6776. if (this.state.pos >= this.length) {
  6777. throw this.raise(this.state.start, JsxErrors.UnterminatedJsxContent);
  6778. }
  6779. const ch = this.input.charCodeAt(this.state.pos);
  6780. switch (ch) {
  6781. case 60:
  6782. case 123:
  6783. if (this.state.pos === this.state.start) {
  6784. if (ch === 60 && this.state.canStartJSXElement) {
  6785. ++this.state.pos;
  6786. return this.finishToken(132);
  6787. }
  6788. return super.getTokenFromCode(ch);
  6789. }
  6790. out += this.input.slice(chunkStart, this.state.pos);
  6791. return this.finishToken(131, out);
  6792. case 38:
  6793. out += this.input.slice(chunkStart, this.state.pos);
  6794. out += this.jsxReadEntity();
  6795. chunkStart = this.state.pos;
  6796. break;
  6797. case 62:
  6798. case 125:
  6799. default:
  6800. if (isNewLine(ch)) {
  6801. out += this.input.slice(chunkStart, this.state.pos);
  6802. out += this.jsxReadNewLine(true);
  6803. chunkStart = this.state.pos;
  6804. } else {
  6805. ++this.state.pos;
  6806. }
  6807. }
  6808. }
  6809. }
  6810. jsxReadNewLine(normalizeCRLF) {
  6811. const ch = this.input.charCodeAt(this.state.pos);
  6812. let out;
  6813. ++this.state.pos;
  6814. if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) {
  6815. ++this.state.pos;
  6816. out = normalizeCRLF ? "\n" : "\r\n";
  6817. } else {
  6818. out = String.fromCharCode(ch);
  6819. }
  6820. ++this.state.curLine;
  6821. this.state.lineStart = this.state.pos;
  6822. return out;
  6823. }
  6824. jsxReadString(quote) {
  6825. let out = "";
  6826. let chunkStart = ++this.state.pos;
  6827. for (;;) {
  6828. if (this.state.pos >= this.length) {
  6829. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  6830. }
  6831. const ch = this.input.charCodeAt(this.state.pos);
  6832. if (ch === quote) break;
  6833. if (ch === 38) {
  6834. out += this.input.slice(chunkStart, this.state.pos);
  6835. out += this.jsxReadEntity();
  6836. chunkStart = this.state.pos;
  6837. } else if (isNewLine(ch)) {
  6838. out += this.input.slice(chunkStart, this.state.pos);
  6839. out += this.jsxReadNewLine(false);
  6840. chunkStart = this.state.pos;
  6841. } else {
  6842. ++this.state.pos;
  6843. }
  6844. }
  6845. out += this.input.slice(chunkStart, this.state.pos++);
  6846. return this.finishToken(123, out);
  6847. }
  6848. jsxReadEntity() {
  6849. let str = "";
  6850. let count = 0;
  6851. let entity;
  6852. let ch = this.input[this.state.pos];
  6853. const startPos = ++this.state.pos;
  6854. while (this.state.pos < this.length && count++ < 10) {
  6855. ch = this.input[this.state.pos++];
  6856. if (ch === ";") {
  6857. if (str[0] === "#") {
  6858. if (str[1] === "x") {
  6859. str = str.substr(2);
  6860. if (HEX_NUMBER.test(str)) {
  6861. entity = String.fromCodePoint(parseInt(str, 16));
  6862. }
  6863. } else {
  6864. str = str.substr(1);
  6865. if (DECIMAL_NUMBER.test(str)) {
  6866. entity = String.fromCodePoint(parseInt(str, 10));
  6867. }
  6868. }
  6869. } else {
  6870. entity = entities[str];
  6871. }
  6872. break;
  6873. }
  6874. str += ch;
  6875. }
  6876. if (!entity) {
  6877. this.state.pos = startPos;
  6878. return "&";
  6879. }
  6880. return entity;
  6881. }
  6882. jsxReadWord() {
  6883. let ch;
  6884. const start = this.state.pos;
  6885. do {
  6886. ch = this.input.charCodeAt(++this.state.pos);
  6887. } while (isIdentifierChar(ch) || ch === 45);
  6888. return this.finishToken(130, this.input.slice(start, this.state.pos));
  6889. }
  6890. jsxParseIdentifier() {
  6891. const node = this.startNode();
  6892. if (this.match(130)) {
  6893. node.name = this.state.value;
  6894. } else if (tokenIsKeyword(this.state.type)) {
  6895. node.name = tokenLabelName(this.state.type);
  6896. } else {
  6897. this.unexpected();
  6898. }
  6899. this.next();
  6900. return this.finishNode(node, "JSXIdentifier");
  6901. }
  6902. jsxParseNamespacedName() {
  6903. const startPos = this.state.start;
  6904. const startLoc = this.state.startLoc;
  6905. const name = this.jsxParseIdentifier();
  6906. if (!this.eat(14)) return name;
  6907. const node = this.startNodeAt(startPos, startLoc);
  6908. node.namespace = name;
  6909. node.name = this.jsxParseIdentifier();
  6910. return this.finishNode(node, "JSXNamespacedName");
  6911. }
  6912. jsxParseElementName() {
  6913. const startPos = this.state.start;
  6914. const startLoc = this.state.startLoc;
  6915. let node = this.jsxParseNamespacedName();
  6916. if (node.type === "JSXNamespacedName") {
  6917. return node;
  6918. }
  6919. while (this.eat(16)) {
  6920. const newNode = this.startNodeAt(startPos, startLoc);
  6921. newNode.object = node;
  6922. newNode.property = this.jsxParseIdentifier();
  6923. node = this.finishNode(newNode, "JSXMemberExpression");
  6924. }
  6925. return node;
  6926. }
  6927. jsxParseAttributeValue() {
  6928. let node;
  6929. switch (this.state.type) {
  6930. case 5:
  6931. node = this.startNode();
  6932. this.next();
  6933. node = this.jsxParseExpressionContainer(node);
  6934. if (node.expression.type === "JSXEmptyExpression") {
  6935. this.raise(node.start, JsxErrors.AttributeIsEmpty);
  6936. }
  6937. return node;
  6938. case 132:
  6939. case 123:
  6940. return this.parseExprAtom();
  6941. default:
  6942. throw this.raise(this.state.start, JsxErrors.UnsupportedJsxValue);
  6943. }
  6944. }
  6945. jsxParseEmptyExpression() {
  6946. const node = this.startNodeAt(this.state.lastTokEnd, this.state.lastTokEndLoc);
  6947. return this.finishNodeAt(node, "JSXEmptyExpression", this.state.start, this.state.startLoc);
  6948. }
  6949. jsxParseSpreadChild(node) {
  6950. this.next();
  6951. node.expression = this.parseExpression();
  6952. this.expect(8);
  6953. return this.finishNode(node, "JSXSpreadChild");
  6954. }
  6955. jsxParseExpressionContainer(node) {
  6956. if (this.match(8)) {
  6957. node.expression = this.jsxParseEmptyExpression();
  6958. } else {
  6959. const expression = this.parseExpression();
  6960. node.expression = expression;
  6961. }
  6962. this.expect(8);
  6963. return this.finishNode(node, "JSXExpressionContainer");
  6964. }
  6965. jsxParseAttribute() {
  6966. const node = this.startNode();
  6967. if (this.eat(5)) {
  6968. this.expect(21);
  6969. node.argument = this.parseMaybeAssignAllowIn();
  6970. this.expect(8);
  6971. return this.finishNode(node, "JSXSpreadAttribute");
  6972. }
  6973. node.name = this.jsxParseNamespacedName();
  6974. node.value = this.eat(27) ? this.jsxParseAttributeValue() : null;
  6975. return this.finishNode(node, "JSXAttribute");
  6976. }
  6977. jsxParseOpeningElementAt(startPos, startLoc) {
  6978. const node = this.startNodeAt(startPos, startLoc);
  6979. if (this.match(133)) {
  6980. this.expect(133);
  6981. return this.finishNode(node, "JSXOpeningFragment");
  6982. }
  6983. node.name = this.jsxParseElementName();
  6984. return this.jsxParseOpeningElementAfterName(node);
  6985. }
  6986. jsxParseOpeningElementAfterName(node) {
  6987. const attributes = [];
  6988. while (!this.match(50) && !this.match(133)) {
  6989. attributes.push(this.jsxParseAttribute());
  6990. }
  6991. node.attributes = attributes;
  6992. node.selfClosing = this.eat(50);
  6993. this.expect(133);
  6994. return this.finishNode(node, "JSXOpeningElement");
  6995. }
  6996. jsxParseClosingElementAt(startPos, startLoc) {
  6997. const node = this.startNodeAt(startPos, startLoc);
  6998. if (this.match(133)) {
  6999. this.expect(133);
  7000. return this.finishNode(node, "JSXClosingFragment");
  7001. }
  7002. node.name = this.jsxParseElementName();
  7003. this.expect(133);
  7004. return this.finishNode(node, "JSXClosingElement");
  7005. }
  7006. jsxParseElementAt(startPos, startLoc) {
  7007. const node = this.startNodeAt(startPos, startLoc);
  7008. const children = [];
  7009. const openingElement = this.jsxParseOpeningElementAt(startPos, startLoc);
  7010. let closingElement = null;
  7011. if (!openingElement.selfClosing) {
  7012. contents: for (;;) {
  7013. switch (this.state.type) {
  7014. case 132:
  7015. startPos = this.state.start;
  7016. startLoc = this.state.startLoc;
  7017. this.next();
  7018. if (this.eat(50)) {
  7019. closingElement = this.jsxParseClosingElementAt(startPos, startLoc);
  7020. break contents;
  7021. }
  7022. children.push(this.jsxParseElementAt(startPos, startLoc));
  7023. break;
  7024. case 131:
  7025. children.push(this.parseExprAtom());
  7026. break;
  7027. case 5:
  7028. {
  7029. const node = this.startNode();
  7030. this.next();
  7031. if (this.match(21)) {
  7032. children.push(this.jsxParseSpreadChild(node));
  7033. } else {
  7034. children.push(this.jsxParseExpressionContainer(node));
  7035. }
  7036. break;
  7037. }
  7038. default:
  7039. throw this.unexpected();
  7040. }
  7041. }
  7042. if (isFragment(openingElement) && !isFragment(closingElement)) {
  7043. this.raise(closingElement.start, JsxErrors.MissingClosingTagFragment);
  7044. } else if (!isFragment(openingElement) && isFragment(closingElement)) {
  7045. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  7046. } else if (!isFragment(openingElement) && !isFragment(closingElement)) {
  7047. if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
  7048. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  7049. }
  7050. }
  7051. }
  7052. if (isFragment(openingElement)) {
  7053. node.openingFragment = openingElement;
  7054. node.closingFragment = closingElement;
  7055. } else {
  7056. node.openingElement = openingElement;
  7057. node.closingElement = closingElement;
  7058. }
  7059. node.children = children;
  7060. if (this.match(43)) {
  7061. throw this.raise(this.state.start, JsxErrors.UnwrappedAdjacentJSXElements);
  7062. }
  7063. return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement");
  7064. }
  7065. jsxParseElement() {
  7066. const startPos = this.state.start;
  7067. const startLoc = this.state.startLoc;
  7068. this.next();
  7069. return this.jsxParseElementAt(startPos, startLoc);
  7070. }
  7071. parseExprAtom(refExpressionErrors) {
  7072. if (this.match(131)) {
  7073. return this.parseLiteral(this.state.value, "JSXText");
  7074. } else if (this.match(132)) {
  7075. return this.jsxParseElement();
  7076. } else if (this.match(43) && this.input.charCodeAt(this.state.pos) !== 33) {
  7077. this.replaceToken(132);
  7078. return this.jsxParseElement();
  7079. } else {
  7080. return super.parseExprAtom(refExpressionErrors);
  7081. }
  7082. }
  7083. getTokenFromCode(code) {
  7084. const context = this.curContext();
  7085. if (context === types$1.j_expr) {
  7086. return this.jsxReadToken();
  7087. }
  7088. if (context === types$1.j_oTag || context === types$1.j_cTag) {
  7089. if (isIdentifierStart(code)) {
  7090. return this.jsxReadWord();
  7091. }
  7092. if (code === 62) {
  7093. ++this.state.pos;
  7094. return this.finishToken(133);
  7095. }
  7096. if ((code === 34 || code === 39) && context === types$1.j_oTag) {
  7097. return this.jsxReadString(code);
  7098. }
  7099. }
  7100. if (code === 60 && this.state.canStartJSXElement && this.input.charCodeAt(this.state.pos + 1) !== 33) {
  7101. ++this.state.pos;
  7102. return this.finishToken(132);
  7103. }
  7104. return super.getTokenFromCode(code);
  7105. }
  7106. updateContext(prevType) {
  7107. super.updateContext(prevType);
  7108. const {
  7109. context,
  7110. type
  7111. } = this.state;
  7112. if (type === 50 && prevType === 132) {
  7113. context.splice(-2, 2, types$1.j_cTag);
  7114. this.state.canStartJSXElement = false;
  7115. } else if (type === 132) {
  7116. context.push(types$1.j_expr, types$1.j_oTag);
  7117. } else if (type === 133) {
  7118. const out = context.pop();
  7119. if (out === types$1.j_oTag && prevType === 50 || out === types$1.j_cTag) {
  7120. context.pop();
  7121. this.state.canStartJSXElement = context[context.length - 1] === types$1.j_expr;
  7122. } else {
  7123. this.state.canStartJSXElement = true;
  7124. }
  7125. } else {
  7126. this.state.canStartJSXElement = tokenComesBeforeExpression(type);
  7127. }
  7128. }
  7129. });
  7130. class TypeScriptScope extends Scope {
  7131. constructor(...args) {
  7132. super(...args);
  7133. this.types = new Set();
  7134. this.enums = new Set();
  7135. this.constEnums = new Set();
  7136. this.classes = new Set();
  7137. this.exportOnlyBindings = new Set();
  7138. }
  7139. }
  7140. class TypeScriptScopeHandler extends ScopeHandler {
  7141. createScope(flags) {
  7142. return new TypeScriptScope(flags);
  7143. }
  7144. declareName(name, bindingType, pos) {
  7145. const scope = this.currentScope();
  7146. if (bindingType & BIND_FLAGS_TS_EXPORT_ONLY) {
  7147. this.maybeExportDefined(scope, name);
  7148. scope.exportOnlyBindings.add(name);
  7149. return;
  7150. }
  7151. super.declareName(...arguments);
  7152. if (bindingType & BIND_KIND_TYPE) {
  7153. if (!(bindingType & BIND_KIND_VALUE)) {
  7154. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  7155. this.maybeExportDefined(scope, name);
  7156. }
  7157. scope.types.add(name);
  7158. }
  7159. if (bindingType & BIND_FLAGS_TS_ENUM) scope.enums.add(name);
  7160. if (bindingType & BIND_FLAGS_TS_CONST_ENUM) scope.constEnums.add(name);
  7161. if (bindingType & BIND_FLAGS_CLASS) scope.classes.add(name);
  7162. }
  7163. isRedeclaredInScope(scope, name, bindingType) {
  7164. if (scope.enums.has(name)) {
  7165. if (bindingType & BIND_FLAGS_TS_ENUM) {
  7166. const isConst = !!(bindingType & BIND_FLAGS_TS_CONST_ENUM);
  7167. const wasConst = scope.constEnums.has(name);
  7168. return isConst !== wasConst;
  7169. }
  7170. return true;
  7171. }
  7172. if (bindingType & BIND_FLAGS_CLASS && scope.classes.has(name)) {
  7173. if (scope.lexical.has(name)) {
  7174. return !!(bindingType & BIND_KIND_VALUE);
  7175. } else {
  7176. return false;
  7177. }
  7178. }
  7179. if (bindingType & BIND_KIND_TYPE && scope.types.has(name)) {
  7180. return true;
  7181. }
  7182. return super.isRedeclaredInScope(...arguments);
  7183. }
  7184. checkLocalExport(id) {
  7185. const topLevelScope = this.scopeStack[0];
  7186. const {
  7187. name
  7188. } = id;
  7189. if (!topLevelScope.types.has(name) && !topLevelScope.exportOnlyBindings.has(name)) {
  7190. super.checkLocalExport(id);
  7191. }
  7192. }
  7193. }
  7194. function nonNull(x) {
  7195. if (x == null) {
  7196. throw new Error(`Unexpected ${x} value.`);
  7197. }
  7198. return x;
  7199. }
  7200. function assert$1(x) {
  7201. if (!x) {
  7202. throw new Error("Assert fail");
  7203. }
  7204. }
  7205. const TSErrors = makeErrorTemplates({
  7206. AbstractMethodHasImplementation: "Method '%0' cannot have an implementation because it is marked abstract.",
  7207. AbstractPropertyHasInitializer: "Property '%0' cannot have an initializer because it is marked abstract.",
  7208. AccesorCannotDeclareThisParameter: "'get' and 'set' accessors cannot declare 'this' parameters.",
  7209. AccesorCannotHaveTypeParameters: "An accessor cannot have type parameters.",
  7210. ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier.",
  7211. ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier.",
  7212. ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.",
  7213. DeclareAccessor: "'declare' is not allowed in %0ters.",
  7214. DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.",
  7215. DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.",
  7216. DuplicateAccessibilityModifier: "Accessibility modifier already seen.",
  7217. DuplicateModifier: "Duplicate modifier: '%0'.",
  7218. EmptyHeritageClauseType: "'%0' list cannot be empty.",
  7219. EmptyTypeArguments: "Type argument list cannot be empty.",
  7220. EmptyTypeParameters: "Type parameter list cannot be empty.",
  7221. ExpectedAmbientAfterExportDeclare: "'export declare' must be followed by an ambient declaration.",
  7222. ImportAliasHasImportType: "An import alias can not use 'import type'.",
  7223. IncompatibleModifiers: "'%0' modifier cannot be used with '%1' modifier.",
  7224. IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier.",
  7225. IndexSignatureHasAccessibility: "Index signatures cannot have an accessibility modifier ('%0').",
  7226. IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier.",
  7227. IndexSignatureHasOverride: "'override' modifier cannot appear on an index signature.",
  7228. IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier.",
  7229. InvalidModifierOnTypeMember: "'%0' modifier cannot appear on a type member.",
  7230. InvalidModifiersOrder: "'%0' modifier must precede '%1' modifier.",
  7231. InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.",
  7232. MissingInterfaceName: "'interface' declarations must be followed by an identifier.",
  7233. MixedLabeledAndUnlabeledElements: "Tuple members must all have names or all not have names.",
  7234. NonAbstractClassHasAbstractMethod: "Abstract methods can only appear within an abstract class.",
  7235. NonClassMethodPropertyHasAbstractModifer: "'abstract' modifier can only appear on a class, method, or property declaration.",
  7236. OptionalTypeBeforeRequired: "A required element cannot follow an optional element.",
  7237. OverrideNotInSubClass: "This member cannot have an 'override' modifier because its containing class does not extend another class.",
  7238. PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.",
  7239. PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.",
  7240. PrivateElementHasAccessibility: "Private elements cannot have an accessibility modifier ('%0').",
  7241. ReadonlyForMethodSignature: "'readonly' modifier can only appear on a property declaration or index signature.",
  7242. ReservedArrowTypeParam: "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma, as in `<T,>() => ...`.",
  7243. ReservedTypeAssertion: "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.",
  7244. SetAccesorCannotHaveOptionalParameter: "A 'set' accessor cannot have an optional parameter.",
  7245. SetAccesorCannotHaveRestParameter: "A 'set' accessor cannot have rest parameter.",
  7246. SetAccesorCannotHaveReturnType: "A 'set' accessor cannot have a return type annotation.",
  7247. StaticBlockCannotHaveModifier: "Static class blocks cannot have any modifier.",
  7248. TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",
  7249. TypeImportCannotSpecifyDefaultAndNamed: "A type-only import can specify a default import or named bindings, but not both.",
  7250. TypeModifierIsUsedInTypeExports: "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.",
  7251. TypeModifierIsUsedInTypeImports: "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.",
  7252. UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.",
  7253. UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.",
  7254. UnexpectedTypeAnnotation: "Did not expect a type annotation here.",
  7255. UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.",
  7256. UnsupportedImportTypeArgument: "Argument in a type import must be a string literal.",
  7257. UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.",
  7258. UnsupportedSignatureParameterKind: "Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got %0."
  7259. }, ErrorCodes.SyntaxError, "typescript");
  7260. function keywordTypeFromName(value) {
  7261. switch (value) {
  7262. case "any":
  7263. return "TSAnyKeyword";
  7264. case "boolean":
  7265. return "TSBooleanKeyword";
  7266. case "bigint":
  7267. return "TSBigIntKeyword";
  7268. case "never":
  7269. return "TSNeverKeyword";
  7270. case "number":
  7271. return "TSNumberKeyword";
  7272. case "object":
  7273. return "TSObjectKeyword";
  7274. case "string":
  7275. return "TSStringKeyword";
  7276. case "symbol":
  7277. return "TSSymbolKeyword";
  7278. case "undefined":
  7279. return "TSUndefinedKeyword";
  7280. case "unknown":
  7281. return "TSUnknownKeyword";
  7282. default:
  7283. return undefined;
  7284. }
  7285. }
  7286. function tsIsAccessModifier(modifier) {
  7287. return modifier === "private" || modifier === "public" || modifier === "protected";
  7288. }
  7289. var typescript = (superClass => class extends superClass {
  7290. getScopeHandler() {
  7291. return TypeScriptScopeHandler;
  7292. }
  7293. tsIsIdentifier() {
  7294. return tokenIsIdentifier(this.state.type);
  7295. }
  7296. tsTokenCanFollowModifier() {
  7297. return (this.match(0) || this.match(5) || this.match(49) || this.match(21) || this.match(128) || this.isLiteralPropertyName()) && !this.hasPrecedingLineBreak();
  7298. }
  7299. tsNextTokenCanFollowModifier() {
  7300. this.next();
  7301. return this.tsTokenCanFollowModifier();
  7302. }
  7303. tsParseModifier(allowedModifiers, stopOnStartOfClassStaticBlock) {
  7304. if (!tokenIsIdentifier(this.state.type)) {
  7305. return undefined;
  7306. }
  7307. const modifier = this.state.value;
  7308. if (allowedModifiers.indexOf(modifier) !== -1) {
  7309. if (stopOnStartOfClassStaticBlock && this.tsIsStartOfStaticBlocks()) {
  7310. return undefined;
  7311. }
  7312. if (this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {
  7313. return modifier;
  7314. }
  7315. }
  7316. return undefined;
  7317. }
  7318. tsParseModifiers(modified, allowedModifiers, disallowedModifiers, errorTemplate, stopOnStartOfClassStaticBlock) {
  7319. const enforceOrder = (pos, modifier, before, after) => {
  7320. if (modifier === before && modified[after]) {
  7321. this.raise(pos, TSErrors.InvalidModifiersOrder, before, after);
  7322. }
  7323. };
  7324. const incompatible = (pos, modifier, mod1, mod2) => {
  7325. if (modified[mod1] && modifier === mod2 || modified[mod2] && modifier === mod1) {
  7326. this.raise(pos, TSErrors.IncompatibleModifiers, mod1, mod2);
  7327. }
  7328. };
  7329. for (;;) {
  7330. const startPos = this.state.start;
  7331. const modifier = this.tsParseModifier(allowedModifiers.concat(disallowedModifiers != null ? disallowedModifiers : []), stopOnStartOfClassStaticBlock);
  7332. if (!modifier) break;
  7333. if (tsIsAccessModifier(modifier)) {
  7334. if (modified.accessibility) {
  7335. this.raise(startPos, TSErrors.DuplicateAccessibilityModifier);
  7336. } else {
  7337. enforceOrder(startPos, modifier, modifier, "override");
  7338. enforceOrder(startPos, modifier, modifier, "static");
  7339. enforceOrder(startPos, modifier, modifier, "readonly");
  7340. modified.accessibility = modifier;
  7341. }
  7342. } else {
  7343. if (Object.hasOwnProperty.call(modified, modifier)) {
  7344. this.raise(startPos, TSErrors.DuplicateModifier, modifier);
  7345. } else {
  7346. enforceOrder(startPos, modifier, "static", "readonly");
  7347. enforceOrder(startPos, modifier, "static", "override");
  7348. enforceOrder(startPos, modifier, "override", "readonly");
  7349. enforceOrder(startPos, modifier, "abstract", "override");
  7350. incompatible(startPos, modifier, "declare", "override");
  7351. incompatible(startPos, modifier, "static", "abstract");
  7352. }
  7353. modified[modifier] = true;
  7354. }
  7355. if (disallowedModifiers != null && disallowedModifiers.includes(modifier)) {
  7356. this.raise(startPos, errorTemplate, modifier);
  7357. }
  7358. }
  7359. }
  7360. tsIsListTerminator(kind) {
  7361. switch (kind) {
  7362. case "EnumMembers":
  7363. case "TypeMembers":
  7364. return this.match(8);
  7365. case "HeritageClauseElement":
  7366. return this.match(5);
  7367. case "TupleElementTypes":
  7368. return this.match(3);
  7369. case "TypeParametersOrArguments":
  7370. return this.match(44);
  7371. }
  7372. throw new Error("Unreachable");
  7373. }
  7374. tsParseList(kind, parseElement) {
  7375. const result = [];
  7376. while (!this.tsIsListTerminator(kind)) {
  7377. result.push(parseElement());
  7378. }
  7379. return result;
  7380. }
  7381. tsParseDelimitedList(kind, parseElement, refTrailingCommaPos) {
  7382. return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true, refTrailingCommaPos));
  7383. }
  7384. tsParseDelimitedListWorker(kind, parseElement, expectSuccess, refTrailingCommaPos) {
  7385. const result = [];
  7386. let trailingCommaPos = -1;
  7387. for (;;) {
  7388. if (this.tsIsListTerminator(kind)) {
  7389. break;
  7390. }
  7391. trailingCommaPos = -1;
  7392. const element = parseElement();
  7393. if (element == null) {
  7394. return undefined;
  7395. }
  7396. result.push(element);
  7397. if (this.eat(12)) {
  7398. trailingCommaPos = this.state.lastTokStart;
  7399. continue;
  7400. }
  7401. if (this.tsIsListTerminator(kind)) {
  7402. break;
  7403. }
  7404. if (expectSuccess) {
  7405. this.expect(12);
  7406. }
  7407. return undefined;
  7408. }
  7409. if (refTrailingCommaPos) {
  7410. refTrailingCommaPos.value = trailingCommaPos;
  7411. }
  7412. return result;
  7413. }
  7414. tsParseBracketedList(kind, parseElement, bracket, skipFirstToken, refTrailingCommaPos) {
  7415. if (!skipFirstToken) {
  7416. if (bracket) {
  7417. this.expect(0);
  7418. } else {
  7419. this.expect(43);
  7420. }
  7421. }
  7422. const result = this.tsParseDelimitedList(kind, parseElement, refTrailingCommaPos);
  7423. if (bracket) {
  7424. this.expect(3);
  7425. } else {
  7426. this.expect(44);
  7427. }
  7428. return result;
  7429. }
  7430. tsParseImportType() {
  7431. const node = this.startNode();
  7432. this.expect(77);
  7433. this.expect(10);
  7434. if (!this.match(123)) {
  7435. this.raise(this.state.start, TSErrors.UnsupportedImportTypeArgument);
  7436. }
  7437. node.argument = this.parseExprAtom();
  7438. this.expect(11);
  7439. if (this.eat(16)) {
  7440. node.qualifier = this.tsParseEntityName(true);
  7441. }
  7442. if (this.match(43)) {
  7443. node.typeParameters = this.tsParseTypeArguments();
  7444. }
  7445. return this.finishNode(node, "TSImportType");
  7446. }
  7447. tsParseEntityName(allowReservedWords) {
  7448. let entity = this.parseIdentifier();
  7449. while (this.eat(16)) {
  7450. const node = this.startNodeAtNode(entity);
  7451. node.left = entity;
  7452. node.right = this.parseIdentifier(allowReservedWords);
  7453. entity = this.finishNode(node, "TSQualifiedName");
  7454. }
  7455. return entity;
  7456. }
  7457. tsParseTypeReference() {
  7458. const node = this.startNode();
  7459. node.typeName = this.tsParseEntityName(false);
  7460. if (!this.hasPrecedingLineBreak() && this.match(43)) {
  7461. node.typeParameters = this.tsParseTypeArguments();
  7462. }
  7463. return this.finishNode(node, "TSTypeReference");
  7464. }
  7465. tsParseThisTypePredicate(lhs) {
  7466. this.next();
  7467. const node = this.startNodeAtNode(lhs);
  7468. node.parameterName = lhs;
  7469. node.typeAnnotation = this.tsParseTypeAnnotation(false);
  7470. node.asserts = false;
  7471. return this.finishNode(node, "TSTypePredicate");
  7472. }
  7473. tsParseThisTypeNode() {
  7474. const node = this.startNode();
  7475. this.next();
  7476. return this.finishNode(node, "TSThisType");
  7477. }
  7478. tsParseTypeQuery() {
  7479. const node = this.startNode();
  7480. this.expect(81);
  7481. if (this.match(77)) {
  7482. node.exprName = this.tsParseImportType();
  7483. } else {
  7484. node.exprName = this.tsParseEntityName(true);
  7485. }
  7486. return this.finishNode(node, "TSTypeQuery");
  7487. }
  7488. tsParseTypeParameter() {
  7489. const node = this.startNode();
  7490. node.name = this.tsParseTypeParameterName();
  7491. node.constraint = this.tsEatThenParseType(75);
  7492. node.default = this.tsEatThenParseType(27);
  7493. return this.finishNode(node, "TSTypeParameter");
  7494. }
  7495. tsTryParseTypeParameters() {
  7496. if (this.match(43)) {
  7497. return this.tsParseTypeParameters();
  7498. }
  7499. }
  7500. tsParseTypeParameters() {
  7501. const node = this.startNode();
  7502. if (this.match(43) || this.match(132)) {
  7503. this.next();
  7504. } else {
  7505. this.unexpected();
  7506. }
  7507. const refTrailingCommaPos = {
  7508. value: -1
  7509. };
  7510. node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this), false, true, refTrailingCommaPos);
  7511. if (node.params.length === 0) {
  7512. this.raise(node.start, TSErrors.EmptyTypeParameters);
  7513. }
  7514. if (refTrailingCommaPos.value !== -1) {
  7515. this.addExtra(node, "trailingComma", refTrailingCommaPos.value);
  7516. }
  7517. return this.finishNode(node, "TSTypeParameterDeclaration");
  7518. }
  7519. tsTryNextParseConstantContext() {
  7520. if (this.lookahead().type === 69) {
  7521. this.next();
  7522. return this.tsParseTypeReference();
  7523. }
  7524. return null;
  7525. }
  7526. tsFillSignature(returnToken, signature) {
  7527. const returnTokenRequired = returnToken === 19;
  7528. signature.typeParameters = this.tsTryParseTypeParameters();
  7529. this.expect(10);
  7530. signature.parameters = this.tsParseBindingListForSignature();
  7531. if (returnTokenRequired) {
  7532. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  7533. } else if (this.match(returnToken)) {
  7534. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  7535. }
  7536. }
  7537. tsParseBindingListForSignature() {
  7538. return this.parseBindingList(11, 41).map(pattern => {
  7539. if (pattern.type !== "Identifier" && pattern.type !== "RestElement" && pattern.type !== "ObjectPattern" && pattern.type !== "ArrayPattern") {
  7540. this.raise(pattern.start, TSErrors.UnsupportedSignatureParameterKind, pattern.type);
  7541. }
  7542. return pattern;
  7543. });
  7544. }
  7545. tsParseTypeMemberSemicolon() {
  7546. if (!this.eat(12) && !this.isLineTerminator()) {
  7547. this.expect(13);
  7548. }
  7549. }
  7550. tsParseSignatureMember(kind, node) {
  7551. this.tsFillSignature(14, node);
  7552. this.tsParseTypeMemberSemicolon();
  7553. return this.finishNode(node, kind);
  7554. }
  7555. tsIsUnambiguouslyIndexSignature() {
  7556. this.next();
  7557. if (tokenIsIdentifier(this.state.type)) {
  7558. this.next();
  7559. return this.match(14);
  7560. }
  7561. return false;
  7562. }
  7563. tsTryParseIndexSignature(node) {
  7564. if (!(this.match(0) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) {
  7565. return undefined;
  7566. }
  7567. this.expect(0);
  7568. const id = this.parseIdentifier();
  7569. id.typeAnnotation = this.tsParseTypeAnnotation();
  7570. this.resetEndLocation(id);
  7571. this.expect(3);
  7572. node.parameters = [id];
  7573. const type = this.tsTryParseTypeAnnotation();
  7574. if (type) node.typeAnnotation = type;
  7575. this.tsParseTypeMemberSemicolon();
  7576. return this.finishNode(node, "TSIndexSignature");
  7577. }
  7578. tsParsePropertyOrMethodSignature(node, readonly) {
  7579. if (this.eat(17)) node.optional = true;
  7580. const nodeAny = node;
  7581. if (this.match(10) || this.match(43)) {
  7582. if (readonly) {
  7583. this.raise(node.start, TSErrors.ReadonlyForMethodSignature);
  7584. }
  7585. const method = nodeAny;
  7586. if (method.kind && this.match(43)) {
  7587. this.raise(this.state.pos, TSErrors.AccesorCannotHaveTypeParameters);
  7588. }
  7589. this.tsFillSignature(14, method);
  7590. this.tsParseTypeMemberSemicolon();
  7591. if (method.kind === "get") {
  7592. if (method.parameters.length > 0) {
  7593. this.raise(this.state.pos, ErrorMessages.BadGetterArity);
  7594. if (this.isThisParam(method.parameters[0])) {
  7595. this.raise(this.state.pos, TSErrors.AccesorCannotDeclareThisParameter);
  7596. }
  7597. }
  7598. } else if (method.kind === "set") {
  7599. if (method.parameters.length !== 1) {
  7600. this.raise(this.state.pos, ErrorMessages.BadSetterArity);
  7601. } else {
  7602. const firstParameter = method.parameters[0];
  7603. if (this.isThisParam(firstParameter)) {
  7604. this.raise(this.state.pos, TSErrors.AccesorCannotDeclareThisParameter);
  7605. }
  7606. if (firstParameter.type === "Identifier" && firstParameter.optional) {
  7607. this.raise(this.state.pos, TSErrors.SetAccesorCannotHaveOptionalParameter);
  7608. }
  7609. if (firstParameter.type === "RestElement") {
  7610. this.raise(this.state.pos, TSErrors.SetAccesorCannotHaveRestParameter);
  7611. }
  7612. }
  7613. if (method.typeAnnotation) {
  7614. this.raise(method.typeAnnotation.start, TSErrors.SetAccesorCannotHaveReturnType);
  7615. }
  7616. } else {
  7617. method.kind = "method";
  7618. }
  7619. return this.finishNode(method, "TSMethodSignature");
  7620. } else {
  7621. const property = nodeAny;
  7622. if (readonly) property.readonly = true;
  7623. const type = this.tsTryParseTypeAnnotation();
  7624. if (type) property.typeAnnotation = type;
  7625. this.tsParseTypeMemberSemicolon();
  7626. return this.finishNode(property, "TSPropertySignature");
  7627. }
  7628. }
  7629. tsParseTypeMember() {
  7630. const node = this.startNode();
  7631. if (this.match(10) || this.match(43)) {
  7632. return this.tsParseSignatureMember("TSCallSignatureDeclaration", node);
  7633. }
  7634. if (this.match(71)) {
  7635. const id = this.startNode();
  7636. this.next();
  7637. if (this.match(10) || this.match(43)) {
  7638. return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node);
  7639. } else {
  7640. node.key = this.createIdentifier(id, "new");
  7641. return this.tsParsePropertyOrMethodSignature(node, false);
  7642. }
  7643. }
  7644. this.tsParseModifiers(node, ["readonly"], ["declare", "abstract", "private", "protected", "public", "static", "override"], TSErrors.InvalidModifierOnTypeMember);
  7645. const idx = this.tsTryParseIndexSignature(node);
  7646. if (idx) {
  7647. return idx;
  7648. }
  7649. this.parsePropertyName(node);
  7650. if (!node.computed && node.key.type === "Identifier" && (node.key.name === "get" || node.key.name === "set") && this.tsTokenCanFollowModifier()) {
  7651. node.kind = node.key.name;
  7652. this.parsePropertyName(node);
  7653. }
  7654. return this.tsParsePropertyOrMethodSignature(node, !!node.readonly);
  7655. }
  7656. tsParseTypeLiteral() {
  7657. const node = this.startNode();
  7658. node.members = this.tsParseObjectTypeMembers();
  7659. return this.finishNode(node, "TSTypeLiteral");
  7660. }
  7661. tsParseObjectTypeMembers() {
  7662. this.expect(5);
  7663. const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this));
  7664. this.expect(8);
  7665. return members;
  7666. }
  7667. tsIsStartOfMappedType() {
  7668. this.next();
  7669. if (this.eat(47)) {
  7670. return this.isContextual(112);
  7671. }
  7672. if (this.isContextual(112)) {
  7673. this.next();
  7674. }
  7675. if (!this.match(0)) {
  7676. return false;
  7677. }
  7678. this.next();
  7679. if (!this.tsIsIdentifier()) {
  7680. return false;
  7681. }
  7682. this.next();
  7683. return this.match(52);
  7684. }
  7685. tsParseMappedTypeParameter() {
  7686. const node = this.startNode();
  7687. node.name = this.tsParseTypeParameterName();
  7688. node.constraint = this.tsExpectThenParseType(52);
  7689. return this.finishNode(node, "TSTypeParameter");
  7690. }
  7691. tsParseMappedType() {
  7692. const node = this.startNode();
  7693. this.expect(5);
  7694. if (this.match(47)) {
  7695. node.readonly = this.state.value;
  7696. this.next();
  7697. this.expectContextual(112);
  7698. } else if (this.eatContextual(112)) {
  7699. node.readonly = true;
  7700. }
  7701. this.expect(0);
  7702. node.typeParameter = this.tsParseMappedTypeParameter();
  7703. node.nameType = this.eatContextual(87) ? this.tsParseType() : null;
  7704. this.expect(3);
  7705. if (this.match(47)) {
  7706. node.optional = this.state.value;
  7707. this.next();
  7708. this.expect(17);
  7709. } else if (this.eat(17)) {
  7710. node.optional = true;
  7711. }
  7712. node.typeAnnotation = this.tsTryParseType();
  7713. this.semicolon();
  7714. this.expect(8);
  7715. return this.finishNode(node, "TSMappedType");
  7716. }
  7717. tsParseTupleType() {
  7718. const node = this.startNode();
  7719. node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false);
  7720. let seenOptionalElement = false;
  7721. let labeledElements = null;
  7722. node.elementTypes.forEach(elementNode => {
  7723. var _labeledElements;
  7724. let {
  7725. type
  7726. } = elementNode;
  7727. if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) {
  7728. this.raise(elementNode.start, TSErrors.OptionalTypeBeforeRequired);
  7729. }
  7730. seenOptionalElement = seenOptionalElement || type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType";
  7731. if (type === "TSRestType") {
  7732. elementNode = elementNode.typeAnnotation;
  7733. type = elementNode.type;
  7734. }
  7735. const isLabeled = type === "TSNamedTupleMember";
  7736. labeledElements = (_labeledElements = labeledElements) != null ? _labeledElements : isLabeled;
  7737. if (labeledElements !== isLabeled) {
  7738. this.raise(elementNode.start, TSErrors.MixedLabeledAndUnlabeledElements);
  7739. }
  7740. });
  7741. return this.finishNode(node, "TSTupleType");
  7742. }
  7743. tsParseTupleElementType() {
  7744. const {
  7745. start: startPos,
  7746. startLoc
  7747. } = this.state;
  7748. const rest = this.eat(21);
  7749. let type = this.tsParseType();
  7750. const optional = this.eat(17);
  7751. const labeled = this.eat(14);
  7752. if (labeled) {
  7753. const labeledNode = this.startNodeAtNode(type);
  7754. labeledNode.optional = optional;
  7755. if (type.type === "TSTypeReference" && !type.typeParameters && type.typeName.type === "Identifier") {
  7756. labeledNode.label = type.typeName;
  7757. } else {
  7758. this.raise(type.start, TSErrors.InvalidTupleMemberLabel);
  7759. labeledNode.label = type;
  7760. }
  7761. labeledNode.elementType = this.tsParseType();
  7762. type = this.finishNode(labeledNode, "TSNamedTupleMember");
  7763. } else if (optional) {
  7764. const optionalTypeNode = this.startNodeAtNode(type);
  7765. optionalTypeNode.typeAnnotation = type;
  7766. type = this.finishNode(optionalTypeNode, "TSOptionalType");
  7767. }
  7768. if (rest) {
  7769. const restNode = this.startNodeAt(startPos, startLoc);
  7770. restNode.typeAnnotation = type;
  7771. type = this.finishNode(restNode, "TSRestType");
  7772. }
  7773. return type;
  7774. }
  7775. tsParseParenthesizedType() {
  7776. const node = this.startNode();
  7777. this.expect(10);
  7778. node.typeAnnotation = this.tsParseType();
  7779. this.expect(11);
  7780. return this.finishNode(node, "TSParenthesizedType");
  7781. }
  7782. tsParseFunctionOrConstructorType(type, abstract) {
  7783. const node = this.startNode();
  7784. if (type === "TSConstructorType") {
  7785. node.abstract = !!abstract;
  7786. if (abstract) this.next();
  7787. this.next();
  7788. }
  7789. this.tsFillSignature(19, node);
  7790. return this.finishNode(node, type);
  7791. }
  7792. tsParseLiteralTypeNode() {
  7793. const node = this.startNode();
  7794. node.literal = (() => {
  7795. switch (this.state.type) {
  7796. case 124:
  7797. case 125:
  7798. case 123:
  7799. case 79:
  7800. case 80:
  7801. return this.parseExprAtom();
  7802. default:
  7803. throw this.unexpected();
  7804. }
  7805. })();
  7806. return this.finishNode(node, "TSLiteralType");
  7807. }
  7808. tsParseTemplateLiteralType() {
  7809. const node = this.startNode();
  7810. node.literal = this.parseTemplate(false);
  7811. return this.finishNode(node, "TSLiteralType");
  7812. }
  7813. parseTemplateSubstitution() {
  7814. if (this.state.inType) return this.tsParseType();
  7815. return super.parseTemplateSubstitution();
  7816. }
  7817. tsParseThisTypeOrThisTypePredicate() {
  7818. const thisKeyword = this.tsParseThisTypeNode();
  7819. if (this.isContextual(107) && !this.hasPrecedingLineBreak()) {
  7820. return this.tsParseThisTypePredicate(thisKeyword);
  7821. } else {
  7822. return thisKeyword;
  7823. }
  7824. }
  7825. tsParseNonArrayType() {
  7826. switch (this.state.type) {
  7827. case 123:
  7828. case 124:
  7829. case 125:
  7830. case 79:
  7831. case 80:
  7832. return this.tsParseLiteralTypeNode();
  7833. case 47:
  7834. if (this.state.value === "-") {
  7835. const node = this.startNode();
  7836. const nextToken = this.lookahead();
  7837. if (nextToken.type !== 124 && nextToken.type !== 125) {
  7838. throw this.unexpected();
  7839. }
  7840. node.literal = this.parseMaybeUnary();
  7841. return this.finishNode(node, "TSLiteralType");
  7842. }
  7843. break;
  7844. case 72:
  7845. return this.tsParseThisTypeOrThisTypePredicate();
  7846. case 81:
  7847. return this.tsParseTypeQuery();
  7848. case 77:
  7849. return this.tsParseImportType();
  7850. case 5:
  7851. return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral();
  7852. case 0:
  7853. return this.tsParseTupleType();
  7854. case 10:
  7855. return this.tsParseParenthesizedType();
  7856. case 22:
  7857. return this.tsParseTemplateLiteralType();
  7858. default:
  7859. {
  7860. const {
  7861. type
  7862. } = this.state;
  7863. if (tokenIsIdentifier(type) || type === 82 || type === 78) {
  7864. const nodeType = type === 82 ? "TSVoidKeyword" : type === 78 ? "TSNullKeyword" : keywordTypeFromName(this.state.value);
  7865. if (nodeType !== undefined && this.lookaheadCharCode() !== 46) {
  7866. const node = this.startNode();
  7867. this.next();
  7868. return this.finishNode(node, nodeType);
  7869. }
  7870. return this.tsParseTypeReference();
  7871. }
  7872. }
  7873. }
  7874. throw this.unexpected();
  7875. }
  7876. tsParseArrayTypeOrHigher() {
  7877. let type = this.tsParseNonArrayType();
  7878. while (!this.hasPrecedingLineBreak() && this.eat(0)) {
  7879. if (this.match(3)) {
  7880. const node = this.startNodeAtNode(type);
  7881. node.elementType = type;
  7882. this.expect(3);
  7883. type = this.finishNode(node, "TSArrayType");
  7884. } else {
  7885. const node = this.startNodeAtNode(type);
  7886. node.objectType = type;
  7887. node.indexType = this.tsParseType();
  7888. this.expect(3);
  7889. type = this.finishNode(node, "TSIndexedAccessType");
  7890. }
  7891. }
  7892. return type;
  7893. }
  7894. tsParseTypeOperator() {
  7895. const node = this.startNode();
  7896. const operator = this.state.value;
  7897. this.next();
  7898. node.operator = operator;
  7899. node.typeAnnotation = this.tsParseTypeOperatorOrHigher();
  7900. if (operator === "readonly") {
  7901. this.tsCheckTypeAnnotationForReadOnly(node);
  7902. }
  7903. return this.finishNode(node, "TSTypeOperator");
  7904. }
  7905. tsCheckTypeAnnotationForReadOnly(node) {
  7906. switch (node.typeAnnotation.type) {
  7907. case "TSTupleType":
  7908. case "TSArrayType":
  7909. return;
  7910. default:
  7911. this.raise(node.start, TSErrors.UnexpectedReadonly);
  7912. }
  7913. }
  7914. tsParseInferType() {
  7915. const node = this.startNode();
  7916. this.expectContextual(106);
  7917. const typeParameter = this.startNode();
  7918. typeParameter.name = this.tsParseTypeParameterName();
  7919. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  7920. return this.finishNode(node, "TSInferType");
  7921. }
  7922. tsParseTypeOperatorOrHigher() {
  7923. const isTypeOperator = tokenIsTSTypeOperator(this.state.type) && !this.state.containsEsc;
  7924. return isTypeOperator ? this.tsParseTypeOperator() : this.isContextual(106) ? this.tsParseInferType() : this.tsParseArrayTypeOrHigher();
  7925. }
  7926. tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) {
  7927. const node = this.startNode();
  7928. const hasLeadingOperator = this.eat(operator);
  7929. const types = [];
  7930. do {
  7931. types.push(parseConstituentType());
  7932. } while (this.eat(operator));
  7933. if (types.length === 1 && !hasLeadingOperator) {
  7934. return types[0];
  7935. }
  7936. node.types = types;
  7937. return this.finishNode(node, kind);
  7938. }
  7939. tsParseIntersectionTypeOrHigher() {
  7940. return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), 41);
  7941. }
  7942. tsParseUnionTypeOrHigher() {
  7943. return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), 39);
  7944. }
  7945. tsIsStartOfFunctionType() {
  7946. if (this.match(43)) {
  7947. return true;
  7948. }
  7949. return this.match(10) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this));
  7950. }
  7951. tsSkipParameterStart() {
  7952. if (tokenIsIdentifier(this.state.type) || this.match(72)) {
  7953. this.next();
  7954. return true;
  7955. }
  7956. if (this.match(5)) {
  7957. let braceStackCounter = 1;
  7958. this.next();
  7959. while (braceStackCounter > 0) {
  7960. if (this.match(5)) {
  7961. ++braceStackCounter;
  7962. } else if (this.match(8)) {
  7963. --braceStackCounter;
  7964. }
  7965. this.next();
  7966. }
  7967. return true;
  7968. }
  7969. if (this.match(0)) {
  7970. let braceStackCounter = 1;
  7971. this.next();
  7972. while (braceStackCounter > 0) {
  7973. if (this.match(0)) {
  7974. ++braceStackCounter;
  7975. } else if (this.match(3)) {
  7976. --braceStackCounter;
  7977. }
  7978. this.next();
  7979. }
  7980. return true;
  7981. }
  7982. return false;
  7983. }
  7984. tsIsUnambiguouslyStartOfFunctionType() {
  7985. this.next();
  7986. if (this.match(11) || this.match(21)) {
  7987. return true;
  7988. }
  7989. if (this.tsSkipParameterStart()) {
  7990. if (this.match(14) || this.match(12) || this.match(17) || this.match(27)) {
  7991. return true;
  7992. }
  7993. if (this.match(11)) {
  7994. this.next();
  7995. if (this.match(19)) {
  7996. return true;
  7997. }
  7998. }
  7999. }
  8000. return false;
  8001. }
  8002. tsParseTypeOrTypePredicateAnnotation(returnToken) {
  8003. return this.tsInType(() => {
  8004. const t = this.startNode();
  8005. this.expect(returnToken);
  8006. const node = this.startNode();
  8007. const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));
  8008. if (asserts && this.match(72)) {
  8009. let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate();
  8010. if (thisTypePredicate.type === "TSThisType") {
  8011. node.parameterName = thisTypePredicate;
  8012. node.asserts = true;
  8013. node.typeAnnotation = null;
  8014. thisTypePredicate = this.finishNode(node, "TSTypePredicate");
  8015. } else {
  8016. this.resetStartLocationFromNode(thisTypePredicate, node);
  8017. thisTypePredicate.asserts = true;
  8018. }
  8019. t.typeAnnotation = thisTypePredicate;
  8020. return this.finishNode(t, "TSTypeAnnotation");
  8021. }
  8022. const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));
  8023. if (!typePredicateVariable) {
  8024. if (!asserts) {
  8025. return this.tsParseTypeAnnotation(false, t);
  8026. }
  8027. node.parameterName = this.parseIdentifier();
  8028. node.asserts = asserts;
  8029. node.typeAnnotation = null;
  8030. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  8031. return this.finishNode(t, "TSTypeAnnotation");
  8032. }
  8033. const type = this.tsParseTypeAnnotation(false);
  8034. node.parameterName = typePredicateVariable;
  8035. node.typeAnnotation = type;
  8036. node.asserts = asserts;
  8037. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  8038. return this.finishNode(t, "TSTypeAnnotation");
  8039. });
  8040. }
  8041. tsTryParseTypeOrTypePredicateAnnotation() {
  8042. return this.match(14) ? this.tsParseTypeOrTypePredicateAnnotation(14) : undefined;
  8043. }
  8044. tsTryParseTypeAnnotation() {
  8045. return this.match(14) ? this.tsParseTypeAnnotation() : undefined;
  8046. }
  8047. tsTryParseType() {
  8048. return this.tsEatThenParseType(14);
  8049. }
  8050. tsParseTypePredicatePrefix() {
  8051. const id = this.parseIdentifier();
  8052. if (this.isContextual(107) && !this.hasPrecedingLineBreak()) {
  8053. this.next();
  8054. return id;
  8055. }
  8056. }
  8057. tsParseTypePredicateAsserts() {
  8058. if (this.state.type !== 100) {
  8059. return false;
  8060. }
  8061. const containsEsc = this.state.containsEsc;
  8062. this.next();
  8063. if (!tokenIsIdentifier(this.state.type) && !this.match(72)) {
  8064. return false;
  8065. }
  8066. if (containsEsc) {
  8067. this.raise(this.state.lastTokStart, ErrorMessages.InvalidEscapedReservedWord, "asserts");
  8068. }
  8069. return true;
  8070. }
  8071. tsParseTypeAnnotation(eatColon = true, t = this.startNode()) {
  8072. this.tsInType(() => {
  8073. if (eatColon) this.expect(14);
  8074. t.typeAnnotation = this.tsParseType();
  8075. });
  8076. return this.finishNode(t, "TSTypeAnnotation");
  8077. }
  8078. tsParseType() {
  8079. assert$1(this.state.inType);
  8080. const type = this.tsParseNonConditionalType();
  8081. if (this.hasPrecedingLineBreak() || !this.eat(75)) {
  8082. return type;
  8083. }
  8084. const node = this.startNodeAtNode(type);
  8085. node.checkType = type;
  8086. node.extendsType = this.tsParseNonConditionalType();
  8087. this.expect(17);
  8088. node.trueType = this.tsParseType();
  8089. this.expect(14);
  8090. node.falseType = this.tsParseType();
  8091. return this.finishNode(node, "TSConditionalType");
  8092. }
  8093. isAbstractConstructorSignature() {
  8094. return this.isContextual(114) && this.lookahead().type === 71;
  8095. }
  8096. tsParseNonConditionalType() {
  8097. if (this.tsIsStartOfFunctionType()) {
  8098. return this.tsParseFunctionOrConstructorType("TSFunctionType");
  8099. }
  8100. if (this.match(71)) {
  8101. return this.tsParseFunctionOrConstructorType("TSConstructorType");
  8102. } else if (this.isAbstractConstructorSignature()) {
  8103. return this.tsParseFunctionOrConstructorType("TSConstructorType", true);
  8104. }
  8105. return this.tsParseUnionTypeOrHigher();
  8106. }
  8107. tsParseTypeAssertion() {
  8108. if (this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) {
  8109. this.raise(this.state.start, TSErrors.ReservedTypeAssertion);
  8110. }
  8111. const node = this.startNode();
  8112. const _const = this.tsTryNextParseConstantContext();
  8113. node.typeAnnotation = _const || this.tsNextThenParseType();
  8114. this.expect(44);
  8115. node.expression = this.parseMaybeUnary();
  8116. return this.finishNode(node, "TSTypeAssertion");
  8117. }
  8118. tsParseHeritageClause(descriptor) {
  8119. const originalStart = this.state.start;
  8120. const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", this.tsParseExpressionWithTypeArguments.bind(this));
  8121. if (!delimitedList.length) {
  8122. this.raise(originalStart, TSErrors.EmptyHeritageClauseType, descriptor);
  8123. }
  8124. return delimitedList;
  8125. }
  8126. tsParseExpressionWithTypeArguments() {
  8127. const node = this.startNode();
  8128. node.expression = this.tsParseEntityName(false);
  8129. if (this.match(43)) {
  8130. node.typeParameters = this.tsParseTypeArguments();
  8131. }
  8132. return this.finishNode(node, "TSExpressionWithTypeArguments");
  8133. }
  8134. tsParseInterfaceDeclaration(node) {
  8135. if (tokenIsIdentifier(this.state.type)) {
  8136. node.id = this.parseIdentifier();
  8137. this.checkLVal(node.id, "typescript interface declaration", BIND_TS_INTERFACE);
  8138. } else {
  8139. node.id = null;
  8140. this.raise(this.state.start, TSErrors.MissingInterfaceName);
  8141. }
  8142. node.typeParameters = this.tsTryParseTypeParameters();
  8143. if (this.eat(75)) {
  8144. node.extends = this.tsParseHeritageClause("extends");
  8145. }
  8146. const body = this.startNode();
  8147. body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this));
  8148. node.body = this.finishNode(body, "TSInterfaceBody");
  8149. return this.finishNode(node, "TSInterfaceDeclaration");
  8150. }
  8151. tsParseTypeAliasDeclaration(node) {
  8152. node.id = this.parseIdentifier();
  8153. this.checkLVal(node.id, "typescript type alias", BIND_TS_TYPE);
  8154. node.typeParameters = this.tsTryParseTypeParameters();
  8155. node.typeAnnotation = this.tsInType(() => {
  8156. this.expect(27);
  8157. if (this.isContextual(105) && this.lookahead().type !== 16) {
  8158. const node = this.startNode();
  8159. this.next();
  8160. return this.finishNode(node, "TSIntrinsicKeyword");
  8161. }
  8162. return this.tsParseType();
  8163. });
  8164. this.semicolon();
  8165. return this.finishNode(node, "TSTypeAliasDeclaration");
  8166. }
  8167. tsInNoContext(cb) {
  8168. const oldContext = this.state.context;
  8169. this.state.context = [oldContext[0]];
  8170. try {
  8171. return cb();
  8172. } finally {
  8173. this.state.context = oldContext;
  8174. }
  8175. }
  8176. tsInType(cb) {
  8177. const oldInType = this.state.inType;
  8178. this.state.inType = true;
  8179. try {
  8180. return cb();
  8181. } finally {
  8182. this.state.inType = oldInType;
  8183. }
  8184. }
  8185. tsEatThenParseType(token) {
  8186. return !this.match(token) ? undefined : this.tsNextThenParseType();
  8187. }
  8188. tsExpectThenParseType(token) {
  8189. return this.tsDoThenParseType(() => this.expect(token));
  8190. }
  8191. tsNextThenParseType() {
  8192. return this.tsDoThenParseType(() => this.next());
  8193. }
  8194. tsDoThenParseType(cb) {
  8195. return this.tsInType(() => {
  8196. cb();
  8197. return this.tsParseType();
  8198. });
  8199. }
  8200. tsParseEnumMember() {
  8201. const node = this.startNode();
  8202. node.id = this.match(123) ? this.parseExprAtom() : this.parseIdentifier(true);
  8203. if (this.eat(27)) {
  8204. node.initializer = this.parseMaybeAssignAllowIn();
  8205. }
  8206. return this.finishNode(node, "TSEnumMember");
  8207. }
  8208. tsParseEnumDeclaration(node, isConst) {
  8209. if (isConst) node.const = true;
  8210. node.id = this.parseIdentifier();
  8211. this.checkLVal(node.id, "typescript enum declaration", isConst ? BIND_TS_CONST_ENUM : BIND_TS_ENUM);
  8212. this.expect(5);
  8213. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  8214. this.expect(8);
  8215. return this.finishNode(node, "TSEnumDeclaration");
  8216. }
  8217. tsParseModuleBlock() {
  8218. const node = this.startNode();
  8219. this.scope.enter(SCOPE_OTHER);
  8220. this.expect(5);
  8221. this.parseBlockOrModuleBlockBody(node.body = [], undefined, true, 8);
  8222. this.scope.exit();
  8223. return this.finishNode(node, "TSModuleBlock");
  8224. }
  8225. tsParseModuleOrNamespaceDeclaration(node, nested = false) {
  8226. node.id = this.parseIdentifier();
  8227. if (!nested) {
  8228. this.checkLVal(node.id, "module or namespace declaration", BIND_TS_NAMESPACE);
  8229. }
  8230. if (this.eat(16)) {
  8231. const inner = this.startNode();
  8232. this.tsParseModuleOrNamespaceDeclaration(inner, true);
  8233. node.body = inner;
  8234. } else {
  8235. this.scope.enter(SCOPE_TS_MODULE);
  8236. this.prodParam.enter(PARAM);
  8237. node.body = this.tsParseModuleBlock();
  8238. this.prodParam.exit();
  8239. this.scope.exit();
  8240. }
  8241. return this.finishNode(node, "TSModuleDeclaration");
  8242. }
  8243. tsParseAmbientExternalModuleDeclaration(node) {
  8244. if (this.isContextual(103)) {
  8245. node.global = true;
  8246. node.id = this.parseIdentifier();
  8247. } else if (this.match(123)) {
  8248. node.id = this.parseExprAtom();
  8249. } else {
  8250. this.unexpected();
  8251. }
  8252. if (this.match(5)) {
  8253. this.scope.enter(SCOPE_TS_MODULE);
  8254. this.prodParam.enter(PARAM);
  8255. node.body = this.tsParseModuleBlock();
  8256. this.prodParam.exit();
  8257. this.scope.exit();
  8258. } else {
  8259. this.semicolon();
  8260. }
  8261. return this.finishNode(node, "TSModuleDeclaration");
  8262. }
  8263. tsParseImportEqualsDeclaration(node, isExport) {
  8264. node.isExport = isExport || false;
  8265. node.id = this.parseIdentifier();
  8266. this.checkLVal(node.id, "import equals declaration", BIND_LEXICAL);
  8267. this.expect(27);
  8268. const moduleReference = this.tsParseModuleReference();
  8269. if (node.importKind === "type" && moduleReference.type !== "TSExternalModuleReference") {
  8270. this.raise(moduleReference.start, TSErrors.ImportAliasHasImportType);
  8271. }
  8272. node.moduleReference = moduleReference;
  8273. this.semicolon();
  8274. return this.finishNode(node, "TSImportEqualsDeclaration");
  8275. }
  8276. tsIsExternalModuleReference() {
  8277. return this.isContextual(110) && this.lookaheadCharCode() === 40;
  8278. }
  8279. tsParseModuleReference() {
  8280. return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false);
  8281. }
  8282. tsParseExternalModuleReference() {
  8283. const node = this.startNode();
  8284. this.expectContextual(110);
  8285. this.expect(10);
  8286. if (!this.match(123)) {
  8287. throw this.unexpected();
  8288. }
  8289. node.expression = this.parseExprAtom();
  8290. this.expect(11);
  8291. return this.finishNode(node, "TSExternalModuleReference");
  8292. }
  8293. tsLookAhead(f) {
  8294. const state = this.state.clone();
  8295. const res = f();
  8296. this.state = state;
  8297. return res;
  8298. }
  8299. tsTryParseAndCatch(f) {
  8300. const result = this.tryParse(abort => f() || abort());
  8301. if (result.aborted || !result.node) return undefined;
  8302. if (result.error) this.state = result.failState;
  8303. return result.node;
  8304. }
  8305. tsTryParse(f) {
  8306. const state = this.state.clone();
  8307. const result = f();
  8308. if (result !== undefined && result !== false) {
  8309. return result;
  8310. } else {
  8311. this.state = state;
  8312. return undefined;
  8313. }
  8314. }
  8315. tsTryParseDeclare(nany) {
  8316. if (this.isLineTerminator()) {
  8317. return;
  8318. }
  8319. let starttype = this.state.type;
  8320. let kind;
  8321. if (this.isContextual(93)) {
  8322. starttype = 68;
  8323. kind = "let";
  8324. }
  8325. return this.tsInAmbientContext(() => {
  8326. switch (starttype) {
  8327. case 62:
  8328. nany.declare = true;
  8329. return this.parseFunctionStatement(nany, false, true);
  8330. case 74:
  8331. nany.declare = true;
  8332. return this.parseClass(nany, true, false);
  8333. case 69:
  8334. if (this.match(69) && this.isLookaheadContextual("enum")) {
  8335. this.expect(69);
  8336. this.expectContextual(116);
  8337. return this.tsParseEnumDeclaration(nany, true);
  8338. }
  8339. case 68:
  8340. kind = kind || this.state.value;
  8341. return this.parseVarStatement(nany, kind);
  8342. case 103:
  8343. return this.tsParseAmbientExternalModuleDeclaration(nany);
  8344. default:
  8345. {
  8346. if (tokenIsIdentifier(starttype)) {
  8347. return this.tsParseDeclaration(nany, this.state.value, true);
  8348. }
  8349. }
  8350. }
  8351. });
  8352. }
  8353. tsTryParseExportDeclaration() {
  8354. return this.tsParseDeclaration(this.startNode(), this.state.value, true);
  8355. }
  8356. tsParseExpressionStatement(node, expr) {
  8357. switch (expr.name) {
  8358. case "declare":
  8359. {
  8360. const declaration = this.tsTryParseDeclare(node);
  8361. if (declaration) {
  8362. declaration.declare = true;
  8363. return declaration;
  8364. }
  8365. break;
  8366. }
  8367. case "global":
  8368. if (this.match(5)) {
  8369. this.scope.enter(SCOPE_TS_MODULE);
  8370. this.prodParam.enter(PARAM);
  8371. const mod = node;
  8372. mod.global = true;
  8373. mod.id = expr;
  8374. mod.body = this.tsParseModuleBlock();
  8375. this.scope.exit();
  8376. this.prodParam.exit();
  8377. return this.finishNode(mod, "TSModuleDeclaration");
  8378. }
  8379. break;
  8380. default:
  8381. return this.tsParseDeclaration(node, expr.name, false);
  8382. }
  8383. }
  8384. tsParseDeclaration(node, value, next) {
  8385. switch (value) {
  8386. case "abstract":
  8387. if (this.tsCheckLineTerminator(next) && (this.match(74) || tokenIsIdentifier(this.state.type))) {
  8388. return this.tsParseAbstractDeclaration(node);
  8389. }
  8390. break;
  8391. case "enum":
  8392. if (next || tokenIsIdentifier(this.state.type)) {
  8393. if (next) this.next();
  8394. return this.tsParseEnumDeclaration(node, false);
  8395. }
  8396. break;
  8397. case "interface":
  8398. if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
  8399. return this.tsParseInterfaceDeclaration(node);
  8400. }
  8401. break;
  8402. case "module":
  8403. if (this.tsCheckLineTerminator(next)) {
  8404. if (this.match(123)) {
  8405. return this.tsParseAmbientExternalModuleDeclaration(node);
  8406. } else if (tokenIsIdentifier(this.state.type)) {
  8407. return this.tsParseModuleOrNamespaceDeclaration(node);
  8408. }
  8409. }
  8410. break;
  8411. case "namespace":
  8412. if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
  8413. return this.tsParseModuleOrNamespaceDeclaration(node);
  8414. }
  8415. break;
  8416. case "type":
  8417. if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
  8418. return this.tsParseTypeAliasDeclaration(node);
  8419. }
  8420. break;
  8421. }
  8422. }
  8423. tsCheckLineTerminator(next) {
  8424. if (next) {
  8425. if (this.hasFollowingLineBreak()) return false;
  8426. this.next();
  8427. return true;
  8428. }
  8429. return !this.isLineTerminator();
  8430. }
  8431. tsTryParseGenericAsyncArrowFunction(startPos, startLoc) {
  8432. if (!this.match(43)) {
  8433. return undefined;
  8434. }
  8435. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8436. this.state.maybeInArrowParameters = true;
  8437. const res = this.tsTryParseAndCatch(() => {
  8438. const node = this.startNodeAt(startPos, startLoc);
  8439. node.typeParameters = this.tsParseTypeParameters();
  8440. super.parseFunctionParams(node);
  8441. node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation();
  8442. this.expect(19);
  8443. return node;
  8444. });
  8445. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8446. if (!res) {
  8447. return undefined;
  8448. }
  8449. return this.parseArrowExpression(res, null, true);
  8450. }
  8451. tsParseTypeArguments() {
  8452. const node = this.startNode();
  8453. node.params = this.tsInType(() => this.tsInNoContext(() => {
  8454. this.expect(43);
  8455. return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this));
  8456. }));
  8457. if (node.params.length === 0) {
  8458. this.raise(node.start, TSErrors.EmptyTypeArguments);
  8459. }
  8460. this.expect(44);
  8461. return this.finishNode(node, "TSTypeParameterInstantiation");
  8462. }
  8463. tsIsDeclarationStart() {
  8464. return tokenIsTSDeclarationStart(this.state.type);
  8465. }
  8466. isExportDefaultSpecifier() {
  8467. if (this.tsIsDeclarationStart()) return false;
  8468. return super.isExportDefaultSpecifier();
  8469. }
  8470. parseAssignableListItem(allowModifiers, decorators) {
  8471. const startPos = this.state.start;
  8472. const startLoc = this.state.startLoc;
  8473. let accessibility;
  8474. let readonly = false;
  8475. let override = false;
  8476. if (allowModifiers !== undefined) {
  8477. const modified = {};
  8478. this.tsParseModifiers(modified, ["public", "private", "protected", "override", "readonly"]);
  8479. accessibility = modified.accessibility;
  8480. override = modified.override;
  8481. readonly = modified.readonly;
  8482. if (allowModifiers === false && (accessibility || readonly || override)) {
  8483. this.raise(startPos, TSErrors.UnexpectedParameterModifier);
  8484. }
  8485. }
  8486. const left = this.parseMaybeDefault();
  8487. this.parseAssignableListItemTypes(left);
  8488. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  8489. if (accessibility || readonly || override) {
  8490. const pp = this.startNodeAt(startPos, startLoc);
  8491. if (decorators.length) {
  8492. pp.decorators = decorators;
  8493. }
  8494. if (accessibility) pp.accessibility = accessibility;
  8495. if (readonly) pp.readonly = readonly;
  8496. if (override) pp.override = override;
  8497. if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") {
  8498. this.raise(pp.start, TSErrors.UnsupportedParameterPropertyKind);
  8499. }
  8500. pp.parameter = elt;
  8501. return this.finishNode(pp, "TSParameterProperty");
  8502. }
  8503. if (decorators.length) {
  8504. left.decorators = decorators;
  8505. }
  8506. return elt;
  8507. }
  8508. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  8509. if (this.match(14)) {
  8510. node.returnType = this.tsParseTypeOrTypePredicateAnnotation(14);
  8511. }
  8512. const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" || type === "ClassPrivateMethod" ? "TSDeclareMethod" : undefined;
  8513. if (bodilessType && !this.match(5) && this.isLineTerminator()) {
  8514. this.finishNode(node, bodilessType);
  8515. return;
  8516. }
  8517. if (bodilessType === "TSDeclareFunction" && this.state.isAmbientContext) {
  8518. this.raise(node.start, TSErrors.DeclareFunctionHasImplementation);
  8519. if (node.declare) {
  8520. super.parseFunctionBodyAndFinish(node, bodilessType, isMethod);
  8521. return;
  8522. }
  8523. }
  8524. super.parseFunctionBodyAndFinish(node, type, isMethod);
  8525. }
  8526. registerFunctionStatementId(node) {
  8527. if (!node.body && node.id) {
  8528. this.checkLVal(node.id, "function name", BIND_TS_AMBIENT);
  8529. } else {
  8530. super.registerFunctionStatementId(...arguments);
  8531. }
  8532. }
  8533. tsCheckForInvalidTypeCasts(items) {
  8534. items.forEach(node => {
  8535. if ((node == null ? void 0 : node.type) === "TSTypeCastExpression") {
  8536. this.raise(node.typeAnnotation.start, TSErrors.UnexpectedTypeAnnotation);
  8537. }
  8538. });
  8539. }
  8540. toReferencedList(exprList, isInParens) {
  8541. this.tsCheckForInvalidTypeCasts(exprList);
  8542. return exprList;
  8543. }
  8544. parseArrayLike(...args) {
  8545. const node = super.parseArrayLike(...args);
  8546. if (node.type === "ArrayExpression") {
  8547. this.tsCheckForInvalidTypeCasts(node.elements);
  8548. }
  8549. return node;
  8550. }
  8551. parseSubscript(base, startPos, startLoc, noCalls, state) {
  8552. if (!this.hasPrecedingLineBreak() && this.match(33)) {
  8553. this.state.canStartJSXElement = false;
  8554. this.next();
  8555. const nonNullExpression = this.startNodeAt(startPos, startLoc);
  8556. nonNullExpression.expression = base;
  8557. return this.finishNode(nonNullExpression, "TSNonNullExpression");
  8558. }
  8559. let isOptionalCall = false;
  8560. if (this.match(18) && this.lookaheadCharCode() === 60) {
  8561. if (noCalls) {
  8562. state.stop = true;
  8563. return base;
  8564. }
  8565. state.optionalChainMember = isOptionalCall = true;
  8566. this.next();
  8567. }
  8568. if (this.match(43)) {
  8569. let missingParenErrorPos;
  8570. const result = this.tsTryParseAndCatch(() => {
  8571. if (!noCalls && this.atPossibleAsyncArrow(base)) {
  8572. const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startPos, startLoc);
  8573. if (asyncArrowFn) {
  8574. return asyncArrowFn;
  8575. }
  8576. }
  8577. const node = this.startNodeAt(startPos, startLoc);
  8578. node.callee = base;
  8579. const typeArguments = this.tsParseTypeArguments();
  8580. if (typeArguments) {
  8581. if (isOptionalCall && !this.match(10)) {
  8582. missingParenErrorPos = this.state.pos;
  8583. this.unexpected();
  8584. }
  8585. if (!noCalls && this.eat(10)) {
  8586. node.arguments = this.parseCallExpressionArguments(11, false);
  8587. this.tsCheckForInvalidTypeCasts(node.arguments);
  8588. node.typeParameters = typeArguments;
  8589. if (state.optionalChainMember) {
  8590. node.optional = isOptionalCall;
  8591. }
  8592. return this.finishCallExpression(node, state.optionalChainMember);
  8593. } else if (this.match(22)) {
  8594. const result = this.parseTaggedTemplateExpression(base, startPos, startLoc, state);
  8595. result.typeParameters = typeArguments;
  8596. return result;
  8597. }
  8598. }
  8599. this.unexpected();
  8600. });
  8601. if (missingParenErrorPos) {
  8602. this.unexpected(missingParenErrorPos, 10);
  8603. }
  8604. if (result) return result;
  8605. }
  8606. return super.parseSubscript(base, startPos, startLoc, noCalls, state);
  8607. }
  8608. parseNewArguments(node) {
  8609. if (this.match(43)) {
  8610. const typeParameters = this.tsTryParseAndCatch(() => {
  8611. const args = this.tsParseTypeArguments();
  8612. if (!this.match(10)) this.unexpected();
  8613. return args;
  8614. });
  8615. if (typeParameters) {
  8616. node.typeParameters = typeParameters;
  8617. }
  8618. }
  8619. super.parseNewArguments(node);
  8620. }
  8621. parseExprOp(left, leftStartPos, leftStartLoc, minPrec) {
  8622. if (tokenOperatorPrecedence(52) > minPrec && !this.hasPrecedingLineBreak() && this.isContextual(87)) {
  8623. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  8624. node.expression = left;
  8625. const _const = this.tsTryNextParseConstantContext();
  8626. if (_const) {
  8627. node.typeAnnotation = _const;
  8628. } else {
  8629. node.typeAnnotation = this.tsNextThenParseType();
  8630. }
  8631. this.finishNode(node, "TSAsExpression");
  8632. this.reScan_lt_gt();
  8633. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec);
  8634. }
  8635. return super.parseExprOp(left, leftStartPos, leftStartLoc, minPrec);
  8636. }
  8637. checkReservedWord(word, startLoc, checkKeywords, isBinding) {}
  8638. checkDuplicateExports() {}
  8639. parseImport(node) {
  8640. node.importKind = "value";
  8641. if (tokenIsIdentifier(this.state.type) || this.match(49) || this.match(5)) {
  8642. let ahead = this.lookahead();
  8643. if (this.isContextual(120) && ahead.type !== 12 && ahead.type !== 91 && ahead.type !== 27) {
  8644. node.importKind = "type";
  8645. this.next();
  8646. ahead = this.lookahead();
  8647. }
  8648. if (tokenIsIdentifier(this.state.type) && ahead.type === 27) {
  8649. return this.tsParseImportEqualsDeclaration(node);
  8650. }
  8651. }
  8652. const importNode = super.parseImport(node);
  8653. if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") {
  8654. this.raise(importNode.start, TSErrors.TypeImportCannotSpecifyDefaultAndNamed);
  8655. }
  8656. return importNode;
  8657. }
  8658. parseExport(node) {
  8659. if (this.match(77)) {
  8660. this.next();
  8661. if (this.isContextual(120) && this.lookaheadCharCode() !== 61) {
  8662. node.importKind = "type";
  8663. this.next();
  8664. } else {
  8665. node.importKind = "value";
  8666. }
  8667. return this.tsParseImportEqualsDeclaration(node, true);
  8668. } else if (this.eat(27)) {
  8669. const assign = node;
  8670. assign.expression = this.parseExpression();
  8671. this.semicolon();
  8672. return this.finishNode(assign, "TSExportAssignment");
  8673. } else if (this.eatContextual(87)) {
  8674. const decl = node;
  8675. this.expectContextual(118);
  8676. decl.id = this.parseIdentifier();
  8677. this.semicolon();
  8678. return this.finishNode(decl, "TSNamespaceExportDeclaration");
  8679. } else {
  8680. if (this.isContextual(120) && this.lookahead().type === 5) {
  8681. this.next();
  8682. node.exportKind = "type";
  8683. } else {
  8684. node.exportKind = "value";
  8685. }
  8686. return super.parseExport(node);
  8687. }
  8688. }
  8689. isAbstractClass() {
  8690. return this.isContextual(114) && this.lookahead().type === 74;
  8691. }
  8692. parseExportDefaultExpression() {
  8693. if (this.isAbstractClass()) {
  8694. const cls = this.startNode();
  8695. this.next();
  8696. cls.abstract = true;
  8697. this.parseClass(cls, true, true);
  8698. return cls;
  8699. }
  8700. if (this.match(119)) {
  8701. const interfaceNode = this.startNode();
  8702. this.next();
  8703. const result = this.tsParseInterfaceDeclaration(interfaceNode);
  8704. if (result) return result;
  8705. }
  8706. return super.parseExportDefaultExpression();
  8707. }
  8708. parseStatementContent(context, topLevel) {
  8709. if (this.state.type === 69) {
  8710. const ahead = this.lookahead();
  8711. if (ahead.type === 116) {
  8712. const node = this.startNode();
  8713. this.next();
  8714. this.expectContextual(116);
  8715. return this.tsParseEnumDeclaration(node, true);
  8716. }
  8717. }
  8718. return super.parseStatementContent(context, topLevel);
  8719. }
  8720. parseAccessModifier() {
  8721. return this.tsParseModifier(["public", "protected", "private"]);
  8722. }
  8723. tsHasSomeModifiers(member, modifiers) {
  8724. return modifiers.some(modifier => {
  8725. if (tsIsAccessModifier(modifier)) {
  8726. return member.accessibility === modifier;
  8727. }
  8728. return !!member[modifier];
  8729. });
  8730. }
  8731. tsIsStartOfStaticBlocks() {
  8732. return this.isContextual(98) && this.lookaheadCharCode() === 123;
  8733. }
  8734. parseClassMember(classBody, member, state) {
  8735. const modifiers = ["declare", "private", "public", "protected", "override", "abstract", "readonly", "static"];
  8736. this.tsParseModifiers(member, modifiers, undefined, undefined, true);
  8737. const callParseClassMemberWithIsStatic = () => {
  8738. if (this.tsIsStartOfStaticBlocks()) {
  8739. this.next();
  8740. this.next();
  8741. if (this.tsHasSomeModifiers(member, modifiers)) {
  8742. this.raise(this.state.pos, TSErrors.StaticBlockCannotHaveModifier);
  8743. }
  8744. this.parseClassStaticBlock(classBody, member);
  8745. } else {
  8746. this.parseClassMemberWithIsStatic(classBody, member, state, !!member.static);
  8747. }
  8748. };
  8749. if (member.declare) {
  8750. this.tsInAmbientContext(callParseClassMemberWithIsStatic);
  8751. } else {
  8752. callParseClassMemberWithIsStatic();
  8753. }
  8754. }
  8755. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  8756. const idx = this.tsTryParseIndexSignature(member);
  8757. if (idx) {
  8758. classBody.body.push(idx);
  8759. if (member.abstract) {
  8760. this.raise(member.start, TSErrors.IndexSignatureHasAbstract);
  8761. }
  8762. if (member.accessibility) {
  8763. this.raise(member.start, TSErrors.IndexSignatureHasAccessibility, member.accessibility);
  8764. }
  8765. if (member.declare) {
  8766. this.raise(member.start, TSErrors.IndexSignatureHasDeclare);
  8767. }
  8768. if (member.override) {
  8769. this.raise(member.start, TSErrors.IndexSignatureHasOverride);
  8770. }
  8771. return;
  8772. }
  8773. if (!this.state.inAbstractClass && member.abstract) {
  8774. this.raise(member.start, TSErrors.NonAbstractClassHasAbstractMethod);
  8775. }
  8776. if (member.override) {
  8777. if (!state.hadSuperClass) {
  8778. this.raise(member.start, TSErrors.OverrideNotInSubClass);
  8779. }
  8780. }
  8781. super.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  8782. }
  8783. parsePostMemberNameModifiers(methodOrProp) {
  8784. const optional = this.eat(17);
  8785. if (optional) methodOrProp.optional = true;
  8786. if (methodOrProp.readonly && this.match(10)) {
  8787. this.raise(methodOrProp.start, TSErrors.ClassMethodHasReadonly);
  8788. }
  8789. if (methodOrProp.declare && this.match(10)) {
  8790. this.raise(methodOrProp.start, TSErrors.ClassMethodHasDeclare);
  8791. }
  8792. }
  8793. parseExpressionStatement(node, expr) {
  8794. const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr) : undefined;
  8795. return decl || super.parseExpressionStatement(node, expr);
  8796. }
  8797. shouldParseExportDeclaration() {
  8798. if (this.tsIsDeclarationStart()) return true;
  8799. return super.shouldParseExportDeclaration();
  8800. }
  8801. parseConditional(expr, startPos, startLoc, refExpressionErrors) {
  8802. if (!this.state.maybeInArrowParameters || !this.match(17)) {
  8803. return super.parseConditional(expr, startPos, startLoc, refExpressionErrors);
  8804. }
  8805. const result = this.tryParse(() => super.parseConditional(expr, startPos, startLoc));
  8806. if (!result.node) {
  8807. if (result.error) {
  8808. super.setOptionalParametersError(refExpressionErrors, result.error);
  8809. }
  8810. return expr;
  8811. }
  8812. if (result.error) this.state = result.failState;
  8813. return result.node;
  8814. }
  8815. parseParenItem(node, startPos, startLoc) {
  8816. node = super.parseParenItem(node, startPos, startLoc);
  8817. if (this.eat(17)) {
  8818. node.optional = true;
  8819. this.resetEndLocation(node);
  8820. }
  8821. if (this.match(14)) {
  8822. const typeCastNode = this.startNodeAt(startPos, startLoc);
  8823. typeCastNode.expression = node;
  8824. typeCastNode.typeAnnotation = this.tsParseTypeAnnotation();
  8825. return this.finishNode(typeCastNode, "TSTypeCastExpression");
  8826. }
  8827. return node;
  8828. }
  8829. parseExportDeclaration(node) {
  8830. const startPos = this.state.start;
  8831. const startLoc = this.state.startLoc;
  8832. const isDeclare = this.eatContextual(115);
  8833. if (isDeclare && (this.isContextual(115) || !this.shouldParseExportDeclaration())) {
  8834. throw this.raise(this.state.start, TSErrors.ExpectedAmbientAfterExportDeclare);
  8835. }
  8836. let declaration;
  8837. if (tokenIsIdentifier(this.state.type)) {
  8838. declaration = this.tsTryParseExportDeclaration();
  8839. }
  8840. if (!declaration) {
  8841. declaration = super.parseExportDeclaration(node);
  8842. }
  8843. if (declaration && (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare)) {
  8844. node.exportKind = "type";
  8845. }
  8846. if (declaration && isDeclare) {
  8847. this.resetStartLocation(declaration, startPos, startLoc);
  8848. declaration.declare = true;
  8849. }
  8850. return declaration;
  8851. }
  8852. parseClassId(node, isStatement, optionalId) {
  8853. if ((!isStatement || optionalId) && this.isContextual(104)) {
  8854. return;
  8855. }
  8856. super.parseClassId(node, isStatement, optionalId, node.declare ? BIND_TS_AMBIENT : BIND_CLASS);
  8857. const typeParameters = this.tsTryParseTypeParameters();
  8858. if (typeParameters) node.typeParameters = typeParameters;
  8859. }
  8860. parseClassPropertyAnnotation(node) {
  8861. if (!node.optional && this.eat(33)) {
  8862. node.definite = true;
  8863. }
  8864. const type = this.tsTryParseTypeAnnotation();
  8865. if (type) node.typeAnnotation = type;
  8866. }
  8867. parseClassProperty(node) {
  8868. this.parseClassPropertyAnnotation(node);
  8869. if (this.state.isAmbientContext && this.match(27)) {
  8870. this.raise(this.state.start, TSErrors.DeclareClassFieldHasInitializer);
  8871. }
  8872. if (node.abstract && this.match(27)) {
  8873. const {
  8874. key
  8875. } = node;
  8876. this.raise(this.state.start, TSErrors.AbstractPropertyHasInitializer, key.type === "Identifier" && !node.computed ? key.name : `[${this.input.slice(key.start, key.end)}]`);
  8877. }
  8878. return super.parseClassProperty(node);
  8879. }
  8880. parseClassPrivateProperty(node) {
  8881. if (node.abstract) {
  8882. this.raise(node.start, TSErrors.PrivateElementHasAbstract);
  8883. }
  8884. if (node.accessibility) {
  8885. this.raise(node.start, TSErrors.PrivateElementHasAccessibility, node.accessibility);
  8886. }
  8887. this.parseClassPropertyAnnotation(node);
  8888. return super.parseClassPrivateProperty(node);
  8889. }
  8890. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  8891. const typeParameters = this.tsTryParseTypeParameters();
  8892. if (typeParameters && isConstructor) {
  8893. this.raise(typeParameters.start, TSErrors.ConstructorHasTypeParameters);
  8894. }
  8895. if (method.declare && (method.kind === "get" || method.kind === "set")) {
  8896. this.raise(method.start, TSErrors.DeclareAccessor, method.kind);
  8897. }
  8898. if (typeParameters) method.typeParameters = typeParameters;
  8899. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  8900. }
  8901. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  8902. const typeParameters = this.tsTryParseTypeParameters();
  8903. if (typeParameters) method.typeParameters = typeParameters;
  8904. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  8905. }
  8906. declareClassPrivateMethodInScope(node, kind) {
  8907. if (node.type === "TSDeclareMethod") return;
  8908. if (node.type === "MethodDefinition" && !node.value.body) return;
  8909. super.declareClassPrivateMethodInScope(node, kind);
  8910. }
  8911. parseClassSuper(node) {
  8912. super.parseClassSuper(node);
  8913. if (node.superClass && this.match(43)) {
  8914. node.superTypeParameters = this.tsParseTypeArguments();
  8915. }
  8916. if (this.eatContextual(104)) {
  8917. node.implements = this.tsParseHeritageClause("implements");
  8918. }
  8919. }
  8920. parseObjPropValue(prop, ...args) {
  8921. const typeParameters = this.tsTryParseTypeParameters();
  8922. if (typeParameters) prop.typeParameters = typeParameters;
  8923. super.parseObjPropValue(prop, ...args);
  8924. }
  8925. parseFunctionParams(node, allowModifiers) {
  8926. const typeParameters = this.tsTryParseTypeParameters();
  8927. if (typeParameters) node.typeParameters = typeParameters;
  8928. super.parseFunctionParams(node, allowModifiers);
  8929. }
  8930. parseVarId(decl, kind) {
  8931. super.parseVarId(decl, kind);
  8932. if (decl.id.type === "Identifier" && this.eat(33)) {
  8933. decl.definite = true;
  8934. }
  8935. const type = this.tsTryParseTypeAnnotation();
  8936. if (type) {
  8937. decl.id.typeAnnotation = type;
  8938. this.resetEndLocation(decl.id);
  8939. }
  8940. }
  8941. parseAsyncArrowFromCallExpression(node, call) {
  8942. if (this.match(14)) {
  8943. node.returnType = this.tsParseTypeAnnotation();
  8944. }
  8945. return super.parseAsyncArrowFromCallExpression(node, call);
  8946. }
  8947. parseMaybeAssign(...args) {
  8948. var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2, _jsx4, _typeCast3;
  8949. let state;
  8950. let jsx;
  8951. let typeCast;
  8952. if (this.hasPlugin("jsx") && (this.match(132) || this.match(43))) {
  8953. state = this.state.clone();
  8954. jsx = this.tryParse(() => super.parseMaybeAssign(...args), state);
  8955. if (!jsx.error) return jsx.node;
  8956. const {
  8957. context
  8958. } = this.state;
  8959. if (context[context.length - 1] === types$1.j_oTag) {
  8960. context.length -= 2;
  8961. } else if (context[context.length - 1] === types$1.j_expr) {
  8962. context.length -= 1;
  8963. }
  8964. }
  8965. if (!((_jsx = jsx) != null && _jsx.error) && !this.match(43)) {
  8966. return super.parseMaybeAssign(...args);
  8967. }
  8968. let typeParameters;
  8969. state = state || this.state.clone();
  8970. const arrow = this.tryParse(abort => {
  8971. var _expr$extra, _typeParameters;
  8972. typeParameters = this.tsParseTypeParameters();
  8973. const expr = super.parseMaybeAssign(...args);
  8974. if (expr.type !== "ArrowFunctionExpression" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) {
  8975. abort();
  8976. }
  8977. if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) {
  8978. this.resetStartLocationFromNode(expr, typeParameters);
  8979. }
  8980. expr.typeParameters = typeParameters;
  8981. return expr;
  8982. }, state);
  8983. if (!arrow.error && !arrow.aborted) {
  8984. if (typeParameters) this.reportReservedArrowTypeParam(typeParameters);
  8985. return arrow.node;
  8986. }
  8987. if (!jsx) {
  8988. assert$1(!this.hasPlugin("jsx"));
  8989. typeCast = this.tryParse(() => super.parseMaybeAssign(...args), state);
  8990. if (!typeCast.error) return typeCast.node;
  8991. }
  8992. if ((_jsx2 = jsx) != null && _jsx2.node) {
  8993. this.state = jsx.failState;
  8994. return jsx.node;
  8995. }
  8996. if (arrow.node) {
  8997. this.state = arrow.failState;
  8998. if (typeParameters) this.reportReservedArrowTypeParam(typeParameters);
  8999. return arrow.node;
  9000. }
  9001. if ((_typeCast = typeCast) != null && _typeCast.node) {
  9002. this.state = typeCast.failState;
  9003. return typeCast.node;
  9004. }
  9005. if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error;
  9006. if (arrow.thrown) throw arrow.error;
  9007. if ((_typeCast2 = typeCast) != null && _typeCast2.thrown) throw typeCast.error;
  9008. throw ((_jsx4 = jsx) == null ? void 0 : _jsx4.error) || arrow.error || ((_typeCast3 = typeCast) == null ? void 0 : _typeCast3.error);
  9009. }
  9010. reportReservedArrowTypeParam(node) {
  9011. var _node$extra;
  9012. if (node.params.length === 1 && !((_node$extra = node.extra) != null && _node$extra.trailingComma) && this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) {
  9013. this.raise(node.start, TSErrors.ReservedArrowTypeParam);
  9014. }
  9015. }
  9016. parseMaybeUnary(refExpressionErrors) {
  9017. if (!this.hasPlugin("jsx") && this.match(43)) {
  9018. return this.tsParseTypeAssertion();
  9019. } else {
  9020. return super.parseMaybeUnary(refExpressionErrors);
  9021. }
  9022. }
  9023. parseArrow(node) {
  9024. if (this.match(14)) {
  9025. const result = this.tryParse(abort => {
  9026. const returnType = this.tsParseTypeOrTypePredicateAnnotation(14);
  9027. if (this.canInsertSemicolon() || !this.match(19)) abort();
  9028. return returnType;
  9029. });
  9030. if (result.aborted) return;
  9031. if (!result.thrown) {
  9032. if (result.error) this.state = result.failState;
  9033. node.returnType = result.node;
  9034. }
  9035. }
  9036. return super.parseArrow(node);
  9037. }
  9038. parseAssignableListItemTypes(param) {
  9039. if (this.eat(17)) {
  9040. if (param.type !== "Identifier" && !this.state.isAmbientContext && !this.state.inType) {
  9041. this.raise(param.start, TSErrors.PatternIsOptional);
  9042. }
  9043. param.optional = true;
  9044. }
  9045. const type = this.tsTryParseTypeAnnotation();
  9046. if (type) param.typeAnnotation = type;
  9047. this.resetEndLocation(param);
  9048. return param;
  9049. }
  9050. isAssignable(node, isBinding) {
  9051. switch (node.type) {
  9052. case "TSTypeCastExpression":
  9053. return this.isAssignable(node.expression, isBinding);
  9054. case "TSParameterProperty":
  9055. return true;
  9056. default:
  9057. return super.isAssignable(node, isBinding);
  9058. }
  9059. }
  9060. toAssignable(node, isLHS = false) {
  9061. switch (node.type) {
  9062. case "TSTypeCastExpression":
  9063. return super.toAssignable(this.typeCastToParameter(node), isLHS);
  9064. case "TSParameterProperty":
  9065. return super.toAssignable(node, isLHS);
  9066. case "ParenthesizedExpression":
  9067. return this.toAssignableParenthesizedExpression(node, isLHS);
  9068. case "TSAsExpression":
  9069. case "TSNonNullExpression":
  9070. case "TSTypeAssertion":
  9071. node.expression = this.toAssignable(node.expression, isLHS);
  9072. return node;
  9073. default:
  9074. return super.toAssignable(node, isLHS);
  9075. }
  9076. }
  9077. toAssignableParenthesizedExpression(node, isLHS) {
  9078. switch (node.expression.type) {
  9079. case "TSAsExpression":
  9080. case "TSNonNullExpression":
  9081. case "TSTypeAssertion":
  9082. case "ParenthesizedExpression":
  9083. node.expression = this.toAssignable(node.expression, isLHS);
  9084. return node;
  9085. default:
  9086. return super.toAssignable(node, isLHS);
  9087. }
  9088. }
  9089. checkLVal(expr, contextDescription, ...args) {
  9090. var _expr$extra2;
  9091. switch (expr.type) {
  9092. case "TSTypeCastExpression":
  9093. return;
  9094. case "TSParameterProperty":
  9095. this.checkLVal(expr.parameter, "parameter property", ...args);
  9096. return;
  9097. case "TSAsExpression":
  9098. case "TSTypeAssertion":
  9099. if (!args[0] && contextDescription !== "parenthesized expression" && !((_expr$extra2 = expr.extra) != null && _expr$extra2.parenthesized)) {
  9100. this.raise(expr.start, ErrorMessages.InvalidLhs, contextDescription);
  9101. break;
  9102. }
  9103. this.checkLVal(expr.expression, "parenthesized expression", ...args);
  9104. return;
  9105. case "TSNonNullExpression":
  9106. this.checkLVal(expr.expression, contextDescription, ...args);
  9107. return;
  9108. default:
  9109. super.checkLVal(expr, contextDescription, ...args);
  9110. return;
  9111. }
  9112. }
  9113. parseBindingAtom() {
  9114. switch (this.state.type) {
  9115. case 72:
  9116. return this.parseIdentifier(true);
  9117. default:
  9118. return super.parseBindingAtom();
  9119. }
  9120. }
  9121. parseMaybeDecoratorArguments(expr) {
  9122. if (this.match(43)) {
  9123. const typeArguments = this.tsParseTypeArguments();
  9124. if (this.match(10)) {
  9125. const call = super.parseMaybeDecoratorArguments(expr);
  9126. call.typeParameters = typeArguments;
  9127. return call;
  9128. }
  9129. this.unexpected(this.state.start, 10);
  9130. }
  9131. return super.parseMaybeDecoratorArguments(expr);
  9132. }
  9133. checkCommaAfterRest(close) {
  9134. if (this.state.isAmbientContext && this.match(12) && this.lookaheadCharCode() === close) {
  9135. this.next();
  9136. } else {
  9137. super.checkCommaAfterRest(close);
  9138. }
  9139. }
  9140. isClassMethod() {
  9141. return this.match(43) || super.isClassMethod();
  9142. }
  9143. isClassProperty() {
  9144. return this.match(33) || this.match(14) || super.isClassProperty();
  9145. }
  9146. parseMaybeDefault(...args) {
  9147. const node = super.parseMaybeDefault(...args);
  9148. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  9149. this.raise(node.typeAnnotation.start, TSErrors.TypeAnnotationAfterAssign);
  9150. }
  9151. return node;
  9152. }
  9153. getTokenFromCode(code) {
  9154. if (this.state.inType) {
  9155. if (code === 62) {
  9156. return this.finishOp(44, 1);
  9157. }
  9158. if (code === 60) {
  9159. return this.finishOp(43, 1);
  9160. }
  9161. }
  9162. return super.getTokenFromCode(code);
  9163. }
  9164. reScan_lt_gt() {
  9165. const {
  9166. type
  9167. } = this.state;
  9168. if (type === 43) {
  9169. this.state.pos -= 1;
  9170. this.readToken_lt();
  9171. } else if (type === 44) {
  9172. this.state.pos -= 1;
  9173. this.readToken_gt();
  9174. }
  9175. }
  9176. toAssignableList(exprList) {
  9177. for (let i = 0; i < exprList.length; i++) {
  9178. const expr = exprList[i];
  9179. if (!expr) continue;
  9180. switch (expr.type) {
  9181. case "TSTypeCastExpression":
  9182. exprList[i] = this.typeCastToParameter(expr);
  9183. break;
  9184. case "TSAsExpression":
  9185. case "TSTypeAssertion":
  9186. if (!this.state.maybeInArrowParameters) {
  9187. exprList[i] = this.typeCastToParameter(expr);
  9188. } else {
  9189. this.raise(expr.start, TSErrors.UnexpectedTypeCastInParameter);
  9190. }
  9191. break;
  9192. }
  9193. }
  9194. return super.toAssignableList(...arguments);
  9195. }
  9196. typeCastToParameter(node) {
  9197. node.expression.typeAnnotation = node.typeAnnotation;
  9198. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  9199. return node.expression;
  9200. }
  9201. shouldParseArrow(params) {
  9202. if (this.match(14)) {
  9203. return params.every(expr => this.isAssignable(expr, true));
  9204. }
  9205. return super.shouldParseArrow(params);
  9206. }
  9207. shouldParseAsyncArrow() {
  9208. return this.match(14) || super.shouldParseAsyncArrow();
  9209. }
  9210. canHaveLeadingDecorator() {
  9211. return super.canHaveLeadingDecorator() || this.isAbstractClass();
  9212. }
  9213. jsxParseOpeningElementAfterName(node) {
  9214. if (this.match(43)) {
  9215. const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArguments());
  9216. if (typeArguments) node.typeParameters = typeArguments;
  9217. }
  9218. return super.jsxParseOpeningElementAfterName(node);
  9219. }
  9220. getGetterSetterExpectedParamCount(method) {
  9221. const baseCount = super.getGetterSetterExpectedParamCount(method);
  9222. const params = this.getObjectOrClassMethodParams(method);
  9223. const firstParam = params[0];
  9224. const hasContextParam = firstParam && this.isThisParam(firstParam);
  9225. return hasContextParam ? baseCount + 1 : baseCount;
  9226. }
  9227. parseCatchClauseParam() {
  9228. const param = super.parseCatchClauseParam();
  9229. const type = this.tsTryParseTypeAnnotation();
  9230. if (type) {
  9231. param.typeAnnotation = type;
  9232. this.resetEndLocation(param);
  9233. }
  9234. return param;
  9235. }
  9236. tsInAmbientContext(cb) {
  9237. const oldIsAmbientContext = this.state.isAmbientContext;
  9238. this.state.isAmbientContext = true;
  9239. try {
  9240. return cb();
  9241. } finally {
  9242. this.state.isAmbientContext = oldIsAmbientContext;
  9243. }
  9244. }
  9245. parseClass(node, ...args) {
  9246. const oldInAbstractClass = this.state.inAbstractClass;
  9247. this.state.inAbstractClass = !!node.abstract;
  9248. try {
  9249. return super.parseClass(node, ...args);
  9250. } finally {
  9251. this.state.inAbstractClass = oldInAbstractClass;
  9252. }
  9253. }
  9254. tsParseAbstractDeclaration(node) {
  9255. if (this.match(74)) {
  9256. node.abstract = true;
  9257. return this.parseClass(node, true, false);
  9258. } else if (this.isContextual(119)) {
  9259. if (!this.hasFollowingLineBreak()) {
  9260. node.abstract = true;
  9261. this.raise(node.start, TSErrors.NonClassMethodPropertyHasAbstractModifer);
  9262. this.next();
  9263. return this.tsParseInterfaceDeclaration(node);
  9264. }
  9265. } else {
  9266. this.unexpected(null, 74);
  9267. }
  9268. }
  9269. parseMethod(...args) {
  9270. const method = super.parseMethod(...args);
  9271. if (method.abstract) {
  9272. const hasBody = this.hasPlugin("estree") ? !!method.value.body : !!method.body;
  9273. if (hasBody) {
  9274. const {
  9275. key
  9276. } = method;
  9277. this.raise(method.start, TSErrors.AbstractMethodHasImplementation, key.type === "Identifier" && !method.computed ? key.name : `[${this.input.slice(key.start, key.end)}]`);
  9278. }
  9279. }
  9280. return method;
  9281. }
  9282. tsParseTypeParameterName() {
  9283. const typeName = this.parseIdentifier();
  9284. return typeName.name;
  9285. }
  9286. shouldParseAsAmbientContext() {
  9287. return !!this.getPluginOption("typescript", "dts");
  9288. }
  9289. parse() {
  9290. if (this.shouldParseAsAmbientContext()) {
  9291. this.state.isAmbientContext = true;
  9292. }
  9293. return super.parse();
  9294. }
  9295. getExpression() {
  9296. if (this.shouldParseAsAmbientContext()) {
  9297. this.state.isAmbientContext = true;
  9298. }
  9299. return super.getExpression();
  9300. }
  9301. parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) {
  9302. if (!isString && isMaybeTypeOnly) {
  9303. this.parseTypeOnlyImportExportSpecifier(node, false, isInTypeExport);
  9304. return this.finishNode(node, "ExportSpecifier");
  9305. }
  9306. node.exportKind = "value";
  9307. return super.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly);
  9308. }
  9309. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly) {
  9310. if (!importedIsString && isMaybeTypeOnly) {
  9311. this.parseTypeOnlyImportExportSpecifier(specifier, true, isInTypeOnlyImport);
  9312. return this.finishNode(specifier, "ImportSpecifier");
  9313. }
  9314. specifier.importKind = "value";
  9315. return super.parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly);
  9316. }
  9317. parseTypeOnlyImportExportSpecifier(node, isImport, isInTypeOnlyImportExport) {
  9318. const leftOfAsKey = isImport ? "imported" : "local";
  9319. const rightOfAsKey = isImport ? "local" : "exported";
  9320. let leftOfAs = node[leftOfAsKey];
  9321. let rightOfAs;
  9322. let hasTypeSpecifier = false;
  9323. let canParseAsKeyword = true;
  9324. const pos = leftOfAs.start;
  9325. if (this.isContextual(87)) {
  9326. const firstAs = this.parseIdentifier();
  9327. if (this.isContextual(87)) {
  9328. const secondAs = this.parseIdentifier();
  9329. if (tokenIsKeywordOrIdentifier(this.state.type)) {
  9330. hasTypeSpecifier = true;
  9331. leftOfAs = firstAs;
  9332. rightOfAs = this.parseIdentifier();
  9333. canParseAsKeyword = false;
  9334. } else {
  9335. rightOfAs = secondAs;
  9336. canParseAsKeyword = false;
  9337. }
  9338. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  9339. canParseAsKeyword = false;
  9340. rightOfAs = this.parseIdentifier();
  9341. } else {
  9342. hasTypeSpecifier = true;
  9343. leftOfAs = firstAs;
  9344. }
  9345. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  9346. hasTypeSpecifier = true;
  9347. leftOfAs = this.parseIdentifier();
  9348. }
  9349. if (hasTypeSpecifier && isInTypeOnlyImportExport) {
  9350. this.raise(pos, isImport ? TSErrors.TypeModifierIsUsedInTypeImports : TSErrors.TypeModifierIsUsedInTypeExports);
  9351. }
  9352. node[leftOfAsKey] = leftOfAs;
  9353. node[rightOfAsKey] = rightOfAs;
  9354. const kindKey = isImport ? "importKind" : "exportKind";
  9355. node[kindKey] = hasTypeSpecifier ? "type" : "value";
  9356. if (canParseAsKeyword && this.eatContextual(87)) {
  9357. node[rightOfAsKey] = isImport ? this.parseIdentifier() : this.parseModuleExportName();
  9358. }
  9359. if (!node[rightOfAsKey]) {
  9360. node[rightOfAsKey] = cloneIdentifier(node[leftOfAsKey]);
  9361. }
  9362. if (isImport) {
  9363. this.checkLVal(node[rightOfAsKey], "import specifier", BIND_LEXICAL);
  9364. }
  9365. }
  9366. });
  9367. const PlaceHolderErrors = makeErrorTemplates({
  9368. ClassNameIsRequired: "A class name is required."
  9369. }, ErrorCodes.SyntaxError);
  9370. var placeholders = (superClass => class extends superClass {
  9371. parsePlaceholder(expectedNode) {
  9372. if (this.match(134)) {
  9373. const node = this.startNode();
  9374. this.next();
  9375. this.assertNoSpace("Unexpected space in placeholder.");
  9376. node.name = super.parseIdentifier(true);
  9377. this.assertNoSpace("Unexpected space in placeholder.");
  9378. this.expect(134);
  9379. return this.finishPlaceholder(node, expectedNode);
  9380. }
  9381. }
  9382. finishPlaceholder(node, expectedNode) {
  9383. const isFinished = !!(node.expectedNode && node.type === "Placeholder");
  9384. node.expectedNode = expectedNode;
  9385. return isFinished ? node : this.finishNode(node, "Placeholder");
  9386. }
  9387. getTokenFromCode(code) {
  9388. if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) {
  9389. return this.finishOp(134, 2);
  9390. }
  9391. return super.getTokenFromCode(...arguments);
  9392. }
  9393. parseExprAtom() {
  9394. return this.parsePlaceholder("Expression") || super.parseExprAtom(...arguments);
  9395. }
  9396. parseIdentifier() {
  9397. return this.parsePlaceholder("Identifier") || super.parseIdentifier(...arguments);
  9398. }
  9399. checkReservedWord(word) {
  9400. if (word !== undefined) super.checkReservedWord(...arguments);
  9401. }
  9402. parseBindingAtom() {
  9403. return this.parsePlaceholder("Pattern") || super.parseBindingAtom(...arguments);
  9404. }
  9405. checkLVal(expr) {
  9406. if (expr.type !== "Placeholder") super.checkLVal(...arguments);
  9407. }
  9408. toAssignable(node) {
  9409. if (node && node.type === "Placeholder" && node.expectedNode === "Expression") {
  9410. node.expectedNode = "Pattern";
  9411. return node;
  9412. }
  9413. return super.toAssignable(...arguments);
  9414. }
  9415. isLet(context) {
  9416. if (super.isLet(context)) {
  9417. return true;
  9418. }
  9419. if (!this.isContextual(93)) {
  9420. return false;
  9421. }
  9422. if (context) return false;
  9423. const nextToken = this.lookahead();
  9424. if (nextToken.type === 134) {
  9425. return true;
  9426. }
  9427. return false;
  9428. }
  9429. verifyBreakContinue(node) {
  9430. if (node.label && node.label.type === "Placeholder") return;
  9431. super.verifyBreakContinue(...arguments);
  9432. }
  9433. parseExpressionStatement(node, expr) {
  9434. if (expr.type !== "Placeholder" || expr.extra && expr.extra.parenthesized) {
  9435. return super.parseExpressionStatement(...arguments);
  9436. }
  9437. if (this.match(14)) {
  9438. const stmt = node;
  9439. stmt.label = this.finishPlaceholder(expr, "Identifier");
  9440. this.next();
  9441. stmt.body = this.parseStatement("label");
  9442. return this.finishNode(stmt, "LabeledStatement");
  9443. }
  9444. this.semicolon();
  9445. node.name = expr.name;
  9446. return this.finishPlaceholder(node, "Statement");
  9447. }
  9448. parseBlock() {
  9449. return this.parsePlaceholder("BlockStatement") || super.parseBlock(...arguments);
  9450. }
  9451. parseFunctionId() {
  9452. return this.parsePlaceholder("Identifier") || super.parseFunctionId(...arguments);
  9453. }
  9454. parseClass(node, isStatement, optionalId) {
  9455. const type = isStatement ? "ClassDeclaration" : "ClassExpression";
  9456. this.next();
  9457. this.takeDecorators(node);
  9458. const oldStrict = this.state.strict;
  9459. const placeholder = this.parsePlaceholder("Identifier");
  9460. if (placeholder) {
  9461. if (this.match(75) || this.match(134) || this.match(5)) {
  9462. node.id = placeholder;
  9463. } else if (optionalId || !isStatement) {
  9464. node.id = null;
  9465. node.body = this.finishPlaceholder(placeholder, "ClassBody");
  9466. return this.finishNode(node, type);
  9467. } else {
  9468. this.unexpected(null, PlaceHolderErrors.ClassNameIsRequired);
  9469. }
  9470. } else {
  9471. this.parseClassId(node, isStatement, optionalId);
  9472. }
  9473. this.parseClassSuper(node);
  9474. node.body = this.parsePlaceholder("ClassBody") || this.parseClassBody(!!node.superClass, oldStrict);
  9475. return this.finishNode(node, type);
  9476. }
  9477. parseExport(node) {
  9478. const placeholder = this.parsePlaceholder("Identifier");
  9479. if (!placeholder) return super.parseExport(...arguments);
  9480. if (!this.isContextual(91) && !this.match(12)) {
  9481. node.specifiers = [];
  9482. node.source = null;
  9483. node.declaration = this.finishPlaceholder(placeholder, "Declaration");
  9484. return this.finishNode(node, "ExportNamedDeclaration");
  9485. }
  9486. this.expectPlugin("exportDefaultFrom");
  9487. const specifier = this.startNode();
  9488. specifier.exported = placeholder;
  9489. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  9490. return super.parseExport(node);
  9491. }
  9492. isExportDefaultSpecifier() {
  9493. if (this.match(59)) {
  9494. const next = this.nextTokenStart();
  9495. if (this.isUnparsedContextual(next, "from")) {
  9496. if (this.input.startsWith(tokenLabelName(134), this.nextTokenStartSince(next + 4))) {
  9497. return true;
  9498. }
  9499. }
  9500. }
  9501. return super.isExportDefaultSpecifier();
  9502. }
  9503. maybeParseExportDefaultSpecifier(node) {
  9504. if (node.specifiers && node.specifiers.length > 0) {
  9505. return true;
  9506. }
  9507. return super.maybeParseExportDefaultSpecifier(...arguments);
  9508. }
  9509. checkExport(node) {
  9510. const {
  9511. specifiers
  9512. } = node;
  9513. if (specifiers != null && specifiers.length) {
  9514. node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder");
  9515. }
  9516. super.checkExport(node);
  9517. node.specifiers = specifiers;
  9518. }
  9519. parseImport(node) {
  9520. const placeholder = this.parsePlaceholder("Identifier");
  9521. if (!placeholder) return super.parseImport(...arguments);
  9522. node.specifiers = [];
  9523. if (!this.isContextual(91) && !this.match(12)) {
  9524. node.source = this.finishPlaceholder(placeholder, "StringLiteral");
  9525. this.semicolon();
  9526. return this.finishNode(node, "ImportDeclaration");
  9527. }
  9528. const specifier = this.startNodeAtNode(placeholder);
  9529. specifier.local = placeholder;
  9530. this.finishNode(specifier, "ImportDefaultSpecifier");
  9531. node.specifiers.push(specifier);
  9532. if (this.eat(12)) {
  9533. const hasStarImport = this.maybeParseStarImportSpecifier(node);
  9534. if (!hasStarImport) this.parseNamedImportSpecifiers(node);
  9535. }
  9536. this.expectContextual(91);
  9537. node.source = this.parseImportSource();
  9538. this.semicolon();
  9539. return this.finishNode(node, "ImportDeclaration");
  9540. }
  9541. parseImportSource() {
  9542. return this.parsePlaceholder("StringLiteral") || super.parseImportSource(...arguments);
  9543. }
  9544. });
  9545. var v8intrinsic = (superClass => class extends superClass {
  9546. parseV8Intrinsic() {
  9547. if (this.match(48)) {
  9548. const v8IntrinsicStart = this.state.start;
  9549. const node = this.startNode();
  9550. this.next();
  9551. if (tokenIsIdentifier(this.state.type)) {
  9552. const name = this.parseIdentifierName(this.state.start);
  9553. const identifier = this.createIdentifier(node, name);
  9554. identifier.type = "V8IntrinsicIdentifier";
  9555. if (this.match(10)) {
  9556. return identifier;
  9557. }
  9558. }
  9559. this.unexpected(v8IntrinsicStart);
  9560. }
  9561. }
  9562. parseExprAtom() {
  9563. return this.parseV8Intrinsic() || super.parseExprAtom(...arguments);
  9564. }
  9565. });
  9566. function hasPlugin(plugins, name) {
  9567. return plugins.some(plugin => {
  9568. if (Array.isArray(plugin)) {
  9569. return plugin[0] === name;
  9570. } else {
  9571. return plugin === name;
  9572. }
  9573. });
  9574. }
  9575. function getPluginOption(plugins, name, option) {
  9576. const plugin = plugins.find(plugin => {
  9577. if (Array.isArray(plugin)) {
  9578. return plugin[0] === name;
  9579. } else {
  9580. return plugin === name;
  9581. }
  9582. });
  9583. if (plugin && Array.isArray(plugin)) {
  9584. return plugin[1][option];
  9585. }
  9586. return null;
  9587. }
  9588. const PIPELINE_PROPOSALS = ["minimal", "fsharp", "hack", "smart"];
  9589. const TOPIC_TOKENS = ["^", "%", "#"];
  9590. const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"];
  9591. function validatePlugins(plugins) {
  9592. if (hasPlugin(plugins, "decorators")) {
  9593. if (hasPlugin(plugins, "decorators-legacy")) {
  9594. throw new Error("Cannot use the decorators and decorators-legacy plugin together");
  9595. }
  9596. const decoratorsBeforeExport = getPluginOption(plugins, "decorators", "decoratorsBeforeExport");
  9597. if (decoratorsBeforeExport == null) {
  9598. throw new Error("The 'decorators' plugin requires a 'decoratorsBeforeExport' option," + " whose value must be a boolean. If you are migrating from" + " Babylon/Babel 6 or want to use the old decorators proposal, you" + " should use the 'decorators-legacy' plugin instead of 'decorators'.");
  9599. } else if (typeof decoratorsBeforeExport !== "boolean") {
  9600. throw new Error("'decoratorsBeforeExport' must be a boolean.");
  9601. }
  9602. }
  9603. if (hasPlugin(plugins, "flow") && hasPlugin(plugins, "typescript")) {
  9604. throw new Error("Cannot combine flow and typescript plugins.");
  9605. }
  9606. if (hasPlugin(plugins, "placeholders") && hasPlugin(plugins, "v8intrinsic")) {
  9607. throw new Error("Cannot combine placeholders and v8intrinsic plugins.");
  9608. }
  9609. if (hasPlugin(plugins, "pipelineOperator")) {
  9610. const proposal = getPluginOption(plugins, "pipelineOperator", "proposal");
  9611. if (!PIPELINE_PROPOSALS.includes(proposal)) {
  9612. const proposalList = PIPELINE_PROPOSALS.map(p => `"${p}"`).join(", ");
  9613. throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${proposalList}.`);
  9614. }
  9615. const tupleSyntaxIsHash = hasPlugin(plugins, "recordAndTuple") && getPluginOption(plugins, "recordAndTuple", "syntaxType") === "hash";
  9616. if (proposal === "hack") {
  9617. if (hasPlugin(plugins, "placeholders")) {
  9618. throw new Error("Cannot combine placeholders plugin and Hack-style pipes.");
  9619. }
  9620. if (hasPlugin(plugins, "v8intrinsic")) {
  9621. throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes.");
  9622. }
  9623. const topicToken = getPluginOption(plugins, "pipelineOperator", "topicToken");
  9624. if (!TOPIC_TOKENS.includes(topicToken)) {
  9625. const tokenList = TOPIC_TOKENS.map(t => `"${t}"`).join(", ");
  9626. throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${tokenList}.`);
  9627. }
  9628. if (topicToken === "#" && tupleSyntaxIsHash) {
  9629. throw new Error('Plugin conflict between `["pipelineOperator", { proposal: "hack", topicToken: "#" }]` and `["recordAndtuple", { syntaxType: "hash"}]`.');
  9630. }
  9631. } else if (proposal === "smart" && tupleSyntaxIsHash) {
  9632. throw new Error('Plugin conflict between `["pipelineOperator", { proposal: "smart" }]` and `["recordAndtuple", { syntaxType: "hash"}]`.');
  9633. }
  9634. }
  9635. if (hasPlugin(plugins, "moduleAttributes")) {
  9636. {
  9637. if (hasPlugin(plugins, "importAssertions")) {
  9638. throw new Error("Cannot combine importAssertions and moduleAttributes plugins.");
  9639. }
  9640. const moduleAttributesVerionPluginOption = getPluginOption(plugins, "moduleAttributes", "version");
  9641. if (moduleAttributesVerionPluginOption !== "may-2020") {
  9642. throw new Error("The 'moduleAttributes' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is 'may-2020'.");
  9643. }
  9644. }
  9645. }
  9646. if (hasPlugin(plugins, "recordAndTuple") && !RECORD_AND_TUPLE_SYNTAX_TYPES.includes(getPluginOption(plugins, "recordAndTuple", "syntaxType"))) {
  9647. throw new Error("'recordAndTuple' requires 'syntaxType' option whose value should be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", "));
  9648. }
  9649. if (hasPlugin(plugins, "asyncDoExpressions") && !hasPlugin(plugins, "doExpressions")) {
  9650. const error = new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins.");
  9651. error.missingPlugins = "doExpressions";
  9652. throw error;
  9653. }
  9654. }
  9655. const mixinPlugins = {
  9656. estree,
  9657. jsx,
  9658. flow,
  9659. typescript,
  9660. v8intrinsic,
  9661. placeholders
  9662. };
  9663. const mixinPluginNames = Object.keys(mixinPlugins);
  9664. const defaultOptions = {
  9665. sourceType: "script",
  9666. sourceFilename: undefined,
  9667. startColumn: 0,
  9668. startLine: 1,
  9669. allowAwaitOutsideFunction: false,
  9670. allowReturnOutsideFunction: false,
  9671. allowImportExportEverywhere: false,
  9672. allowSuperOutsideMethod: false,
  9673. allowUndeclaredExports: false,
  9674. plugins: [],
  9675. strictMode: null,
  9676. ranges: false,
  9677. tokens: false,
  9678. createParenthesizedExpressions: false,
  9679. errorRecovery: false,
  9680. attachComment: true
  9681. };
  9682. function getOptions(opts) {
  9683. const options = {};
  9684. for (const key of Object.keys(defaultOptions)) {
  9685. options[key] = opts && opts[key] != null ? opts[key] : defaultOptions[key];
  9686. }
  9687. return options;
  9688. }
  9689. const unwrapParenthesizedExpression = node => {
  9690. return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node;
  9691. };
  9692. class LValParser extends NodeUtils {
  9693. toAssignable(node, isLHS = false) {
  9694. var _node$extra, _node$extra3;
  9695. let parenthesized = undefined;
  9696. if (node.type === "ParenthesizedExpression" || (_node$extra = node.extra) != null && _node$extra.parenthesized) {
  9697. parenthesized = unwrapParenthesizedExpression(node);
  9698. if (isLHS) {
  9699. if (parenthesized.type === "Identifier") {
  9700. this.expressionScope.recordParenthesizedIdentifierError(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  9701. } else if (parenthesized.type !== "MemberExpression") {
  9702. this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  9703. }
  9704. } else {
  9705. this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  9706. }
  9707. }
  9708. switch (node.type) {
  9709. case "Identifier":
  9710. case "ObjectPattern":
  9711. case "ArrayPattern":
  9712. case "AssignmentPattern":
  9713. case "RestElement":
  9714. break;
  9715. case "ObjectExpression":
  9716. node.type = "ObjectPattern";
  9717. for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) {
  9718. var _node$extra2;
  9719. const prop = node.properties[i];
  9720. const isLast = i === last;
  9721. this.toAssignableObjectExpressionProp(prop, isLast, isLHS);
  9722. if (isLast && prop.type === "RestElement" && (_node$extra2 = node.extra) != null && _node$extra2.trailingComma) {
  9723. this.raiseRestNotLast(node.extra.trailingComma);
  9724. }
  9725. }
  9726. break;
  9727. case "ObjectProperty":
  9728. this.toAssignable(node.value, isLHS);
  9729. break;
  9730. case "SpreadElement":
  9731. {
  9732. this.checkToRestConversion(node);
  9733. node.type = "RestElement";
  9734. const arg = node.argument;
  9735. this.toAssignable(arg, isLHS);
  9736. break;
  9737. }
  9738. case "ArrayExpression":
  9739. node.type = "ArrayPattern";
  9740. this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingComma, isLHS);
  9741. break;
  9742. case "AssignmentExpression":
  9743. if (node.operator !== "=") {
  9744. this.raise(node.left.end, ErrorMessages.MissingEqInAssignment);
  9745. }
  9746. node.type = "AssignmentPattern";
  9747. delete node.operator;
  9748. this.toAssignable(node.left, isLHS);
  9749. break;
  9750. case "ParenthesizedExpression":
  9751. this.toAssignable(parenthesized, isLHS);
  9752. break;
  9753. }
  9754. return node;
  9755. }
  9756. toAssignableObjectExpressionProp(prop, isLast, isLHS) {
  9757. if (prop.type === "ObjectMethod") {
  9758. const error = prop.kind === "get" || prop.kind === "set" ? ErrorMessages.PatternHasAccessor : ErrorMessages.PatternHasMethod;
  9759. this.raise(prop.key.start, error);
  9760. } else if (prop.type === "SpreadElement" && !isLast) {
  9761. this.raiseRestNotLast(prop.start);
  9762. } else {
  9763. this.toAssignable(prop, isLHS);
  9764. }
  9765. }
  9766. toAssignableList(exprList, trailingCommaPos, isLHS) {
  9767. let end = exprList.length;
  9768. if (end) {
  9769. const last = exprList[end - 1];
  9770. if ((last == null ? void 0 : last.type) === "RestElement") {
  9771. --end;
  9772. } else if ((last == null ? void 0 : last.type) === "SpreadElement") {
  9773. last.type = "RestElement";
  9774. let arg = last.argument;
  9775. this.toAssignable(arg, isLHS);
  9776. arg = unwrapParenthesizedExpression(arg);
  9777. if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern" && arg.type !== "ObjectPattern") {
  9778. this.unexpected(arg.start);
  9779. }
  9780. if (trailingCommaPos) {
  9781. this.raiseTrailingCommaAfterRest(trailingCommaPos);
  9782. }
  9783. --end;
  9784. }
  9785. }
  9786. for (let i = 0; i < end; i++) {
  9787. const elt = exprList[i];
  9788. if (elt) {
  9789. this.toAssignable(elt, isLHS);
  9790. if (elt.type === "RestElement") {
  9791. this.raiseRestNotLast(elt.start);
  9792. }
  9793. }
  9794. }
  9795. return exprList;
  9796. }
  9797. isAssignable(node, isBinding) {
  9798. switch (node.type) {
  9799. case "Identifier":
  9800. case "ObjectPattern":
  9801. case "ArrayPattern":
  9802. case "AssignmentPattern":
  9803. case "RestElement":
  9804. return true;
  9805. case "ObjectExpression":
  9806. {
  9807. const last = node.properties.length - 1;
  9808. return node.properties.every((prop, i) => {
  9809. return prop.type !== "ObjectMethod" && (i === last || prop.type !== "SpreadElement") && this.isAssignable(prop);
  9810. });
  9811. }
  9812. case "ObjectProperty":
  9813. return this.isAssignable(node.value);
  9814. case "SpreadElement":
  9815. return this.isAssignable(node.argument);
  9816. case "ArrayExpression":
  9817. return node.elements.every(element => element === null || this.isAssignable(element));
  9818. case "AssignmentExpression":
  9819. return node.operator === "=";
  9820. case "ParenthesizedExpression":
  9821. return this.isAssignable(node.expression);
  9822. case "MemberExpression":
  9823. case "OptionalMemberExpression":
  9824. return !isBinding;
  9825. default:
  9826. return false;
  9827. }
  9828. }
  9829. toReferencedList(exprList, isParenthesizedExpr) {
  9830. return exprList;
  9831. }
  9832. toReferencedListDeep(exprList, isParenthesizedExpr) {
  9833. this.toReferencedList(exprList, isParenthesizedExpr);
  9834. for (const expr of exprList) {
  9835. if ((expr == null ? void 0 : expr.type) === "ArrayExpression") {
  9836. this.toReferencedListDeep(expr.elements);
  9837. }
  9838. }
  9839. }
  9840. parseSpread(refExpressionErrors, refNeedsArrowPos) {
  9841. const node = this.startNode();
  9842. this.next();
  9843. node.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, undefined, refNeedsArrowPos);
  9844. return this.finishNode(node, "SpreadElement");
  9845. }
  9846. parseRestBinding() {
  9847. const node = this.startNode();
  9848. this.next();
  9849. node.argument = this.parseBindingAtom();
  9850. return this.finishNode(node, "RestElement");
  9851. }
  9852. parseBindingAtom() {
  9853. switch (this.state.type) {
  9854. case 0:
  9855. {
  9856. const node = this.startNode();
  9857. this.next();
  9858. node.elements = this.parseBindingList(3, 93, true);
  9859. return this.finishNode(node, "ArrayPattern");
  9860. }
  9861. case 5:
  9862. return this.parseObjectLike(8, true);
  9863. }
  9864. return this.parseIdentifier();
  9865. }
  9866. parseBindingList(close, closeCharCode, allowEmpty, allowModifiers) {
  9867. const elts = [];
  9868. let first = true;
  9869. while (!this.eat(close)) {
  9870. if (first) {
  9871. first = false;
  9872. } else {
  9873. this.expect(12);
  9874. }
  9875. if (allowEmpty && this.match(12)) {
  9876. elts.push(null);
  9877. } else if (this.eat(close)) {
  9878. break;
  9879. } else if (this.match(21)) {
  9880. elts.push(this.parseAssignableListItemTypes(this.parseRestBinding()));
  9881. this.checkCommaAfterRest(closeCharCode);
  9882. this.expect(close);
  9883. break;
  9884. } else {
  9885. const decorators = [];
  9886. if (this.match(24) && this.hasPlugin("decorators")) {
  9887. this.raise(this.state.start, ErrorMessages.UnsupportedParameterDecorator);
  9888. }
  9889. while (this.match(24)) {
  9890. decorators.push(this.parseDecorator());
  9891. }
  9892. elts.push(this.parseAssignableListItem(allowModifiers, decorators));
  9893. }
  9894. }
  9895. return elts;
  9896. }
  9897. parseBindingRestProperty(prop) {
  9898. this.next();
  9899. prop.argument = this.parseIdentifier();
  9900. this.checkCommaAfterRest(125);
  9901. return this.finishNode(prop, "RestElement");
  9902. }
  9903. parseBindingProperty() {
  9904. const prop = this.startNode();
  9905. const {
  9906. type,
  9907. start: startPos,
  9908. startLoc
  9909. } = this.state;
  9910. if (type === 21) {
  9911. return this.parseBindingRestProperty(prop);
  9912. } else {
  9913. this.parsePropertyName(prop);
  9914. }
  9915. prop.method = false;
  9916. this.parseObjPropValue(prop, startPos, startLoc, false, false, true, false);
  9917. return prop;
  9918. }
  9919. parseAssignableListItem(allowModifiers, decorators) {
  9920. const left = this.parseMaybeDefault();
  9921. this.parseAssignableListItemTypes(left);
  9922. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  9923. if (decorators.length) {
  9924. left.decorators = decorators;
  9925. }
  9926. return elt;
  9927. }
  9928. parseAssignableListItemTypes(param) {
  9929. return param;
  9930. }
  9931. parseMaybeDefault(startPos, startLoc, left) {
  9932. var _startLoc, _startPos, _left;
  9933. startLoc = (_startLoc = startLoc) != null ? _startLoc : this.state.startLoc;
  9934. startPos = (_startPos = startPos) != null ? _startPos : this.state.start;
  9935. left = (_left = left) != null ? _left : this.parseBindingAtom();
  9936. if (!this.eat(27)) return left;
  9937. const node = this.startNodeAt(startPos, startLoc);
  9938. node.left = left;
  9939. node.right = this.parseMaybeAssignAllowIn();
  9940. return this.finishNode(node, "AssignmentPattern");
  9941. }
  9942. checkLVal(expr, contextDescription, bindingType = BIND_NONE, checkClashes, disallowLetBinding, strictModeChanged = false) {
  9943. switch (expr.type) {
  9944. case "Identifier":
  9945. {
  9946. const {
  9947. name
  9948. } = expr;
  9949. if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(name, this.inModule) : isStrictBindOnlyReservedWord(name))) {
  9950. this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.StrictEvalArguments : ErrorMessages.StrictEvalArgumentsBinding, name);
  9951. }
  9952. if (checkClashes) {
  9953. if (checkClashes.has(name)) {
  9954. this.raise(expr.start, ErrorMessages.ParamDupe);
  9955. } else {
  9956. checkClashes.add(name);
  9957. }
  9958. }
  9959. if (disallowLetBinding && name === "let") {
  9960. this.raise(expr.start, ErrorMessages.LetInLexicalBinding);
  9961. }
  9962. if (!(bindingType & BIND_NONE)) {
  9963. this.scope.declareName(name, bindingType, expr.start);
  9964. }
  9965. break;
  9966. }
  9967. case "MemberExpression":
  9968. if (bindingType !== BIND_NONE) {
  9969. this.raise(expr.start, ErrorMessages.InvalidPropertyBindingPattern);
  9970. }
  9971. break;
  9972. case "ObjectPattern":
  9973. for (let prop of expr.properties) {
  9974. if (this.isObjectProperty(prop)) prop = prop.value;else if (this.isObjectMethod(prop)) continue;
  9975. this.checkLVal(prop, "object destructuring pattern", bindingType, checkClashes, disallowLetBinding);
  9976. }
  9977. break;
  9978. case "ArrayPattern":
  9979. for (const elem of expr.elements) {
  9980. if (elem) {
  9981. this.checkLVal(elem, "array destructuring pattern", bindingType, checkClashes, disallowLetBinding);
  9982. }
  9983. }
  9984. break;
  9985. case "AssignmentPattern":
  9986. this.checkLVal(expr.left, "assignment pattern", bindingType, checkClashes);
  9987. break;
  9988. case "RestElement":
  9989. this.checkLVal(expr.argument, "rest element", bindingType, checkClashes);
  9990. break;
  9991. case "ParenthesizedExpression":
  9992. this.checkLVal(expr.expression, "parenthesized expression", bindingType, checkClashes);
  9993. break;
  9994. default:
  9995. {
  9996. this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.InvalidLhs : ErrorMessages.InvalidLhsBinding, contextDescription);
  9997. }
  9998. }
  9999. }
  10000. checkToRestConversion(node) {
  10001. if (node.argument.type !== "Identifier" && node.argument.type !== "MemberExpression") {
  10002. this.raise(node.argument.start, ErrorMessages.InvalidRestAssignmentPattern);
  10003. }
  10004. }
  10005. checkCommaAfterRest(close) {
  10006. if (this.match(12)) {
  10007. if (this.lookaheadCharCode() === close) {
  10008. this.raiseTrailingCommaAfterRest(this.state.start);
  10009. } else {
  10010. this.raiseRestNotLast(this.state.start);
  10011. }
  10012. }
  10013. }
  10014. raiseRestNotLast(pos) {
  10015. throw this.raise(pos, ErrorMessages.ElementAfterRest);
  10016. }
  10017. raiseTrailingCommaAfterRest(pos) {
  10018. this.raise(pos, ErrorMessages.RestTrailingComma);
  10019. }
  10020. }
  10021. const invalidHackPipeBodies = new Map([["ArrowFunctionExpression", "arrow function"], ["AssignmentExpression", "assignment"], ["ConditionalExpression", "conditional"], ["YieldExpression", "yield"]]);
  10022. class ExpressionParser extends LValParser {
  10023. checkProto(prop, isRecord, protoRef, refExpressionErrors) {
  10024. if (prop.type === "SpreadElement" || this.isObjectMethod(prop) || prop.computed || prop.shorthand) {
  10025. return;
  10026. }
  10027. const key = prop.key;
  10028. const name = key.type === "Identifier" ? key.name : key.value;
  10029. if (name === "__proto__") {
  10030. if (isRecord) {
  10031. this.raise(key.start, ErrorMessages.RecordNoProto);
  10032. return;
  10033. }
  10034. if (protoRef.used) {
  10035. if (refExpressionErrors) {
  10036. if (refExpressionErrors.doubleProto === -1) {
  10037. refExpressionErrors.doubleProto = key.start;
  10038. }
  10039. } else {
  10040. this.raise(key.start, ErrorMessages.DuplicateProto);
  10041. }
  10042. }
  10043. protoRef.used = true;
  10044. }
  10045. }
  10046. shouldExitDescending(expr, potentialArrowAt) {
  10047. return expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt;
  10048. }
  10049. getExpression() {
  10050. this.enterInitialScopes();
  10051. this.nextToken();
  10052. const expr = this.parseExpression();
  10053. if (!this.match(129)) {
  10054. this.unexpected();
  10055. }
  10056. this.finalizeRemainingComments();
  10057. expr.comments = this.state.comments;
  10058. expr.errors = this.state.errors;
  10059. if (this.options.tokens) {
  10060. expr.tokens = this.tokens;
  10061. }
  10062. return expr;
  10063. }
  10064. parseExpression(disallowIn, refExpressionErrors) {
  10065. if (disallowIn) {
  10066. return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  10067. }
  10068. return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  10069. }
  10070. parseExpressionBase(refExpressionErrors) {
  10071. const startPos = this.state.start;
  10072. const startLoc = this.state.startLoc;
  10073. const expr = this.parseMaybeAssign(refExpressionErrors);
  10074. if (this.match(12)) {
  10075. const node = this.startNodeAt(startPos, startLoc);
  10076. node.expressions = [expr];
  10077. while (this.eat(12)) {
  10078. node.expressions.push(this.parseMaybeAssign(refExpressionErrors));
  10079. }
  10080. this.toReferencedList(node.expressions);
  10081. return this.finishNode(node, "SequenceExpression");
  10082. }
  10083. return expr;
  10084. }
  10085. parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse) {
  10086. return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse));
  10087. }
  10088. parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse) {
  10089. return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse));
  10090. }
  10091. setOptionalParametersError(refExpressionErrors, resultError) {
  10092. var _resultError$pos;
  10093. refExpressionErrors.optionalParameters = (_resultError$pos = resultError == null ? void 0 : resultError.pos) != null ? _resultError$pos : this.state.start;
  10094. }
  10095. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  10096. const startPos = this.state.start;
  10097. const startLoc = this.state.startLoc;
  10098. if (this.isContextual(99)) {
  10099. if (this.prodParam.hasYield) {
  10100. let left = this.parseYield();
  10101. if (afterLeftParse) {
  10102. left = afterLeftParse.call(this, left, startPos, startLoc);
  10103. }
  10104. return left;
  10105. }
  10106. }
  10107. let ownExpressionErrors;
  10108. if (refExpressionErrors) {
  10109. ownExpressionErrors = false;
  10110. } else {
  10111. refExpressionErrors = new ExpressionErrors();
  10112. ownExpressionErrors = true;
  10113. }
  10114. const {
  10115. type
  10116. } = this.state;
  10117. if (type === 10 || tokenIsIdentifier(type)) {
  10118. this.state.potentialArrowAt = this.state.start;
  10119. }
  10120. let left = this.parseMaybeConditional(refExpressionErrors);
  10121. if (afterLeftParse) {
  10122. left = afterLeftParse.call(this, left, startPos, startLoc);
  10123. }
  10124. if (tokenIsAssignment(this.state.type)) {
  10125. const node = this.startNodeAt(startPos, startLoc);
  10126. const operator = this.state.value;
  10127. node.operator = operator;
  10128. if (this.match(27)) {
  10129. node.left = this.toAssignable(left, true);
  10130. if (refExpressionErrors.doubleProto >= startPos) {
  10131. refExpressionErrors.doubleProto = -1;
  10132. }
  10133. if (refExpressionErrors.shorthandAssign >= startPos) {
  10134. refExpressionErrors.shorthandAssign = -1;
  10135. }
  10136. } else {
  10137. node.left = left;
  10138. }
  10139. this.checkLVal(left, "assignment expression");
  10140. this.next();
  10141. node.right = this.parseMaybeAssign();
  10142. return this.finishNode(node, "AssignmentExpression");
  10143. } else if (ownExpressionErrors) {
  10144. this.checkExpressionErrors(refExpressionErrors, true);
  10145. }
  10146. return left;
  10147. }
  10148. parseMaybeConditional(refExpressionErrors) {
  10149. const startPos = this.state.start;
  10150. const startLoc = this.state.startLoc;
  10151. const potentialArrowAt = this.state.potentialArrowAt;
  10152. const expr = this.parseExprOps(refExpressionErrors);
  10153. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  10154. return expr;
  10155. }
  10156. return this.parseConditional(expr, startPos, startLoc, refExpressionErrors);
  10157. }
  10158. parseConditional(expr, startPos, startLoc, refExpressionErrors) {
  10159. if (this.eat(17)) {
  10160. const node = this.startNodeAt(startPos, startLoc);
  10161. node.test = expr;
  10162. node.consequent = this.parseMaybeAssignAllowIn();
  10163. this.expect(14);
  10164. node.alternate = this.parseMaybeAssign();
  10165. return this.finishNode(node, "ConditionalExpression");
  10166. }
  10167. return expr;
  10168. }
  10169. parseMaybeUnaryOrPrivate(refExpressionErrors) {
  10170. return this.match(128) ? this.parsePrivateName() : this.parseMaybeUnary(refExpressionErrors);
  10171. }
  10172. parseExprOps(refExpressionErrors) {
  10173. const startPos = this.state.start;
  10174. const startLoc = this.state.startLoc;
  10175. const potentialArrowAt = this.state.potentialArrowAt;
  10176. const expr = this.parseMaybeUnaryOrPrivate(refExpressionErrors);
  10177. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  10178. return expr;
  10179. }
  10180. return this.parseExprOp(expr, startPos, startLoc, -1);
  10181. }
  10182. parseExprOp(left, leftStartPos, leftStartLoc, minPrec) {
  10183. if (this.isPrivateName(left)) {
  10184. const value = this.getPrivateNameSV(left);
  10185. const {
  10186. start
  10187. } = left;
  10188. if (minPrec >= tokenOperatorPrecedence(52) || !this.prodParam.hasIn || !this.match(52)) {
  10189. this.raise(start, ErrorMessages.PrivateInExpectedIn, value);
  10190. }
  10191. this.classScope.usePrivateName(value, start);
  10192. }
  10193. const op = this.state.type;
  10194. if (tokenIsOperator(op) && (this.prodParam.hasIn || !this.match(52))) {
  10195. let prec = tokenOperatorPrecedence(op);
  10196. if (prec > minPrec) {
  10197. if (op === 35) {
  10198. this.expectPlugin("pipelineOperator");
  10199. if (this.state.inFSharpPipelineDirectBody) {
  10200. return left;
  10201. }
  10202. this.checkPipelineAtInfixOperator(left, leftStartPos);
  10203. }
  10204. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  10205. node.left = left;
  10206. node.operator = this.state.value;
  10207. const logical = op === 37 || op === 38;
  10208. const coalesce = op === 36;
  10209. if (coalesce) {
  10210. prec = tokenOperatorPrecedence(38);
  10211. }
  10212. this.next();
  10213. if (op === 35 && this.getPluginOption("pipelineOperator", "proposal") === "minimal") {
  10214. if (this.state.type === 90 && this.prodParam.hasAwait) {
  10215. throw this.raise(this.state.start, ErrorMessages.UnexpectedAwaitAfterPipelineBody);
  10216. }
  10217. }
  10218. node.right = this.parseExprOpRightExpr(op, prec);
  10219. this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression");
  10220. const nextOp = this.state.type;
  10221. if (coalesce && (nextOp === 37 || nextOp === 38) || logical && nextOp === 36) {
  10222. throw this.raise(this.state.start, ErrorMessages.MixingCoalesceWithLogical);
  10223. }
  10224. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec);
  10225. }
  10226. }
  10227. return left;
  10228. }
  10229. parseExprOpRightExpr(op, prec) {
  10230. const startPos = this.state.start;
  10231. const startLoc = this.state.startLoc;
  10232. switch (op) {
  10233. case 35:
  10234. switch (this.getPluginOption("pipelineOperator", "proposal")) {
  10235. case "hack":
  10236. return this.withTopicBindingContext(() => {
  10237. return this.parseHackPipeBody();
  10238. });
  10239. case "smart":
  10240. return this.withTopicBindingContext(() => {
  10241. if (this.prodParam.hasYield && this.isContextual(99)) {
  10242. throw this.raise(this.state.start, ErrorMessages.PipeBodyIsTighter, this.state.value);
  10243. }
  10244. return this.parseSmartPipelineBodyInStyle(this.parseExprOpBaseRightExpr(op, prec), startPos, startLoc);
  10245. });
  10246. case "fsharp":
  10247. return this.withSoloAwaitPermittingContext(() => {
  10248. return this.parseFSharpPipelineBody(prec);
  10249. });
  10250. }
  10251. default:
  10252. return this.parseExprOpBaseRightExpr(op, prec);
  10253. }
  10254. }
  10255. parseExprOpBaseRightExpr(op, prec) {
  10256. const startPos = this.state.start;
  10257. const startLoc = this.state.startLoc;
  10258. return this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startPos, startLoc, tokenIsRightAssociative(op) ? prec - 1 : prec);
  10259. }
  10260. parseHackPipeBody() {
  10261. var _body$extra;
  10262. const {
  10263. start
  10264. } = this.state;
  10265. const body = this.parseMaybeAssign();
  10266. if (invalidHackPipeBodies.has(body.type) && !((_body$extra = body.extra) != null && _body$extra.parenthesized)) {
  10267. this.raise(start, ErrorMessages.PipeUnparenthesizedBody, invalidHackPipeBodies.get(body.type));
  10268. }
  10269. if (!this.topicReferenceWasUsedInCurrentContext()) {
  10270. this.raise(start, ErrorMessages.PipeTopicUnused);
  10271. }
  10272. return body;
  10273. }
  10274. checkExponentialAfterUnary(node) {
  10275. if (this.match(51)) {
  10276. this.raise(node.argument.start, ErrorMessages.UnexpectedTokenUnaryExponentiation);
  10277. }
  10278. }
  10279. parseMaybeUnary(refExpressionErrors, sawUnary) {
  10280. const startPos = this.state.start;
  10281. const startLoc = this.state.startLoc;
  10282. const isAwait = this.isContextual(90);
  10283. if (isAwait && this.isAwaitAllowed()) {
  10284. this.next();
  10285. const expr = this.parseAwait(startPos, startLoc);
  10286. if (!sawUnary) this.checkExponentialAfterUnary(expr);
  10287. return expr;
  10288. }
  10289. const update = this.match(32);
  10290. const node = this.startNode();
  10291. if (tokenIsPrefix(this.state.type)) {
  10292. node.operator = this.state.value;
  10293. node.prefix = true;
  10294. if (this.match(66)) {
  10295. this.expectPlugin("throwExpressions");
  10296. }
  10297. const isDelete = this.match(83);
  10298. this.next();
  10299. node.argument = this.parseMaybeUnary(null, true);
  10300. this.checkExpressionErrors(refExpressionErrors, true);
  10301. if (this.state.strict && isDelete) {
  10302. const arg = node.argument;
  10303. if (arg.type === "Identifier") {
  10304. this.raise(node.start, ErrorMessages.StrictDelete);
  10305. } else if (this.hasPropertyAsPrivateName(arg)) {
  10306. this.raise(node.start, ErrorMessages.DeletePrivateField);
  10307. }
  10308. }
  10309. if (!update) {
  10310. if (!sawUnary) this.checkExponentialAfterUnary(node);
  10311. return this.finishNode(node, "UnaryExpression");
  10312. }
  10313. }
  10314. const expr = this.parseUpdate(node, update, refExpressionErrors);
  10315. if (isAwait) {
  10316. const {
  10317. type
  10318. } = this.state;
  10319. const startsExpr = this.hasPlugin("v8intrinsic") ? tokenCanStartExpression(type) : tokenCanStartExpression(type) && !this.match(48);
  10320. if (startsExpr && !this.isAmbiguousAwait()) {
  10321. this.raiseOverwrite(startPos, ErrorMessages.AwaitNotInAsyncContext);
  10322. return this.parseAwait(startPos, startLoc);
  10323. }
  10324. }
  10325. return expr;
  10326. }
  10327. parseUpdate(node, update, refExpressionErrors) {
  10328. if (update) {
  10329. this.checkLVal(node.argument, "prefix operation");
  10330. return this.finishNode(node, "UpdateExpression");
  10331. }
  10332. const startPos = this.state.start;
  10333. const startLoc = this.state.startLoc;
  10334. let expr = this.parseExprSubscripts(refExpressionErrors);
  10335. if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
  10336. while (tokenIsPostfix(this.state.type) && !this.canInsertSemicolon()) {
  10337. const node = this.startNodeAt(startPos, startLoc);
  10338. node.operator = this.state.value;
  10339. node.prefix = false;
  10340. node.argument = expr;
  10341. this.checkLVal(expr, "postfix operation");
  10342. this.next();
  10343. expr = this.finishNode(node, "UpdateExpression");
  10344. }
  10345. return expr;
  10346. }
  10347. parseExprSubscripts(refExpressionErrors) {
  10348. const startPos = this.state.start;
  10349. const startLoc = this.state.startLoc;
  10350. const potentialArrowAt = this.state.potentialArrowAt;
  10351. const expr = this.parseExprAtom(refExpressionErrors);
  10352. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  10353. return expr;
  10354. }
  10355. return this.parseSubscripts(expr, startPos, startLoc);
  10356. }
  10357. parseSubscripts(base, startPos, startLoc, noCalls) {
  10358. const state = {
  10359. optionalChainMember: false,
  10360. maybeAsyncArrow: this.atPossibleAsyncArrow(base),
  10361. stop: false
  10362. };
  10363. do {
  10364. base = this.parseSubscript(base, startPos, startLoc, noCalls, state);
  10365. state.maybeAsyncArrow = false;
  10366. } while (!state.stop);
  10367. return base;
  10368. }
  10369. parseSubscript(base, startPos, startLoc, noCalls, state) {
  10370. if (!noCalls && this.eat(15)) {
  10371. return this.parseBind(base, startPos, startLoc, noCalls, state);
  10372. } else if (this.match(22)) {
  10373. return this.parseTaggedTemplateExpression(base, startPos, startLoc, state);
  10374. }
  10375. let optional = false;
  10376. if (this.match(18)) {
  10377. if (noCalls && this.lookaheadCharCode() === 40) {
  10378. state.stop = true;
  10379. return base;
  10380. }
  10381. state.optionalChainMember = optional = true;
  10382. this.next();
  10383. }
  10384. if (!noCalls && this.match(10)) {
  10385. return this.parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional);
  10386. } else {
  10387. const computed = this.eat(0);
  10388. if (computed || optional || this.eat(16)) {
  10389. return this.parseMember(base, startPos, startLoc, state, computed, optional);
  10390. } else {
  10391. state.stop = true;
  10392. return base;
  10393. }
  10394. }
  10395. }
  10396. parseMember(base, startPos, startLoc, state, computed, optional) {
  10397. const node = this.startNodeAt(startPos, startLoc);
  10398. node.object = base;
  10399. node.computed = computed;
  10400. const privateName = !computed && this.match(128) && this.state.value;
  10401. const property = computed ? this.parseExpression() : privateName ? this.parsePrivateName() : this.parseIdentifier(true);
  10402. if (privateName !== false) {
  10403. if (node.object.type === "Super") {
  10404. this.raise(startPos, ErrorMessages.SuperPrivateField);
  10405. }
  10406. this.classScope.usePrivateName(privateName, property.start);
  10407. }
  10408. node.property = property;
  10409. if (computed) {
  10410. this.expect(3);
  10411. }
  10412. if (state.optionalChainMember) {
  10413. node.optional = optional;
  10414. return this.finishNode(node, "OptionalMemberExpression");
  10415. } else {
  10416. return this.finishNode(node, "MemberExpression");
  10417. }
  10418. }
  10419. parseBind(base, startPos, startLoc, noCalls, state) {
  10420. const node = this.startNodeAt(startPos, startLoc);
  10421. node.object = base;
  10422. node.callee = this.parseNoCallExpr();
  10423. state.stop = true;
  10424. return this.parseSubscripts(this.finishNode(node, "BindExpression"), startPos, startLoc, noCalls);
  10425. }
  10426. parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional) {
  10427. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  10428. let refExpressionErrors = null;
  10429. this.state.maybeInArrowParameters = true;
  10430. this.next();
  10431. let node = this.startNodeAt(startPos, startLoc);
  10432. node.callee = base;
  10433. if (state.maybeAsyncArrow) {
  10434. this.expressionScope.enter(newAsyncArrowScope());
  10435. refExpressionErrors = new ExpressionErrors();
  10436. }
  10437. if (state.optionalChainMember) {
  10438. node.optional = optional;
  10439. }
  10440. if (optional) {
  10441. node.arguments = this.parseCallExpressionArguments(11);
  10442. } else {
  10443. node.arguments = this.parseCallExpressionArguments(11, base.type === "Import", base.type !== "Super", node, refExpressionErrors);
  10444. }
  10445. this.finishCallExpression(node, state.optionalChainMember);
  10446. if (state.maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {
  10447. state.stop = true;
  10448. this.expressionScope.validateAsPattern();
  10449. this.expressionScope.exit();
  10450. node = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startPos, startLoc), node);
  10451. } else {
  10452. if (state.maybeAsyncArrow) {
  10453. this.checkExpressionErrors(refExpressionErrors, true);
  10454. this.expressionScope.exit();
  10455. }
  10456. this.toReferencedArguments(node);
  10457. }
  10458. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  10459. return node;
  10460. }
  10461. toReferencedArguments(node, isParenthesizedExpr) {
  10462. this.toReferencedListDeep(node.arguments, isParenthesizedExpr);
  10463. }
  10464. parseTaggedTemplateExpression(base, startPos, startLoc, state) {
  10465. const node = this.startNodeAt(startPos, startLoc);
  10466. node.tag = base;
  10467. node.quasi = this.parseTemplate(true);
  10468. if (state.optionalChainMember) {
  10469. this.raise(startPos, ErrorMessages.OptionalChainingNoTemplate);
  10470. }
  10471. return this.finishNode(node, "TaggedTemplateExpression");
  10472. }
  10473. atPossibleAsyncArrow(base) {
  10474. return base.type === "Identifier" && base.name === "async" && this.state.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && base.start === this.state.potentialArrowAt;
  10475. }
  10476. finishCallExpression(node, optional) {
  10477. if (node.callee.type === "Import") {
  10478. if (node.arguments.length === 2) {
  10479. {
  10480. if (!this.hasPlugin("moduleAttributes")) {
  10481. this.expectPlugin("importAssertions");
  10482. }
  10483. }
  10484. }
  10485. if (node.arguments.length === 0 || node.arguments.length > 2) {
  10486. this.raise(node.start, ErrorMessages.ImportCallArity, this.hasPlugin("importAssertions") || this.hasPlugin("moduleAttributes") ? "one or two arguments" : "one argument");
  10487. } else {
  10488. for (const arg of node.arguments) {
  10489. if (arg.type === "SpreadElement") {
  10490. this.raise(arg.start, ErrorMessages.ImportCallSpreadArgument);
  10491. }
  10492. }
  10493. }
  10494. }
  10495. return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression");
  10496. }
  10497. parseCallExpressionArguments(close, dynamicImport, allowPlaceholder, nodeForExtra, refExpressionErrors) {
  10498. const elts = [];
  10499. let first = true;
  10500. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  10501. this.state.inFSharpPipelineDirectBody = false;
  10502. while (!this.eat(close)) {
  10503. if (first) {
  10504. first = false;
  10505. } else {
  10506. this.expect(12);
  10507. if (this.match(close)) {
  10508. if (dynamicImport && !this.hasPlugin("importAssertions") && !this.hasPlugin("moduleAttributes")) {
  10509. this.raise(this.state.lastTokStart, ErrorMessages.ImportCallArgumentTrailingComma);
  10510. }
  10511. if (nodeForExtra) {
  10512. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  10513. }
  10514. this.next();
  10515. break;
  10516. }
  10517. }
  10518. elts.push(this.parseExprListItem(false, refExpressionErrors, allowPlaceholder));
  10519. }
  10520. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  10521. return elts;
  10522. }
  10523. shouldParseAsyncArrow() {
  10524. return this.match(19) && !this.canInsertSemicolon();
  10525. }
  10526. parseAsyncArrowFromCallExpression(node, call) {
  10527. var _call$extra;
  10528. this.resetPreviousNodeTrailingComments(call);
  10529. this.expect(19);
  10530. this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingComma);
  10531. if (call.innerComments) {
  10532. setInnerComments(node, call.innerComments);
  10533. }
  10534. if (call.callee.trailingComments) {
  10535. setInnerComments(node, call.callee.trailingComments);
  10536. }
  10537. return node;
  10538. }
  10539. parseNoCallExpr() {
  10540. const startPos = this.state.start;
  10541. const startLoc = this.state.startLoc;
  10542. return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  10543. }
  10544. parseExprAtom(refExpressionErrors) {
  10545. let node;
  10546. const {
  10547. type
  10548. } = this.state;
  10549. switch (type) {
  10550. case 73:
  10551. return this.parseSuper();
  10552. case 77:
  10553. node = this.startNode();
  10554. this.next();
  10555. if (this.match(16)) {
  10556. return this.parseImportMetaProperty(node);
  10557. }
  10558. if (!this.match(10)) {
  10559. this.raise(this.state.lastTokStart, ErrorMessages.UnsupportedImport);
  10560. }
  10561. return this.finishNode(node, "Import");
  10562. case 72:
  10563. node = this.startNode();
  10564. this.next();
  10565. return this.finishNode(node, "ThisExpression");
  10566. case 84:
  10567. {
  10568. return this.parseDo(this.startNode(), false);
  10569. }
  10570. case 50:
  10571. case 29:
  10572. {
  10573. this.readRegexp();
  10574. return this.parseRegExpLiteral(this.state.value);
  10575. }
  10576. case 124:
  10577. return this.parseNumericLiteral(this.state.value);
  10578. case 125:
  10579. return this.parseBigIntLiteral(this.state.value);
  10580. case 126:
  10581. return this.parseDecimalLiteral(this.state.value);
  10582. case 123:
  10583. return this.parseStringLiteral(this.state.value);
  10584. case 78:
  10585. return this.parseNullLiteral();
  10586. case 79:
  10587. return this.parseBooleanLiteral(true);
  10588. case 80:
  10589. return this.parseBooleanLiteral(false);
  10590. case 10:
  10591. {
  10592. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  10593. return this.parseParenAndDistinguishExpression(canBeArrow);
  10594. }
  10595. case 2:
  10596. case 1:
  10597. {
  10598. return this.parseArrayLike(this.state.type === 2 ? 4 : 3, false, true);
  10599. }
  10600. case 0:
  10601. {
  10602. return this.parseArrayLike(3, true, false, refExpressionErrors);
  10603. }
  10604. case 6:
  10605. case 7:
  10606. {
  10607. return this.parseObjectLike(this.state.type === 6 ? 9 : 8, false, true);
  10608. }
  10609. case 5:
  10610. {
  10611. return this.parseObjectLike(8, false, false, refExpressionErrors);
  10612. }
  10613. case 62:
  10614. return this.parseFunctionOrFunctionSent();
  10615. case 24:
  10616. this.parseDecorators();
  10617. case 74:
  10618. node = this.startNode();
  10619. this.takeDecorators(node);
  10620. return this.parseClass(node, false);
  10621. case 71:
  10622. return this.parseNewOrNewTarget();
  10623. case 22:
  10624. return this.parseTemplate(false);
  10625. case 15:
  10626. {
  10627. node = this.startNode();
  10628. this.next();
  10629. node.object = null;
  10630. const callee = node.callee = this.parseNoCallExpr();
  10631. if (callee.type === "MemberExpression") {
  10632. return this.finishNode(node, "BindExpression");
  10633. } else {
  10634. throw this.raise(callee.start, ErrorMessages.UnsupportedBind);
  10635. }
  10636. }
  10637. case 128:
  10638. {
  10639. this.raise(this.state.start, ErrorMessages.PrivateInExpectedIn, this.state.value);
  10640. return this.parsePrivateName();
  10641. }
  10642. case 31:
  10643. {
  10644. return this.parseTopicReferenceThenEqualsSign(48, "%");
  10645. }
  10646. case 30:
  10647. {
  10648. return this.parseTopicReferenceThenEqualsSign(40, "^");
  10649. }
  10650. case 40:
  10651. case 48:
  10652. case 25:
  10653. {
  10654. const pipeProposal = this.getPluginOption("pipelineOperator", "proposal");
  10655. if (pipeProposal) {
  10656. return this.parseTopicReference(pipeProposal);
  10657. } else {
  10658. throw this.unexpected();
  10659. }
  10660. }
  10661. case 43:
  10662. {
  10663. const lookaheadCh = this.input.codePointAt(this.nextTokenStart());
  10664. if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) {
  10665. this.expectOnePlugin(["jsx", "flow", "typescript"]);
  10666. break;
  10667. } else {
  10668. throw this.unexpected();
  10669. }
  10670. }
  10671. default:
  10672. if (tokenIsIdentifier(type)) {
  10673. if (this.isContextual(117) && this.lookaheadCharCode() === 123 && !this.hasFollowingLineBreak()) {
  10674. return this.parseModuleExpression();
  10675. }
  10676. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  10677. const containsEsc = this.state.containsEsc;
  10678. const id = this.parseIdentifier();
  10679. if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) {
  10680. const {
  10681. type
  10682. } = this.state;
  10683. if (type === 62) {
  10684. this.resetPreviousNodeTrailingComments(id);
  10685. this.next();
  10686. return this.parseFunction(this.startNodeAtNode(id), undefined, true);
  10687. } else if (tokenIsIdentifier(type)) {
  10688. if (this.lookaheadCharCode() === 61) {
  10689. return this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(id));
  10690. } else {
  10691. return id;
  10692. }
  10693. } else if (type === 84) {
  10694. this.resetPreviousNodeTrailingComments(id);
  10695. return this.parseDo(this.startNodeAtNode(id), true);
  10696. }
  10697. }
  10698. if (canBeArrow && this.match(19) && !this.canInsertSemicolon()) {
  10699. this.next();
  10700. return this.parseArrowExpression(this.startNodeAtNode(id), [id], false);
  10701. }
  10702. return id;
  10703. } else {
  10704. throw this.unexpected();
  10705. }
  10706. }
  10707. }
  10708. parseTopicReferenceThenEqualsSign(topicTokenType, topicTokenValue) {
  10709. const pipeProposal = this.getPluginOption("pipelineOperator", "proposal");
  10710. if (pipeProposal) {
  10711. this.state.type = topicTokenType;
  10712. this.state.value = topicTokenValue;
  10713. this.state.pos--;
  10714. this.state.end--;
  10715. this.state.endLoc.column--;
  10716. return this.parseTopicReference(pipeProposal);
  10717. } else {
  10718. throw this.unexpected();
  10719. }
  10720. }
  10721. parseTopicReference(pipeProposal) {
  10722. const node = this.startNode();
  10723. const start = this.state.start;
  10724. const tokenType = this.state.type;
  10725. this.next();
  10726. return this.finishTopicReference(node, start, pipeProposal, tokenType);
  10727. }
  10728. finishTopicReference(node, start, pipeProposal, tokenType) {
  10729. if (this.testTopicReferenceConfiguration(pipeProposal, start, tokenType)) {
  10730. let nodeType;
  10731. if (pipeProposal === "smart") {
  10732. nodeType = "PipelinePrimaryTopicReference";
  10733. } else {
  10734. nodeType = "TopicReference";
  10735. }
  10736. if (!this.topicReferenceIsAllowedInCurrentContext()) {
  10737. if (pipeProposal === "smart") {
  10738. this.raise(start, ErrorMessages.PrimaryTopicNotAllowed);
  10739. } else {
  10740. this.raise(start, ErrorMessages.PipeTopicUnbound);
  10741. }
  10742. }
  10743. this.registerTopicReference();
  10744. return this.finishNode(node, nodeType);
  10745. } else {
  10746. throw this.raise(start, ErrorMessages.PipeTopicUnconfiguredToken, tokenLabelName(tokenType));
  10747. }
  10748. }
  10749. testTopicReferenceConfiguration(pipeProposal, start, tokenType) {
  10750. switch (pipeProposal) {
  10751. case "hack":
  10752. {
  10753. const pluginTopicToken = this.getPluginOption("pipelineOperator", "topicToken");
  10754. return tokenLabelName(tokenType) === pluginTopicToken;
  10755. }
  10756. case "smart":
  10757. return tokenType === 25;
  10758. default:
  10759. throw this.raise(start, ErrorMessages.PipeTopicRequiresHackPipes);
  10760. }
  10761. }
  10762. parseAsyncArrowUnaryFunction(node) {
  10763. this.prodParam.enter(functionFlags(true, this.prodParam.hasYield));
  10764. const params = [this.parseIdentifier()];
  10765. this.prodParam.exit();
  10766. if (this.hasPrecedingLineBreak()) {
  10767. this.raise(this.state.pos, ErrorMessages.LineTerminatorBeforeArrow);
  10768. }
  10769. this.expect(19);
  10770. this.parseArrowExpression(node, params, true);
  10771. return node;
  10772. }
  10773. parseDo(node, isAsync) {
  10774. this.expectPlugin("doExpressions");
  10775. if (isAsync) {
  10776. this.expectPlugin("asyncDoExpressions");
  10777. }
  10778. node.async = isAsync;
  10779. this.next();
  10780. const oldLabels = this.state.labels;
  10781. this.state.labels = [];
  10782. if (isAsync) {
  10783. this.prodParam.enter(PARAM_AWAIT);
  10784. node.body = this.parseBlock();
  10785. this.prodParam.exit();
  10786. } else {
  10787. node.body = this.parseBlock();
  10788. }
  10789. this.state.labels = oldLabels;
  10790. return this.finishNode(node, "DoExpression");
  10791. }
  10792. parseSuper() {
  10793. const node = this.startNode();
  10794. this.next();
  10795. if (this.match(10) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) {
  10796. this.raise(node.start, ErrorMessages.SuperNotAllowed);
  10797. } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) {
  10798. this.raise(node.start, ErrorMessages.UnexpectedSuper);
  10799. }
  10800. if (!this.match(10) && !this.match(0) && !this.match(16)) {
  10801. this.raise(node.start, ErrorMessages.UnsupportedSuper);
  10802. }
  10803. return this.finishNode(node, "Super");
  10804. }
  10805. parsePrivateName() {
  10806. const node = this.startNode();
  10807. const id = this.startNodeAt(this.state.start + 1, new Position(this.state.curLine, this.state.start + 1 - this.state.lineStart));
  10808. const name = this.state.value;
  10809. this.next();
  10810. node.id = this.createIdentifier(id, name);
  10811. return this.finishNode(node, "PrivateName");
  10812. }
  10813. parseFunctionOrFunctionSent() {
  10814. const node = this.startNode();
  10815. this.next();
  10816. if (this.prodParam.hasYield && this.match(16)) {
  10817. const meta = this.createIdentifier(this.startNodeAtNode(node), "function");
  10818. this.next();
  10819. if (this.match(96)) {
  10820. this.expectPlugin("functionSent");
  10821. } else if (!this.hasPlugin("functionSent")) {
  10822. this.unexpected();
  10823. }
  10824. return this.parseMetaProperty(node, meta, "sent");
  10825. }
  10826. return this.parseFunction(node);
  10827. }
  10828. parseMetaProperty(node, meta, propertyName) {
  10829. node.meta = meta;
  10830. const containsEsc = this.state.containsEsc;
  10831. node.property = this.parseIdentifier(true);
  10832. if (node.property.name !== propertyName || containsEsc) {
  10833. this.raise(node.property.start, ErrorMessages.UnsupportedMetaProperty, meta.name, propertyName);
  10834. }
  10835. return this.finishNode(node, "MetaProperty");
  10836. }
  10837. parseImportMetaProperty(node) {
  10838. const id = this.createIdentifier(this.startNodeAtNode(node), "import");
  10839. this.next();
  10840. if (this.isContextual(94)) {
  10841. if (!this.inModule) {
  10842. this.raise(id.start, SourceTypeModuleErrorMessages.ImportMetaOutsideModule);
  10843. }
  10844. this.sawUnambiguousESM = true;
  10845. }
  10846. return this.parseMetaProperty(node, id, "meta");
  10847. }
  10848. parseLiteralAtNode(value, type, node) {
  10849. this.addExtra(node, "rawValue", value);
  10850. this.addExtra(node, "raw", this.input.slice(node.start, this.state.end));
  10851. node.value = value;
  10852. this.next();
  10853. return this.finishNode(node, type);
  10854. }
  10855. parseLiteral(value, type) {
  10856. const node = this.startNode();
  10857. return this.parseLiteralAtNode(value, type, node);
  10858. }
  10859. parseStringLiteral(value) {
  10860. return this.parseLiteral(value, "StringLiteral");
  10861. }
  10862. parseNumericLiteral(value) {
  10863. return this.parseLiteral(value, "NumericLiteral");
  10864. }
  10865. parseBigIntLiteral(value) {
  10866. return this.parseLiteral(value, "BigIntLiteral");
  10867. }
  10868. parseDecimalLiteral(value) {
  10869. return this.parseLiteral(value, "DecimalLiteral");
  10870. }
  10871. parseRegExpLiteral(value) {
  10872. const node = this.parseLiteral(value.value, "RegExpLiteral");
  10873. node.pattern = value.pattern;
  10874. node.flags = value.flags;
  10875. return node;
  10876. }
  10877. parseBooleanLiteral(value) {
  10878. const node = this.startNode();
  10879. node.value = value;
  10880. this.next();
  10881. return this.finishNode(node, "BooleanLiteral");
  10882. }
  10883. parseNullLiteral() {
  10884. const node = this.startNode();
  10885. this.next();
  10886. return this.finishNode(node, "NullLiteral");
  10887. }
  10888. parseParenAndDistinguishExpression(canBeArrow) {
  10889. const startPos = this.state.start;
  10890. const startLoc = this.state.startLoc;
  10891. let val;
  10892. this.next();
  10893. this.expressionScope.enter(newArrowHeadScope());
  10894. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  10895. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  10896. this.state.maybeInArrowParameters = true;
  10897. this.state.inFSharpPipelineDirectBody = false;
  10898. const innerStartPos = this.state.start;
  10899. const innerStartLoc = this.state.startLoc;
  10900. const exprList = [];
  10901. const refExpressionErrors = new ExpressionErrors();
  10902. let first = true;
  10903. let spreadStart;
  10904. let optionalCommaStart;
  10905. while (!this.match(11)) {
  10906. if (first) {
  10907. first = false;
  10908. } else {
  10909. this.expect(12, refExpressionErrors.optionalParameters === -1 ? null : refExpressionErrors.optionalParameters);
  10910. if (this.match(11)) {
  10911. optionalCommaStart = this.state.start;
  10912. break;
  10913. }
  10914. }
  10915. if (this.match(21)) {
  10916. const spreadNodeStartPos = this.state.start;
  10917. const spreadNodeStartLoc = this.state.startLoc;
  10918. spreadStart = this.state.start;
  10919. exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartPos, spreadNodeStartLoc));
  10920. this.checkCommaAfterRest(41);
  10921. break;
  10922. } else {
  10923. exprList.push(this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem));
  10924. }
  10925. }
  10926. const innerEndPos = this.state.lastTokEnd;
  10927. const innerEndLoc = this.state.lastTokEndLoc;
  10928. this.expect(11);
  10929. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  10930. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  10931. let arrowNode = this.startNodeAt(startPos, startLoc);
  10932. if (canBeArrow && this.shouldParseArrow(exprList) && (arrowNode = this.parseArrow(arrowNode))) {
  10933. this.expressionScope.validateAsPattern();
  10934. this.expressionScope.exit();
  10935. this.parseArrowExpression(arrowNode, exprList, false);
  10936. return arrowNode;
  10937. }
  10938. this.expressionScope.exit();
  10939. if (!exprList.length) {
  10940. this.unexpected(this.state.lastTokStart);
  10941. }
  10942. if (optionalCommaStart) this.unexpected(optionalCommaStart);
  10943. if (spreadStart) this.unexpected(spreadStart);
  10944. this.checkExpressionErrors(refExpressionErrors, true);
  10945. this.toReferencedListDeep(exprList, true);
  10946. if (exprList.length > 1) {
  10947. val = this.startNodeAt(innerStartPos, innerStartLoc);
  10948. val.expressions = exprList;
  10949. this.finishNode(val, "SequenceExpression");
  10950. this.resetEndLocation(val, innerEndPos, innerEndLoc);
  10951. } else {
  10952. val = exprList[0];
  10953. }
  10954. if (!this.options.createParenthesizedExpressions) {
  10955. this.addExtra(val, "parenthesized", true);
  10956. this.addExtra(val, "parenStart", startPos);
  10957. this.takeSurroundingComments(val, startPos, this.state.lastTokEnd);
  10958. return val;
  10959. }
  10960. const parenExpression = this.startNodeAt(startPos, startLoc);
  10961. parenExpression.expression = val;
  10962. this.finishNode(parenExpression, "ParenthesizedExpression");
  10963. return parenExpression;
  10964. }
  10965. shouldParseArrow(params) {
  10966. return !this.canInsertSemicolon();
  10967. }
  10968. parseArrow(node) {
  10969. if (this.eat(19)) {
  10970. return node;
  10971. }
  10972. }
  10973. parseParenItem(node, startPos, startLoc) {
  10974. return node;
  10975. }
  10976. parseNewOrNewTarget() {
  10977. const node = this.startNode();
  10978. this.next();
  10979. if (this.match(16)) {
  10980. const meta = this.createIdentifier(this.startNodeAtNode(node), "new");
  10981. this.next();
  10982. const metaProp = this.parseMetaProperty(node, meta, "target");
  10983. if (!this.scope.inNonArrowFunction && !this.scope.inClass) {
  10984. this.raise(metaProp.start, ErrorMessages.UnexpectedNewTarget);
  10985. }
  10986. return metaProp;
  10987. }
  10988. return this.parseNew(node);
  10989. }
  10990. parseNew(node) {
  10991. node.callee = this.parseNoCallExpr();
  10992. if (node.callee.type === "Import") {
  10993. this.raise(node.callee.start, ErrorMessages.ImportCallNotNewExpression);
  10994. } else if (this.isOptionalChain(node.callee)) {
  10995. this.raise(this.state.lastTokEnd, ErrorMessages.OptionalChainingNoNew);
  10996. } else if (this.eat(18)) {
  10997. this.raise(this.state.start, ErrorMessages.OptionalChainingNoNew);
  10998. }
  10999. this.parseNewArguments(node);
  11000. return this.finishNode(node, "NewExpression");
  11001. }
  11002. parseNewArguments(node) {
  11003. if (this.eat(10)) {
  11004. const args = this.parseExprList(11);
  11005. this.toReferencedList(args);
  11006. node.arguments = args;
  11007. } else {
  11008. node.arguments = [];
  11009. }
  11010. }
  11011. parseTemplateElement(isTagged) {
  11012. const elem = this.startNode();
  11013. if (this.state.value === null) {
  11014. if (!isTagged) {
  11015. this.raise(this.state.start + 1, ErrorMessages.InvalidEscapeSequenceTemplate);
  11016. }
  11017. }
  11018. elem.value = {
  11019. raw: this.input.slice(this.state.start, this.state.end).replace(/\r\n?/g, "\n"),
  11020. cooked: this.state.value
  11021. };
  11022. this.next();
  11023. elem.tail = this.match(22);
  11024. return this.finishNode(elem, "TemplateElement");
  11025. }
  11026. parseTemplate(isTagged) {
  11027. const node = this.startNode();
  11028. this.next();
  11029. node.expressions = [];
  11030. let curElt = this.parseTemplateElement(isTagged);
  11031. node.quasis = [curElt];
  11032. while (!curElt.tail) {
  11033. this.expect(23);
  11034. node.expressions.push(this.parseTemplateSubstitution());
  11035. this.expect(8);
  11036. node.quasis.push(curElt = this.parseTemplateElement(isTagged));
  11037. }
  11038. this.next();
  11039. return this.finishNode(node, "TemplateLiteral");
  11040. }
  11041. parseTemplateSubstitution() {
  11042. return this.parseExpression();
  11043. }
  11044. parseObjectLike(close, isPattern, isRecord, refExpressionErrors) {
  11045. if (isRecord) {
  11046. this.expectPlugin("recordAndTuple");
  11047. }
  11048. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  11049. this.state.inFSharpPipelineDirectBody = false;
  11050. const propHash = Object.create(null);
  11051. let first = true;
  11052. const node = this.startNode();
  11053. node.properties = [];
  11054. this.next();
  11055. while (!this.match(close)) {
  11056. if (first) {
  11057. first = false;
  11058. } else {
  11059. this.expect(12);
  11060. if (this.match(close)) {
  11061. this.addExtra(node, "trailingComma", this.state.lastTokStart);
  11062. break;
  11063. }
  11064. }
  11065. let prop;
  11066. if (isPattern) {
  11067. prop = this.parseBindingProperty();
  11068. } else {
  11069. prop = this.parsePropertyDefinition(refExpressionErrors);
  11070. this.checkProto(prop, isRecord, propHash, refExpressionErrors);
  11071. }
  11072. if (isRecord && !this.isObjectProperty(prop) && prop.type !== "SpreadElement") {
  11073. this.raise(prop.start, ErrorMessages.InvalidRecordProperty);
  11074. }
  11075. if (prop.shorthand) {
  11076. this.addExtra(prop, "shorthand", true);
  11077. }
  11078. node.properties.push(prop);
  11079. }
  11080. this.next();
  11081. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  11082. let type = "ObjectExpression";
  11083. if (isPattern) {
  11084. type = "ObjectPattern";
  11085. } else if (isRecord) {
  11086. type = "RecordExpression";
  11087. }
  11088. return this.finishNode(node, type);
  11089. }
  11090. maybeAsyncOrAccessorProp(prop) {
  11091. return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(0) || this.match(49));
  11092. }
  11093. parsePropertyDefinition(refExpressionErrors) {
  11094. let decorators = [];
  11095. if (this.match(24)) {
  11096. if (this.hasPlugin("decorators")) {
  11097. this.raise(this.state.start, ErrorMessages.UnsupportedPropertyDecorator);
  11098. }
  11099. while (this.match(24)) {
  11100. decorators.push(this.parseDecorator());
  11101. }
  11102. }
  11103. const prop = this.startNode();
  11104. let isAsync = false;
  11105. let isAccessor = false;
  11106. let startPos;
  11107. let startLoc;
  11108. if (this.match(21)) {
  11109. if (decorators.length) this.unexpected();
  11110. return this.parseSpread();
  11111. }
  11112. if (decorators.length) {
  11113. prop.decorators = decorators;
  11114. decorators = [];
  11115. }
  11116. prop.method = false;
  11117. if (refExpressionErrors) {
  11118. startPos = this.state.start;
  11119. startLoc = this.state.startLoc;
  11120. }
  11121. let isGenerator = this.eat(49);
  11122. this.parsePropertyNamePrefixOperator(prop);
  11123. const containsEsc = this.state.containsEsc;
  11124. const key = this.parsePropertyName(prop);
  11125. if (!isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) {
  11126. const keyName = key.name;
  11127. if (keyName === "async" && !this.hasPrecedingLineBreak()) {
  11128. isAsync = true;
  11129. this.resetPreviousNodeTrailingComments(key);
  11130. isGenerator = this.eat(49);
  11131. this.parsePropertyName(prop);
  11132. }
  11133. if (keyName === "get" || keyName === "set") {
  11134. isAccessor = true;
  11135. this.resetPreviousNodeTrailingComments(key);
  11136. prop.kind = keyName;
  11137. if (this.match(49)) {
  11138. isGenerator = true;
  11139. this.raise(this.state.pos, ErrorMessages.AccessorIsGenerator, keyName);
  11140. this.next();
  11141. }
  11142. this.parsePropertyName(prop);
  11143. }
  11144. }
  11145. this.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, false, isAccessor, refExpressionErrors);
  11146. return prop;
  11147. }
  11148. getGetterSetterExpectedParamCount(method) {
  11149. return method.kind === "get" ? 0 : 1;
  11150. }
  11151. getObjectOrClassMethodParams(method) {
  11152. return method.params;
  11153. }
  11154. checkGetterSetterParams(method) {
  11155. var _params;
  11156. const paramCount = this.getGetterSetterExpectedParamCount(method);
  11157. const params = this.getObjectOrClassMethodParams(method);
  11158. const start = method.start;
  11159. if (params.length !== paramCount) {
  11160. if (method.kind === "get") {
  11161. this.raise(start, ErrorMessages.BadGetterArity);
  11162. } else {
  11163. this.raise(start, ErrorMessages.BadSetterArity);
  11164. }
  11165. }
  11166. if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") {
  11167. this.raise(start, ErrorMessages.BadSetterRestParameter);
  11168. }
  11169. }
  11170. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  11171. if (isAccessor) {
  11172. this.parseMethod(prop, isGenerator, false, false, false, "ObjectMethod");
  11173. this.checkGetterSetterParams(prop);
  11174. return prop;
  11175. }
  11176. if (isAsync || isGenerator || this.match(10)) {
  11177. if (isPattern) this.unexpected();
  11178. prop.kind = "method";
  11179. prop.method = true;
  11180. return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod");
  11181. }
  11182. }
  11183. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  11184. prop.shorthand = false;
  11185. if (this.eat(14)) {
  11186. prop.value = isPattern ? this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssignAllowIn(refExpressionErrors);
  11187. return this.finishNode(prop, "ObjectProperty");
  11188. }
  11189. if (!prop.computed && prop.key.type === "Identifier") {
  11190. this.checkReservedWord(prop.key.name, prop.key.start, true, false);
  11191. if (isPattern) {
  11192. prop.value = this.parseMaybeDefault(startPos, startLoc, cloneIdentifier(prop.key));
  11193. } else if (this.match(27) && refExpressionErrors) {
  11194. if (refExpressionErrors.shorthandAssign === -1) {
  11195. refExpressionErrors.shorthandAssign = this.state.start;
  11196. }
  11197. prop.value = this.parseMaybeDefault(startPos, startLoc, cloneIdentifier(prop.key));
  11198. } else {
  11199. prop.value = cloneIdentifier(prop.key);
  11200. }
  11201. prop.shorthand = true;
  11202. return this.finishNode(prop, "ObjectProperty");
  11203. }
  11204. }
  11205. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  11206. const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) || this.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  11207. if (!node) this.unexpected();
  11208. return node;
  11209. }
  11210. parsePropertyName(prop) {
  11211. if (this.eat(0)) {
  11212. prop.computed = true;
  11213. prop.key = this.parseMaybeAssignAllowIn();
  11214. this.expect(3);
  11215. } else {
  11216. const {
  11217. type,
  11218. value
  11219. } = this.state;
  11220. let key;
  11221. if (tokenIsKeywordOrIdentifier(type)) {
  11222. key = this.parseIdentifier(true);
  11223. } else {
  11224. switch (type) {
  11225. case 124:
  11226. key = this.parseNumericLiteral(value);
  11227. break;
  11228. case 123:
  11229. key = this.parseStringLiteral(value);
  11230. break;
  11231. case 125:
  11232. key = this.parseBigIntLiteral(value);
  11233. break;
  11234. case 126:
  11235. key = this.parseDecimalLiteral(value);
  11236. break;
  11237. case 128:
  11238. {
  11239. const privateKeyPos = this.state.start + 1;
  11240. this.raise(privateKeyPos, ErrorMessages.UnexpectedPrivateField);
  11241. key = this.parsePrivateName();
  11242. break;
  11243. }
  11244. default:
  11245. throw this.unexpected();
  11246. }
  11247. }
  11248. prop.key = key;
  11249. if (type !== 128) {
  11250. prop.computed = false;
  11251. }
  11252. }
  11253. return prop.key;
  11254. }
  11255. initFunction(node, isAsync) {
  11256. node.id = null;
  11257. node.generator = false;
  11258. node.async = !!isAsync;
  11259. }
  11260. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  11261. this.initFunction(node, isAsync);
  11262. node.generator = !!isGenerator;
  11263. const allowModifiers = isConstructor;
  11264. this.scope.enter(SCOPE_FUNCTION | SCOPE_SUPER | (inClassScope ? SCOPE_CLASS : 0) | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  11265. this.prodParam.enter(functionFlags(isAsync, node.generator));
  11266. this.parseFunctionParams(node, allowModifiers);
  11267. this.parseFunctionBodyAndFinish(node, type, true);
  11268. this.prodParam.exit();
  11269. this.scope.exit();
  11270. return node;
  11271. }
  11272. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  11273. if (isTuple) {
  11274. this.expectPlugin("recordAndTuple");
  11275. }
  11276. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  11277. this.state.inFSharpPipelineDirectBody = false;
  11278. const node = this.startNode();
  11279. this.next();
  11280. node.elements = this.parseExprList(close, !isTuple, refExpressionErrors, node);
  11281. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  11282. return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression");
  11283. }
  11284. parseArrowExpression(node, params, isAsync, trailingCommaPos) {
  11285. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  11286. let flags = functionFlags(isAsync, false);
  11287. if (!this.match(0) && this.prodParam.hasIn) {
  11288. flags |= PARAM_IN;
  11289. }
  11290. this.prodParam.enter(flags);
  11291. this.initFunction(node, isAsync);
  11292. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  11293. if (params) {
  11294. this.state.maybeInArrowParameters = true;
  11295. this.setArrowFunctionParameters(node, params, trailingCommaPos);
  11296. }
  11297. this.state.maybeInArrowParameters = false;
  11298. this.parseFunctionBody(node, true);
  11299. this.prodParam.exit();
  11300. this.scope.exit();
  11301. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  11302. return this.finishNode(node, "ArrowFunctionExpression");
  11303. }
  11304. setArrowFunctionParameters(node, params, trailingCommaPos) {
  11305. node.params = this.toAssignableList(params, trailingCommaPos, false);
  11306. }
  11307. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  11308. this.parseFunctionBody(node, false, isMethod);
  11309. this.finishNode(node, type);
  11310. }
  11311. parseFunctionBody(node, allowExpression, isMethod = false) {
  11312. const isExpression = allowExpression && !this.match(5);
  11313. this.expressionScope.enter(newExpressionScope());
  11314. if (isExpression) {
  11315. node.body = this.parseMaybeAssign();
  11316. this.checkParams(node, false, allowExpression, false);
  11317. } else {
  11318. const oldStrict = this.state.strict;
  11319. const oldLabels = this.state.labels;
  11320. this.state.labels = [];
  11321. this.prodParam.enter(this.prodParam.currentFlags() | PARAM_RETURN);
  11322. node.body = this.parseBlock(true, false, hasStrictModeDirective => {
  11323. const nonSimple = !this.isSimpleParamList(node.params);
  11324. if (hasStrictModeDirective && nonSimple) {
  11325. const errorPos = (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.end : node.start;
  11326. this.raise(errorPos, ErrorMessages.IllegalLanguageModeDirective);
  11327. }
  11328. const strictModeChanged = !oldStrict && this.state.strict;
  11329. this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged);
  11330. if (this.state.strict && node.id) {
  11331. this.checkLVal(node.id, "function name", BIND_OUTSIDE, undefined, undefined, strictModeChanged);
  11332. }
  11333. });
  11334. this.prodParam.exit();
  11335. this.state.labels = oldLabels;
  11336. }
  11337. this.expressionScope.exit();
  11338. }
  11339. isSimpleParamList(params) {
  11340. for (let i = 0, len = params.length; i < len; i++) {
  11341. if (params[i].type !== "Identifier") return false;
  11342. }
  11343. return true;
  11344. }
  11345. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  11346. const checkClashes = new Set();
  11347. for (const param of node.params) {
  11348. this.checkLVal(param, "function parameter list", BIND_VAR, allowDuplicates ? null : checkClashes, undefined, strictModeChanged);
  11349. }
  11350. }
  11351. parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) {
  11352. const elts = [];
  11353. let first = true;
  11354. while (!this.eat(close)) {
  11355. if (first) {
  11356. first = false;
  11357. } else {
  11358. this.expect(12);
  11359. if (this.match(close)) {
  11360. if (nodeForExtra) {
  11361. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  11362. }
  11363. this.next();
  11364. break;
  11365. }
  11366. }
  11367. elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors));
  11368. }
  11369. return elts;
  11370. }
  11371. parseExprListItem(allowEmpty, refExpressionErrors, allowPlaceholder) {
  11372. let elt;
  11373. if (this.match(12)) {
  11374. if (!allowEmpty) {
  11375. this.raise(this.state.pos, ErrorMessages.UnexpectedToken, ",");
  11376. }
  11377. elt = null;
  11378. } else if (this.match(21)) {
  11379. const spreadNodeStartPos = this.state.start;
  11380. const spreadNodeStartLoc = this.state.startLoc;
  11381. elt = this.parseParenItem(this.parseSpread(refExpressionErrors), spreadNodeStartPos, spreadNodeStartLoc);
  11382. } else if (this.match(17)) {
  11383. this.expectPlugin("partialApplication");
  11384. if (!allowPlaceholder) {
  11385. this.raise(this.state.start, ErrorMessages.UnexpectedArgumentPlaceholder);
  11386. }
  11387. const node = this.startNode();
  11388. this.next();
  11389. elt = this.finishNode(node, "ArgumentPlaceholder");
  11390. } else {
  11391. elt = this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem);
  11392. }
  11393. return elt;
  11394. }
  11395. parseIdentifier(liberal) {
  11396. const node = this.startNode();
  11397. const name = this.parseIdentifierName(node.start, liberal);
  11398. return this.createIdentifier(node, name);
  11399. }
  11400. createIdentifier(node, name) {
  11401. node.name = name;
  11402. node.loc.identifierName = name;
  11403. return this.finishNode(node, "Identifier");
  11404. }
  11405. parseIdentifierName(pos, liberal) {
  11406. let name;
  11407. const {
  11408. start,
  11409. type
  11410. } = this.state;
  11411. if (tokenIsKeywordOrIdentifier(type)) {
  11412. name = this.state.value;
  11413. } else {
  11414. throw this.unexpected();
  11415. }
  11416. const tokenIsKeyword = tokenKeywordOrIdentifierIsKeyword(type);
  11417. if (liberal) {
  11418. if (tokenIsKeyword) {
  11419. this.replaceToken(122);
  11420. }
  11421. } else {
  11422. this.checkReservedWord(name, start, tokenIsKeyword, false);
  11423. }
  11424. this.next();
  11425. return name;
  11426. }
  11427. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  11428. if (word.length > 10) {
  11429. return;
  11430. }
  11431. if (!canBeReservedWord(word)) {
  11432. return;
  11433. }
  11434. if (word === "yield") {
  11435. if (this.prodParam.hasYield) {
  11436. this.raise(startLoc, ErrorMessages.YieldBindingIdentifier);
  11437. return;
  11438. }
  11439. } else if (word === "await") {
  11440. if (this.prodParam.hasAwait) {
  11441. this.raise(startLoc, ErrorMessages.AwaitBindingIdentifier);
  11442. return;
  11443. } else if (this.scope.inStaticBlock) {
  11444. this.raise(startLoc, ErrorMessages.AwaitBindingIdentifierInStaticBlock);
  11445. return;
  11446. } else {
  11447. this.expressionScope.recordAsyncArrowParametersError(startLoc, ErrorMessages.AwaitBindingIdentifier);
  11448. }
  11449. } else if (word === "arguments") {
  11450. if (this.scope.inClassAndNotInNonArrowFunction) {
  11451. this.raise(startLoc, ErrorMessages.ArgumentsInClass);
  11452. return;
  11453. }
  11454. }
  11455. if (checkKeywords && isKeyword(word)) {
  11456. this.raise(startLoc, ErrorMessages.UnexpectedKeyword, word);
  11457. return;
  11458. }
  11459. const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord;
  11460. if (reservedTest(word, this.inModule)) {
  11461. this.raise(startLoc, ErrorMessages.UnexpectedReservedWord, word);
  11462. }
  11463. }
  11464. isAwaitAllowed() {
  11465. if (this.prodParam.hasAwait) return true;
  11466. if (this.options.allowAwaitOutsideFunction && !this.scope.inFunction) {
  11467. return true;
  11468. }
  11469. return false;
  11470. }
  11471. parseAwait(startPos, startLoc) {
  11472. const node = this.startNodeAt(startPos, startLoc);
  11473. this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.AwaitExpressionFormalParameter);
  11474. if (this.eat(49)) {
  11475. this.raise(node.start, ErrorMessages.ObsoleteAwaitStar);
  11476. }
  11477. if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) {
  11478. if (this.isAmbiguousAwait()) {
  11479. this.ambiguousScriptDifferentAst = true;
  11480. } else {
  11481. this.sawUnambiguousESM = true;
  11482. }
  11483. }
  11484. if (!this.state.soloAwait) {
  11485. node.argument = this.parseMaybeUnary(null, true);
  11486. }
  11487. return this.finishNode(node, "AwaitExpression");
  11488. }
  11489. isAmbiguousAwait() {
  11490. return this.hasPrecedingLineBreak() || this.match(47) || this.match(10) || this.match(0) || this.match(22) || this.match(127) || this.match(50) || this.hasPlugin("v8intrinsic") && this.match(48);
  11491. }
  11492. parseYield() {
  11493. const node = this.startNode();
  11494. this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.YieldInParameter);
  11495. this.next();
  11496. let delegating = false;
  11497. let argument = null;
  11498. if (!this.hasPrecedingLineBreak()) {
  11499. delegating = this.eat(49);
  11500. switch (this.state.type) {
  11501. case 13:
  11502. case 129:
  11503. case 8:
  11504. case 11:
  11505. case 3:
  11506. case 9:
  11507. case 14:
  11508. case 12:
  11509. if (!delegating) break;
  11510. default:
  11511. argument = this.parseMaybeAssign();
  11512. }
  11513. }
  11514. node.delegate = delegating;
  11515. node.argument = argument;
  11516. return this.finishNode(node, "YieldExpression");
  11517. }
  11518. checkPipelineAtInfixOperator(left, leftStartPos) {
  11519. if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
  11520. if (left.type === "SequenceExpression") {
  11521. this.raise(leftStartPos, ErrorMessages.PipelineHeadSequenceExpression);
  11522. }
  11523. }
  11524. }
  11525. checkHackPipeBodyEarlyErrors(startPos) {
  11526. if (!this.topicReferenceWasUsedInCurrentContext()) {
  11527. this.raise(startPos, ErrorMessages.PipeTopicUnused);
  11528. }
  11529. }
  11530. parseSmartPipelineBodyInStyle(childExpr, startPos, startLoc) {
  11531. const bodyNode = this.startNodeAt(startPos, startLoc);
  11532. if (this.isSimpleReference(childExpr)) {
  11533. bodyNode.callee = childExpr;
  11534. return this.finishNode(bodyNode, "PipelineBareFunction");
  11535. } else {
  11536. this.checkSmartPipeTopicBodyEarlyErrors(startPos);
  11537. bodyNode.expression = childExpr;
  11538. return this.finishNode(bodyNode, "PipelineTopicExpression");
  11539. }
  11540. }
  11541. isSimpleReference(expression) {
  11542. switch (expression.type) {
  11543. case "MemberExpression":
  11544. return !expression.computed && this.isSimpleReference(expression.object);
  11545. case "Identifier":
  11546. return true;
  11547. default:
  11548. return false;
  11549. }
  11550. }
  11551. checkSmartPipeTopicBodyEarlyErrors(startPos) {
  11552. if (this.match(19)) {
  11553. throw this.raise(this.state.start, ErrorMessages.PipelineBodyNoArrow);
  11554. } else if (!this.topicReferenceWasUsedInCurrentContext()) {
  11555. this.raise(startPos, ErrorMessages.PipelineTopicUnused);
  11556. }
  11557. }
  11558. withTopicBindingContext(callback) {
  11559. const outerContextTopicState = this.state.topicContext;
  11560. this.state.topicContext = {
  11561. maxNumOfResolvableTopics: 1,
  11562. maxTopicIndex: null
  11563. };
  11564. try {
  11565. return callback();
  11566. } finally {
  11567. this.state.topicContext = outerContextTopicState;
  11568. }
  11569. }
  11570. withSmartMixTopicForbiddingContext(callback) {
  11571. const proposal = this.getPluginOption("pipelineOperator", "proposal");
  11572. if (proposal === "smart") {
  11573. const outerContextTopicState = this.state.topicContext;
  11574. this.state.topicContext = {
  11575. maxNumOfResolvableTopics: 0,
  11576. maxTopicIndex: null
  11577. };
  11578. try {
  11579. return callback();
  11580. } finally {
  11581. this.state.topicContext = outerContextTopicState;
  11582. }
  11583. } else {
  11584. return callback();
  11585. }
  11586. }
  11587. withSoloAwaitPermittingContext(callback) {
  11588. const outerContextSoloAwaitState = this.state.soloAwait;
  11589. this.state.soloAwait = true;
  11590. try {
  11591. return callback();
  11592. } finally {
  11593. this.state.soloAwait = outerContextSoloAwaitState;
  11594. }
  11595. }
  11596. allowInAnd(callback) {
  11597. const flags = this.prodParam.currentFlags();
  11598. const prodParamToSet = PARAM_IN & ~flags;
  11599. if (prodParamToSet) {
  11600. this.prodParam.enter(flags | PARAM_IN);
  11601. try {
  11602. return callback();
  11603. } finally {
  11604. this.prodParam.exit();
  11605. }
  11606. }
  11607. return callback();
  11608. }
  11609. disallowInAnd(callback) {
  11610. const flags = this.prodParam.currentFlags();
  11611. const prodParamToClear = PARAM_IN & flags;
  11612. if (prodParamToClear) {
  11613. this.prodParam.enter(flags & ~PARAM_IN);
  11614. try {
  11615. return callback();
  11616. } finally {
  11617. this.prodParam.exit();
  11618. }
  11619. }
  11620. return callback();
  11621. }
  11622. registerTopicReference() {
  11623. this.state.topicContext.maxTopicIndex = 0;
  11624. }
  11625. topicReferenceIsAllowedInCurrentContext() {
  11626. return this.state.topicContext.maxNumOfResolvableTopics >= 1;
  11627. }
  11628. topicReferenceWasUsedInCurrentContext() {
  11629. return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0;
  11630. }
  11631. parseFSharpPipelineBody(prec) {
  11632. const startPos = this.state.start;
  11633. const startLoc = this.state.startLoc;
  11634. this.state.potentialArrowAt = this.state.start;
  11635. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  11636. this.state.inFSharpPipelineDirectBody = true;
  11637. const ret = this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startPos, startLoc, prec);
  11638. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  11639. return ret;
  11640. }
  11641. parseModuleExpression() {
  11642. this.expectPlugin("moduleBlocks");
  11643. const node = this.startNode();
  11644. this.next();
  11645. this.eat(5);
  11646. const revertScopes = this.initializeScopes(true);
  11647. this.enterInitialScopes();
  11648. const program = this.startNode();
  11649. try {
  11650. node.body = this.parseProgram(program, 8, "module");
  11651. } finally {
  11652. revertScopes();
  11653. }
  11654. this.eat(8);
  11655. return this.finishNode(node, "ModuleExpression");
  11656. }
  11657. parsePropertyNamePrefixOperator(prop) {}
  11658. }
  11659. const loopLabel = {
  11660. kind: "loop"
  11661. },
  11662. switchLabel = {
  11663. kind: "switch"
  11664. };
  11665. const FUNC_NO_FLAGS = 0b000,
  11666. FUNC_STATEMENT = 0b001,
  11667. FUNC_HANGING_STATEMENT = 0b010,
  11668. FUNC_NULLABLE_ID = 0b100;
  11669. const loneSurrogate = /[\uD800-\uDFFF]/u;
  11670. const keywordRelationalOperator = /in(?:stanceof)?/y;
  11671. function babel7CompatTokens(tokens) {
  11672. for (let i = 0; i < tokens.length; i++) {
  11673. const token = tokens[i];
  11674. const {
  11675. type
  11676. } = token;
  11677. if (type === 128) {
  11678. {
  11679. const {
  11680. loc,
  11681. start,
  11682. value,
  11683. end
  11684. } = token;
  11685. const hashEndPos = start + 1;
  11686. const hashEndLoc = new Position(loc.start.line, loc.start.column + 1);
  11687. tokens.splice(i, 1, new Token({
  11688. type: getExportedToken(25),
  11689. value: "#",
  11690. start: start,
  11691. end: hashEndPos,
  11692. startLoc: loc.start,
  11693. endLoc: hashEndLoc
  11694. }), new Token({
  11695. type: getExportedToken(122),
  11696. value: value,
  11697. start: hashEndPos,
  11698. end: end,
  11699. startLoc: hashEndLoc,
  11700. endLoc: loc.end
  11701. }));
  11702. i++;
  11703. continue;
  11704. }
  11705. }
  11706. if (typeof type === "number") {
  11707. token.type = getExportedToken(type);
  11708. }
  11709. }
  11710. return tokens;
  11711. }
  11712. class StatementParser extends ExpressionParser {
  11713. parseTopLevel(file, program) {
  11714. file.program = this.parseProgram(program);
  11715. file.comments = this.state.comments;
  11716. if (this.options.tokens) file.tokens = babel7CompatTokens(this.tokens);
  11717. return this.finishNode(file, "File");
  11718. }
  11719. parseProgram(program, end = 129, sourceType = this.options.sourceType) {
  11720. program.sourceType = sourceType;
  11721. program.interpreter = this.parseInterpreterDirective();
  11722. this.parseBlockBody(program, true, true, end);
  11723. if (this.inModule && !this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) {
  11724. for (const [name] of Array.from(this.scope.undefinedExports)) {
  11725. const pos = this.scope.undefinedExports.get(name);
  11726. this.raise(pos, ErrorMessages.ModuleExportUndefined, name);
  11727. }
  11728. }
  11729. return this.finishNode(program, "Program");
  11730. }
  11731. stmtToDirective(stmt) {
  11732. const directive = stmt;
  11733. directive.type = "Directive";
  11734. directive.value = directive.expression;
  11735. delete directive.expression;
  11736. const directiveLiteral = directive.value;
  11737. const expressionValue = directiveLiteral.value;
  11738. const raw = this.input.slice(directiveLiteral.start, directiveLiteral.end);
  11739. const val = directiveLiteral.value = raw.slice(1, -1);
  11740. this.addExtra(directiveLiteral, "raw", raw);
  11741. this.addExtra(directiveLiteral, "rawValue", val);
  11742. this.addExtra(directiveLiteral, "expressionValue", expressionValue);
  11743. directiveLiteral.type = "DirectiveLiteral";
  11744. return directive;
  11745. }
  11746. parseInterpreterDirective() {
  11747. if (!this.match(26)) {
  11748. return null;
  11749. }
  11750. const node = this.startNode();
  11751. node.value = this.state.value;
  11752. this.next();
  11753. return this.finishNode(node, "InterpreterDirective");
  11754. }
  11755. isLet(context) {
  11756. if (!this.isContextual(93)) {
  11757. return false;
  11758. }
  11759. return this.isLetKeyword(context);
  11760. }
  11761. isLetKeyword(context) {
  11762. const next = this.nextTokenStart();
  11763. const nextCh = this.codePointAtPos(next);
  11764. if (nextCh === 92 || nextCh === 91) {
  11765. return true;
  11766. }
  11767. if (context) return false;
  11768. if (nextCh === 123) return true;
  11769. if (isIdentifierStart(nextCh)) {
  11770. keywordRelationalOperator.lastIndex = next;
  11771. if (keywordRelationalOperator.test(this.input)) {
  11772. const endCh = this.codePointAtPos(keywordRelationalOperator.lastIndex);
  11773. if (!isIdentifierChar(endCh) && endCh !== 92) {
  11774. return false;
  11775. }
  11776. }
  11777. return true;
  11778. }
  11779. return false;
  11780. }
  11781. parseStatement(context, topLevel) {
  11782. if (this.match(24)) {
  11783. this.parseDecorators(true);
  11784. }
  11785. return this.parseStatementContent(context, topLevel);
  11786. }
  11787. parseStatementContent(context, topLevel) {
  11788. let starttype = this.state.type;
  11789. const node = this.startNode();
  11790. let kind;
  11791. if (this.isLet(context)) {
  11792. starttype = 68;
  11793. kind = "let";
  11794. }
  11795. switch (starttype) {
  11796. case 54:
  11797. return this.parseBreakContinueStatement(node, true);
  11798. case 57:
  11799. return this.parseBreakContinueStatement(node, false);
  11800. case 58:
  11801. return this.parseDebuggerStatement(node);
  11802. case 84:
  11803. return this.parseDoStatement(node);
  11804. case 85:
  11805. return this.parseForStatement(node);
  11806. case 62:
  11807. if (this.lookaheadCharCode() === 46) break;
  11808. if (context) {
  11809. if (this.state.strict) {
  11810. this.raise(this.state.start, ErrorMessages.StrictFunction);
  11811. } else if (context !== "if" && context !== "label") {
  11812. this.raise(this.state.start, ErrorMessages.SloppyFunction);
  11813. }
  11814. }
  11815. return this.parseFunctionStatement(node, false, !context);
  11816. case 74:
  11817. if (context) this.unexpected();
  11818. return this.parseClass(node, true);
  11819. case 63:
  11820. return this.parseIfStatement(node);
  11821. case 64:
  11822. return this.parseReturnStatement(node);
  11823. case 65:
  11824. return this.parseSwitchStatement(node);
  11825. case 66:
  11826. return this.parseThrowStatement(node);
  11827. case 67:
  11828. return this.parseTryStatement(node);
  11829. case 69:
  11830. case 68:
  11831. kind = kind || this.state.value;
  11832. if (context && kind !== "var") {
  11833. this.raise(this.state.start, ErrorMessages.UnexpectedLexicalDeclaration);
  11834. }
  11835. return this.parseVarStatement(node, kind);
  11836. case 86:
  11837. return this.parseWhileStatement(node);
  11838. case 70:
  11839. return this.parseWithStatement(node);
  11840. case 5:
  11841. return this.parseBlock();
  11842. case 13:
  11843. return this.parseEmptyStatement(node);
  11844. case 77:
  11845. {
  11846. const nextTokenCharCode = this.lookaheadCharCode();
  11847. if (nextTokenCharCode === 40 || nextTokenCharCode === 46) {
  11848. break;
  11849. }
  11850. }
  11851. case 76:
  11852. {
  11853. if (!this.options.allowImportExportEverywhere && !topLevel) {
  11854. this.raise(this.state.start, ErrorMessages.UnexpectedImportExport);
  11855. }
  11856. this.next();
  11857. let result;
  11858. if (starttype === 77) {
  11859. result = this.parseImport(node);
  11860. if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) {
  11861. this.sawUnambiguousESM = true;
  11862. }
  11863. } else {
  11864. result = this.parseExport(node);
  11865. if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") {
  11866. this.sawUnambiguousESM = true;
  11867. }
  11868. }
  11869. this.assertModuleNodeAllowed(node);
  11870. return result;
  11871. }
  11872. default:
  11873. {
  11874. if (this.isAsyncFunction()) {
  11875. if (context) {
  11876. this.raise(this.state.start, ErrorMessages.AsyncFunctionInSingleStatementContext);
  11877. }
  11878. this.next();
  11879. return this.parseFunctionStatement(node, true, !context);
  11880. }
  11881. }
  11882. }
  11883. const maybeName = this.state.value;
  11884. const expr = this.parseExpression();
  11885. if (tokenIsIdentifier(starttype) && expr.type === "Identifier" && this.eat(14)) {
  11886. return this.parseLabeledStatement(node, maybeName, expr, context);
  11887. } else {
  11888. return this.parseExpressionStatement(node, expr);
  11889. }
  11890. }
  11891. assertModuleNodeAllowed(node) {
  11892. if (!this.options.allowImportExportEverywhere && !this.inModule) {
  11893. this.raise(node.start, SourceTypeModuleErrorMessages.ImportOutsideModule);
  11894. }
  11895. }
  11896. takeDecorators(node) {
  11897. const decorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  11898. if (decorators.length) {
  11899. node.decorators = decorators;
  11900. this.resetStartLocationFromNode(node, decorators[0]);
  11901. this.state.decoratorStack[this.state.decoratorStack.length - 1] = [];
  11902. }
  11903. }
  11904. canHaveLeadingDecorator() {
  11905. return this.match(74);
  11906. }
  11907. parseDecorators(allowExport) {
  11908. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  11909. while (this.match(24)) {
  11910. const decorator = this.parseDecorator();
  11911. currentContextDecorators.push(decorator);
  11912. }
  11913. if (this.match(76)) {
  11914. if (!allowExport) {
  11915. this.unexpected();
  11916. }
  11917. if (this.hasPlugin("decorators") && !this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  11918. this.raise(this.state.start, ErrorMessages.DecoratorExportClass);
  11919. }
  11920. } else if (!this.canHaveLeadingDecorator()) {
  11921. throw this.raise(this.state.start, ErrorMessages.UnexpectedLeadingDecorator);
  11922. }
  11923. }
  11924. parseDecorator() {
  11925. this.expectOnePlugin(["decorators-legacy", "decorators"]);
  11926. const node = this.startNode();
  11927. this.next();
  11928. if (this.hasPlugin("decorators")) {
  11929. this.state.decoratorStack.push([]);
  11930. const startPos = this.state.start;
  11931. const startLoc = this.state.startLoc;
  11932. let expr;
  11933. if (this.eat(10)) {
  11934. expr = this.parseExpression();
  11935. this.expect(11);
  11936. } else {
  11937. expr = this.parseIdentifier(false);
  11938. while (this.eat(16)) {
  11939. const node = this.startNodeAt(startPos, startLoc);
  11940. node.object = expr;
  11941. node.property = this.parseIdentifier(true);
  11942. node.computed = false;
  11943. expr = this.finishNode(node, "MemberExpression");
  11944. }
  11945. }
  11946. node.expression = this.parseMaybeDecoratorArguments(expr);
  11947. this.state.decoratorStack.pop();
  11948. } else {
  11949. node.expression = this.parseExprSubscripts();
  11950. }
  11951. return this.finishNode(node, "Decorator");
  11952. }
  11953. parseMaybeDecoratorArguments(expr) {
  11954. if (this.eat(10)) {
  11955. const node = this.startNodeAtNode(expr);
  11956. node.callee = expr;
  11957. node.arguments = this.parseCallExpressionArguments(11, false);
  11958. this.toReferencedList(node.arguments);
  11959. return this.finishNode(node, "CallExpression");
  11960. }
  11961. return expr;
  11962. }
  11963. parseBreakContinueStatement(node, isBreak) {
  11964. this.next();
  11965. if (this.isLineTerminator()) {
  11966. node.label = null;
  11967. } else {
  11968. node.label = this.parseIdentifier();
  11969. this.semicolon();
  11970. }
  11971. this.verifyBreakContinue(node, isBreak);
  11972. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  11973. }
  11974. verifyBreakContinue(node, isBreak) {
  11975. let i;
  11976. for (i = 0; i < this.state.labels.length; ++i) {
  11977. const lab = this.state.labels[i];
  11978. if (node.label == null || lab.name === node.label.name) {
  11979. if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
  11980. if (node.label && isBreak) break;
  11981. }
  11982. }
  11983. if (i === this.state.labels.length) {
  11984. this.raise(node.start, ErrorMessages.IllegalBreakContinue, isBreak ? "break" : "continue");
  11985. }
  11986. }
  11987. parseDebuggerStatement(node) {
  11988. this.next();
  11989. this.semicolon();
  11990. return this.finishNode(node, "DebuggerStatement");
  11991. }
  11992. parseHeaderExpression() {
  11993. this.expect(10);
  11994. const val = this.parseExpression();
  11995. this.expect(11);
  11996. return val;
  11997. }
  11998. parseDoStatement(node) {
  11999. this.next();
  12000. this.state.labels.push(loopLabel);
  12001. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement("do"));
  12002. this.state.labels.pop();
  12003. this.expect(86);
  12004. node.test = this.parseHeaderExpression();
  12005. this.eat(13);
  12006. return this.finishNode(node, "DoWhileStatement");
  12007. }
  12008. parseForStatement(node) {
  12009. this.next();
  12010. this.state.labels.push(loopLabel);
  12011. let awaitAt = -1;
  12012. if (this.isAwaitAllowed() && this.eatContextual(90)) {
  12013. awaitAt = this.state.lastTokStart;
  12014. }
  12015. this.scope.enter(SCOPE_OTHER);
  12016. this.expect(10);
  12017. if (this.match(13)) {
  12018. if (awaitAt > -1) {
  12019. this.unexpected(awaitAt);
  12020. }
  12021. return this.parseFor(node, null);
  12022. }
  12023. const startsWithLet = this.isContextual(93);
  12024. const isLet = startsWithLet && this.isLetKeyword();
  12025. if (this.match(68) || this.match(69) || isLet) {
  12026. const init = this.startNode();
  12027. const kind = isLet ? "let" : this.state.value;
  12028. this.next();
  12029. this.parseVar(init, true, kind);
  12030. this.finishNode(init, "VariableDeclaration");
  12031. if ((this.match(52) || this.isContextual(95)) && init.declarations.length === 1) {
  12032. return this.parseForIn(node, init, awaitAt);
  12033. }
  12034. if (awaitAt > -1) {
  12035. this.unexpected(awaitAt);
  12036. }
  12037. return this.parseFor(node, init);
  12038. }
  12039. const startsWithAsync = this.isContextual(89);
  12040. const refExpressionErrors = new ExpressionErrors();
  12041. const init = this.parseExpression(true, refExpressionErrors);
  12042. const isForOf = this.isContextual(95);
  12043. if (isForOf) {
  12044. if (startsWithLet) {
  12045. this.raise(init.start, ErrorMessages.ForOfLet);
  12046. } else if (awaitAt === -1 && startsWithAsync && init.type === "Identifier") {
  12047. this.raise(init.start, ErrorMessages.ForOfAsync);
  12048. }
  12049. }
  12050. if (isForOf || this.match(52)) {
  12051. this.toAssignable(init, true);
  12052. const description = isForOf ? "for-of statement" : "for-in statement";
  12053. this.checkLVal(init, description);
  12054. return this.parseForIn(node, init, awaitAt);
  12055. } else {
  12056. this.checkExpressionErrors(refExpressionErrors, true);
  12057. }
  12058. if (awaitAt > -1) {
  12059. this.unexpected(awaitAt);
  12060. }
  12061. return this.parseFor(node, init);
  12062. }
  12063. parseFunctionStatement(node, isAsync, declarationPosition) {
  12064. this.next();
  12065. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), isAsync);
  12066. }
  12067. parseIfStatement(node) {
  12068. this.next();
  12069. node.test = this.parseHeaderExpression();
  12070. node.consequent = this.parseStatement("if");
  12071. node.alternate = this.eat(60) ? this.parseStatement("if") : null;
  12072. return this.finishNode(node, "IfStatement");
  12073. }
  12074. parseReturnStatement(node) {
  12075. if (!this.prodParam.hasReturn && !this.options.allowReturnOutsideFunction) {
  12076. this.raise(this.state.start, ErrorMessages.IllegalReturn);
  12077. }
  12078. this.next();
  12079. if (this.isLineTerminator()) {
  12080. node.argument = null;
  12081. } else {
  12082. node.argument = this.parseExpression();
  12083. this.semicolon();
  12084. }
  12085. return this.finishNode(node, "ReturnStatement");
  12086. }
  12087. parseSwitchStatement(node) {
  12088. this.next();
  12089. node.discriminant = this.parseHeaderExpression();
  12090. const cases = node.cases = [];
  12091. this.expect(5);
  12092. this.state.labels.push(switchLabel);
  12093. this.scope.enter(SCOPE_OTHER);
  12094. let cur;
  12095. for (let sawDefault; !this.match(8);) {
  12096. if (this.match(55) || this.match(59)) {
  12097. const isCase = this.match(55);
  12098. if (cur) this.finishNode(cur, "SwitchCase");
  12099. cases.push(cur = this.startNode());
  12100. cur.consequent = [];
  12101. this.next();
  12102. if (isCase) {
  12103. cur.test = this.parseExpression();
  12104. } else {
  12105. if (sawDefault) {
  12106. this.raise(this.state.lastTokStart, ErrorMessages.MultipleDefaultsInSwitch);
  12107. }
  12108. sawDefault = true;
  12109. cur.test = null;
  12110. }
  12111. this.expect(14);
  12112. } else {
  12113. if (cur) {
  12114. cur.consequent.push(this.parseStatement(null));
  12115. } else {
  12116. this.unexpected();
  12117. }
  12118. }
  12119. }
  12120. this.scope.exit();
  12121. if (cur) this.finishNode(cur, "SwitchCase");
  12122. this.next();
  12123. this.state.labels.pop();
  12124. return this.finishNode(node, "SwitchStatement");
  12125. }
  12126. parseThrowStatement(node) {
  12127. this.next();
  12128. if (this.hasPrecedingLineBreak()) {
  12129. this.raise(this.state.lastTokEnd, ErrorMessages.NewlineAfterThrow);
  12130. }
  12131. node.argument = this.parseExpression();
  12132. this.semicolon();
  12133. return this.finishNode(node, "ThrowStatement");
  12134. }
  12135. parseCatchClauseParam() {
  12136. const param = this.parseBindingAtom();
  12137. const simple = param.type === "Identifier";
  12138. this.scope.enter(simple ? SCOPE_SIMPLE_CATCH : 0);
  12139. this.checkLVal(param, "catch clause", BIND_LEXICAL);
  12140. return param;
  12141. }
  12142. parseTryStatement(node) {
  12143. this.next();
  12144. node.block = this.parseBlock();
  12145. node.handler = null;
  12146. if (this.match(56)) {
  12147. const clause = this.startNode();
  12148. this.next();
  12149. if (this.match(10)) {
  12150. this.expect(10);
  12151. clause.param = this.parseCatchClauseParam();
  12152. this.expect(11);
  12153. } else {
  12154. clause.param = null;
  12155. this.scope.enter(SCOPE_OTHER);
  12156. }
  12157. clause.body = this.withSmartMixTopicForbiddingContext(() => this.parseBlock(false, false));
  12158. this.scope.exit();
  12159. node.handler = this.finishNode(clause, "CatchClause");
  12160. }
  12161. node.finalizer = this.eat(61) ? this.parseBlock() : null;
  12162. if (!node.handler && !node.finalizer) {
  12163. this.raise(node.start, ErrorMessages.NoCatchOrFinally);
  12164. }
  12165. return this.finishNode(node, "TryStatement");
  12166. }
  12167. parseVarStatement(node, kind) {
  12168. this.next();
  12169. this.parseVar(node, false, kind);
  12170. this.semicolon();
  12171. return this.finishNode(node, "VariableDeclaration");
  12172. }
  12173. parseWhileStatement(node) {
  12174. this.next();
  12175. node.test = this.parseHeaderExpression();
  12176. this.state.labels.push(loopLabel);
  12177. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement("while"));
  12178. this.state.labels.pop();
  12179. return this.finishNode(node, "WhileStatement");
  12180. }
  12181. parseWithStatement(node) {
  12182. if (this.state.strict) {
  12183. this.raise(this.state.start, ErrorMessages.StrictWith);
  12184. }
  12185. this.next();
  12186. node.object = this.parseHeaderExpression();
  12187. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement("with"));
  12188. return this.finishNode(node, "WithStatement");
  12189. }
  12190. parseEmptyStatement(node) {
  12191. this.next();
  12192. return this.finishNode(node, "EmptyStatement");
  12193. }
  12194. parseLabeledStatement(node, maybeName, expr, context) {
  12195. for (const label of this.state.labels) {
  12196. if (label.name === maybeName) {
  12197. this.raise(expr.start, ErrorMessages.LabelRedeclaration, maybeName);
  12198. }
  12199. }
  12200. const kind = tokenIsLoop(this.state.type) ? "loop" : this.match(65) ? "switch" : null;
  12201. for (let i = this.state.labels.length - 1; i >= 0; i--) {
  12202. const label = this.state.labels[i];
  12203. if (label.statementStart === node.start) {
  12204. label.statementStart = this.state.start;
  12205. label.kind = kind;
  12206. } else {
  12207. break;
  12208. }
  12209. }
  12210. this.state.labels.push({
  12211. name: maybeName,
  12212. kind: kind,
  12213. statementStart: this.state.start
  12214. });
  12215. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  12216. this.state.labels.pop();
  12217. node.label = expr;
  12218. return this.finishNode(node, "LabeledStatement");
  12219. }
  12220. parseExpressionStatement(node, expr) {
  12221. node.expression = expr;
  12222. this.semicolon();
  12223. return this.finishNode(node, "ExpressionStatement");
  12224. }
  12225. parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) {
  12226. const node = this.startNode();
  12227. if (allowDirectives) {
  12228. this.state.strictErrors.clear();
  12229. }
  12230. this.expect(5);
  12231. if (createNewLexicalScope) {
  12232. this.scope.enter(SCOPE_OTHER);
  12233. }
  12234. this.parseBlockBody(node, allowDirectives, false, 8, afterBlockParse);
  12235. if (createNewLexicalScope) {
  12236. this.scope.exit();
  12237. }
  12238. return this.finishNode(node, "BlockStatement");
  12239. }
  12240. isValidDirective(stmt) {
  12241. return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized;
  12242. }
  12243. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  12244. const body = node.body = [];
  12245. const directives = node.directives = [];
  12246. this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse);
  12247. }
  12248. parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) {
  12249. const oldStrict = this.state.strict;
  12250. let hasStrictModeDirective = false;
  12251. let parsedNonDirective = false;
  12252. while (!this.match(end)) {
  12253. const stmt = this.parseStatement(null, topLevel);
  12254. if (directives && !parsedNonDirective) {
  12255. if (this.isValidDirective(stmt)) {
  12256. const directive = this.stmtToDirective(stmt);
  12257. directives.push(directive);
  12258. if (!hasStrictModeDirective && directive.value.value === "use strict") {
  12259. hasStrictModeDirective = true;
  12260. this.setStrict(true);
  12261. }
  12262. continue;
  12263. }
  12264. parsedNonDirective = true;
  12265. this.state.strictErrors.clear();
  12266. }
  12267. body.push(stmt);
  12268. }
  12269. if (afterBlockParse) {
  12270. afterBlockParse.call(this, hasStrictModeDirective);
  12271. }
  12272. if (!oldStrict) {
  12273. this.setStrict(false);
  12274. }
  12275. this.next();
  12276. }
  12277. parseFor(node, init) {
  12278. node.init = init;
  12279. this.semicolon(false);
  12280. node.test = this.match(13) ? null : this.parseExpression();
  12281. this.semicolon(false);
  12282. node.update = this.match(11) ? null : this.parseExpression();
  12283. this.expect(11);
  12284. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement("for"));
  12285. this.scope.exit();
  12286. this.state.labels.pop();
  12287. return this.finishNode(node, "ForStatement");
  12288. }
  12289. parseForIn(node, init, awaitAt) {
  12290. const isForIn = this.match(52);
  12291. this.next();
  12292. if (isForIn) {
  12293. if (awaitAt > -1) this.unexpected(awaitAt);
  12294. } else {
  12295. node.await = awaitAt > -1;
  12296. }
  12297. if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
  12298. this.raise(init.start, ErrorMessages.ForInOfLoopInitializer, isForIn ? "for-in" : "for-of");
  12299. } else if (init.type === "AssignmentPattern") {
  12300. this.raise(init.start, ErrorMessages.InvalidLhs, "for-loop");
  12301. }
  12302. node.left = init;
  12303. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn();
  12304. this.expect(11);
  12305. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement("for"));
  12306. this.scope.exit();
  12307. this.state.labels.pop();
  12308. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
  12309. }
  12310. parseVar(node, isFor, kind) {
  12311. const declarations = node.declarations = [];
  12312. const isTypescript = this.hasPlugin("typescript");
  12313. node.kind = kind;
  12314. for (;;) {
  12315. const decl = this.startNode();
  12316. this.parseVarId(decl, kind);
  12317. if (this.eat(27)) {
  12318. decl.init = isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn();
  12319. } else {
  12320. if (kind === "const" && !(this.match(52) || this.isContextual(95))) {
  12321. if (!isTypescript) {
  12322. this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Const declarations");
  12323. }
  12324. } else if (decl.id.type !== "Identifier" && !(isFor && (this.match(52) || this.isContextual(95)))) {
  12325. this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Complex binding patterns");
  12326. }
  12327. decl.init = null;
  12328. }
  12329. declarations.push(this.finishNode(decl, "VariableDeclarator"));
  12330. if (!this.eat(12)) break;
  12331. }
  12332. return node;
  12333. }
  12334. parseVarId(decl, kind) {
  12335. decl.id = this.parseBindingAtom();
  12336. this.checkLVal(decl.id, "variable declaration", kind === "var" ? BIND_VAR : BIND_LEXICAL, undefined, kind !== "var");
  12337. }
  12338. parseFunction(node, statement = FUNC_NO_FLAGS, isAsync = false) {
  12339. const isStatement = statement & FUNC_STATEMENT;
  12340. const isHangingStatement = statement & FUNC_HANGING_STATEMENT;
  12341. const requireId = !!isStatement && !(statement & FUNC_NULLABLE_ID);
  12342. this.initFunction(node, isAsync);
  12343. if (this.match(49) && isHangingStatement) {
  12344. this.raise(this.state.start, ErrorMessages.GeneratorInSingleStatementContext);
  12345. }
  12346. node.generator = this.eat(49);
  12347. if (isStatement) {
  12348. node.id = this.parseFunctionId(requireId);
  12349. }
  12350. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  12351. this.state.maybeInArrowParameters = false;
  12352. this.scope.enter(SCOPE_FUNCTION);
  12353. this.prodParam.enter(functionFlags(isAsync, node.generator));
  12354. if (!isStatement) {
  12355. node.id = this.parseFunctionId();
  12356. }
  12357. this.parseFunctionParams(node, false);
  12358. this.withSmartMixTopicForbiddingContext(() => {
  12359. this.parseFunctionBodyAndFinish(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
  12360. });
  12361. this.prodParam.exit();
  12362. this.scope.exit();
  12363. if (isStatement && !isHangingStatement) {
  12364. this.registerFunctionStatementId(node);
  12365. }
  12366. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  12367. return node;
  12368. }
  12369. parseFunctionId(requireId) {
  12370. return requireId || tokenIsIdentifier(this.state.type) ? this.parseIdentifier() : null;
  12371. }
  12372. parseFunctionParams(node, allowModifiers) {
  12373. this.expect(10);
  12374. this.expressionScope.enter(newParameterDeclarationScope());
  12375. node.params = this.parseBindingList(11, 41, false, allowModifiers);
  12376. this.expressionScope.exit();
  12377. }
  12378. registerFunctionStatementId(node) {
  12379. if (!node.id) return;
  12380. this.scope.declareName(node.id.name, this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION, node.id.start);
  12381. }
  12382. parseClass(node, isStatement, optionalId) {
  12383. this.next();
  12384. this.takeDecorators(node);
  12385. const oldStrict = this.state.strict;
  12386. this.state.strict = true;
  12387. this.parseClassId(node, isStatement, optionalId);
  12388. this.parseClassSuper(node);
  12389. node.body = this.parseClassBody(!!node.superClass, oldStrict);
  12390. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
  12391. }
  12392. isClassProperty() {
  12393. return this.match(27) || this.match(13) || this.match(8);
  12394. }
  12395. isClassMethod() {
  12396. return this.match(10);
  12397. }
  12398. isNonstaticConstructor(method) {
  12399. return !method.computed && !method.static && (method.key.name === "constructor" || method.key.value === "constructor");
  12400. }
  12401. parseClassBody(hadSuperClass, oldStrict) {
  12402. this.classScope.enter();
  12403. const state = {
  12404. hadConstructor: false,
  12405. hadSuperClass
  12406. };
  12407. let decorators = [];
  12408. const classBody = this.startNode();
  12409. classBody.body = [];
  12410. this.expect(5);
  12411. this.withSmartMixTopicForbiddingContext(() => {
  12412. while (!this.match(8)) {
  12413. if (this.eat(13)) {
  12414. if (decorators.length > 0) {
  12415. throw this.raise(this.state.lastTokEnd, ErrorMessages.DecoratorSemicolon);
  12416. }
  12417. continue;
  12418. }
  12419. if (this.match(24)) {
  12420. decorators.push(this.parseDecorator());
  12421. continue;
  12422. }
  12423. const member = this.startNode();
  12424. if (decorators.length) {
  12425. member.decorators = decorators;
  12426. this.resetStartLocationFromNode(member, decorators[0]);
  12427. decorators = [];
  12428. }
  12429. this.parseClassMember(classBody, member, state);
  12430. if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) {
  12431. this.raise(member.start, ErrorMessages.DecoratorConstructor);
  12432. }
  12433. }
  12434. });
  12435. this.state.strict = oldStrict;
  12436. this.next();
  12437. if (decorators.length) {
  12438. throw this.raise(this.state.start, ErrorMessages.TrailingDecorator);
  12439. }
  12440. this.classScope.exit();
  12441. return this.finishNode(classBody, "ClassBody");
  12442. }
  12443. parseClassMemberFromModifier(classBody, member) {
  12444. const key = this.parseIdentifier(true);
  12445. if (this.isClassMethod()) {
  12446. const method = member;
  12447. method.kind = "method";
  12448. method.computed = false;
  12449. method.key = key;
  12450. method.static = false;
  12451. this.pushClassMethod(classBody, method, false, false, false, false);
  12452. return true;
  12453. } else if (this.isClassProperty()) {
  12454. const prop = member;
  12455. prop.computed = false;
  12456. prop.key = key;
  12457. prop.static = false;
  12458. classBody.body.push(this.parseClassProperty(prop));
  12459. return true;
  12460. }
  12461. this.resetPreviousNodeTrailingComments(key);
  12462. return false;
  12463. }
  12464. parseClassMember(classBody, member, state) {
  12465. const isStatic = this.isContextual(98);
  12466. if (isStatic) {
  12467. if (this.parseClassMemberFromModifier(classBody, member)) {
  12468. return;
  12469. }
  12470. if (this.eat(5)) {
  12471. this.parseClassStaticBlock(classBody, member);
  12472. return;
  12473. }
  12474. }
  12475. this.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  12476. }
  12477. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  12478. const publicMethod = member;
  12479. const privateMethod = member;
  12480. const publicProp = member;
  12481. const privateProp = member;
  12482. const method = publicMethod;
  12483. const publicMember = publicMethod;
  12484. member.static = isStatic;
  12485. this.parsePropertyNamePrefixOperator(member);
  12486. if (this.eat(49)) {
  12487. method.kind = "method";
  12488. const isPrivateName = this.match(128);
  12489. this.parseClassElementName(method);
  12490. if (isPrivateName) {
  12491. this.pushClassPrivateMethod(classBody, privateMethod, true, false);
  12492. return;
  12493. }
  12494. if (this.isNonstaticConstructor(publicMethod)) {
  12495. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsGenerator);
  12496. }
  12497. this.pushClassMethod(classBody, publicMethod, true, false, false, false);
  12498. return;
  12499. }
  12500. const isContextual = tokenIsIdentifier(this.state.type) && !this.state.containsEsc;
  12501. const isPrivate = this.match(128);
  12502. const key = this.parseClassElementName(member);
  12503. const maybeQuestionTokenStart = this.state.start;
  12504. this.parsePostMemberNameModifiers(publicMember);
  12505. if (this.isClassMethod()) {
  12506. method.kind = "method";
  12507. if (isPrivate) {
  12508. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  12509. return;
  12510. }
  12511. const isConstructor = this.isNonstaticConstructor(publicMethod);
  12512. let allowsDirectSuper = false;
  12513. if (isConstructor) {
  12514. publicMethod.kind = "constructor";
  12515. if (state.hadConstructor && !this.hasPlugin("typescript")) {
  12516. this.raise(key.start, ErrorMessages.DuplicateConstructor);
  12517. }
  12518. if (isConstructor && this.hasPlugin("typescript") && member.override) {
  12519. this.raise(key.start, ErrorMessages.OverrideOnConstructor);
  12520. }
  12521. state.hadConstructor = true;
  12522. allowsDirectSuper = state.hadSuperClass;
  12523. }
  12524. this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper);
  12525. } else if (this.isClassProperty()) {
  12526. if (isPrivate) {
  12527. this.pushClassPrivateProperty(classBody, privateProp);
  12528. } else {
  12529. this.pushClassProperty(classBody, publicProp);
  12530. }
  12531. } else if (isContextual && key.name === "async" && !this.isLineTerminator()) {
  12532. this.resetPreviousNodeTrailingComments(key);
  12533. const isGenerator = this.eat(49);
  12534. if (publicMember.optional) {
  12535. this.unexpected(maybeQuestionTokenStart);
  12536. }
  12537. method.kind = "method";
  12538. const isPrivate = this.match(128);
  12539. this.parseClassElementName(method);
  12540. this.parsePostMemberNameModifiers(publicMember);
  12541. if (isPrivate) {
  12542. this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true);
  12543. } else {
  12544. if (this.isNonstaticConstructor(publicMethod)) {
  12545. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAsync);
  12546. }
  12547. this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false);
  12548. }
  12549. } else if (isContextual && (key.name === "get" || key.name === "set") && !(this.match(49) && this.isLineTerminator())) {
  12550. this.resetPreviousNodeTrailingComments(key);
  12551. method.kind = key.name;
  12552. const isPrivate = this.match(128);
  12553. this.parseClassElementName(publicMethod);
  12554. if (isPrivate) {
  12555. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  12556. } else {
  12557. if (this.isNonstaticConstructor(publicMethod)) {
  12558. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAccessor);
  12559. }
  12560. this.pushClassMethod(classBody, publicMethod, false, false, false, false);
  12561. }
  12562. this.checkGetterSetterParams(publicMethod);
  12563. } else if (this.isLineTerminator()) {
  12564. if (isPrivate) {
  12565. this.pushClassPrivateProperty(classBody, privateProp);
  12566. } else {
  12567. this.pushClassProperty(classBody, publicProp);
  12568. }
  12569. } else {
  12570. this.unexpected();
  12571. }
  12572. }
  12573. parseClassElementName(member) {
  12574. const {
  12575. type,
  12576. value,
  12577. start
  12578. } = this.state;
  12579. if ((type === 122 || type === 123) && member.static && value === "prototype") {
  12580. this.raise(start, ErrorMessages.StaticPrototype);
  12581. }
  12582. if (type === 128) {
  12583. if (value === "constructor") {
  12584. this.raise(start, ErrorMessages.ConstructorClassPrivateField);
  12585. }
  12586. const key = this.parsePrivateName();
  12587. member.key = key;
  12588. return key;
  12589. }
  12590. return this.parsePropertyName(member);
  12591. }
  12592. parseClassStaticBlock(classBody, member) {
  12593. var _member$decorators;
  12594. this.scope.enter(SCOPE_CLASS | SCOPE_STATIC_BLOCK | SCOPE_SUPER);
  12595. const oldLabels = this.state.labels;
  12596. this.state.labels = [];
  12597. this.prodParam.enter(PARAM);
  12598. const body = member.body = [];
  12599. this.parseBlockOrModuleBlockBody(body, undefined, false, 8);
  12600. this.prodParam.exit();
  12601. this.scope.exit();
  12602. this.state.labels = oldLabels;
  12603. classBody.body.push(this.finishNode(member, "StaticBlock"));
  12604. if ((_member$decorators = member.decorators) != null && _member$decorators.length) {
  12605. this.raise(member.start, ErrorMessages.DecoratorStaticBlock);
  12606. }
  12607. }
  12608. pushClassProperty(classBody, prop) {
  12609. if (!prop.computed && (prop.key.name === "constructor" || prop.key.value === "constructor")) {
  12610. this.raise(prop.key.start, ErrorMessages.ConstructorClassField);
  12611. }
  12612. classBody.body.push(this.parseClassProperty(prop));
  12613. }
  12614. pushClassPrivateProperty(classBody, prop) {
  12615. const node = this.parseClassPrivateProperty(prop);
  12616. classBody.body.push(node);
  12617. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), CLASS_ELEMENT_OTHER, node.key.start);
  12618. }
  12619. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  12620. classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true));
  12621. }
  12622. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  12623. const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true);
  12624. classBody.body.push(node);
  12625. const kind = node.kind === "get" ? node.static ? CLASS_ELEMENT_STATIC_GETTER : CLASS_ELEMENT_INSTANCE_GETTER : node.kind === "set" ? node.static ? CLASS_ELEMENT_STATIC_SETTER : CLASS_ELEMENT_INSTANCE_SETTER : CLASS_ELEMENT_OTHER;
  12626. this.declareClassPrivateMethodInScope(node, kind);
  12627. }
  12628. declareClassPrivateMethodInScope(node, kind) {
  12629. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), kind, node.key.start);
  12630. }
  12631. parsePostMemberNameModifiers(methodOrProp) {}
  12632. parseClassPrivateProperty(node) {
  12633. this.parseInitializer(node);
  12634. this.semicolon();
  12635. return this.finishNode(node, "ClassPrivateProperty");
  12636. }
  12637. parseClassProperty(node) {
  12638. this.parseInitializer(node);
  12639. this.semicolon();
  12640. return this.finishNode(node, "ClassProperty");
  12641. }
  12642. parseInitializer(node) {
  12643. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  12644. this.expressionScope.enter(newExpressionScope());
  12645. this.prodParam.enter(PARAM);
  12646. node.value = this.eat(27) ? this.parseMaybeAssignAllowIn() : null;
  12647. this.expressionScope.exit();
  12648. this.prodParam.exit();
  12649. this.scope.exit();
  12650. }
  12651. parseClassId(node, isStatement, optionalId, bindingType = BIND_CLASS) {
  12652. if (tokenIsIdentifier(this.state.type)) {
  12653. node.id = this.parseIdentifier();
  12654. if (isStatement) {
  12655. this.checkLVal(node.id, "class name", bindingType);
  12656. }
  12657. } else {
  12658. if (optionalId || !isStatement) {
  12659. node.id = null;
  12660. } else {
  12661. this.unexpected(null, ErrorMessages.MissingClassName);
  12662. }
  12663. }
  12664. }
  12665. parseClassSuper(node) {
  12666. node.superClass = this.eat(75) ? this.parseExprSubscripts() : null;
  12667. }
  12668. parseExport(node) {
  12669. const hasDefault = this.maybeParseExportDefaultSpecifier(node);
  12670. const parseAfterDefault = !hasDefault || this.eat(12);
  12671. const hasStar = parseAfterDefault && this.eatExportStar(node);
  12672. const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node);
  12673. const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(12));
  12674. const isFromRequired = hasDefault || hasStar;
  12675. if (hasStar && !hasNamespace) {
  12676. if (hasDefault) this.unexpected();
  12677. this.parseExportFrom(node, true);
  12678. return this.finishNode(node, "ExportAllDeclaration");
  12679. }
  12680. const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node);
  12681. if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers || hasNamespace && parseAfterNamespace && !hasSpecifiers) {
  12682. throw this.unexpected(null, 5);
  12683. }
  12684. let hasDeclaration;
  12685. if (isFromRequired || hasSpecifiers) {
  12686. hasDeclaration = false;
  12687. this.parseExportFrom(node, isFromRequired);
  12688. } else {
  12689. hasDeclaration = this.maybeParseExportDeclaration(node);
  12690. }
  12691. if (isFromRequired || hasSpecifiers || hasDeclaration) {
  12692. this.checkExport(node, true, false, !!node.source);
  12693. return this.finishNode(node, "ExportNamedDeclaration");
  12694. }
  12695. if (this.eat(59)) {
  12696. node.declaration = this.parseExportDefaultExpression();
  12697. this.checkExport(node, true, true);
  12698. return this.finishNode(node, "ExportDefaultDeclaration");
  12699. }
  12700. throw this.unexpected(null, 5);
  12701. }
  12702. eatExportStar(node) {
  12703. return this.eat(49);
  12704. }
  12705. maybeParseExportDefaultSpecifier(node) {
  12706. if (this.isExportDefaultSpecifier()) {
  12707. this.expectPlugin("exportDefaultFrom");
  12708. const specifier = this.startNode();
  12709. specifier.exported = this.parseIdentifier(true);
  12710. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  12711. return true;
  12712. }
  12713. return false;
  12714. }
  12715. maybeParseExportNamespaceSpecifier(node) {
  12716. if (this.isContextual(87)) {
  12717. if (!node.specifiers) node.specifiers = [];
  12718. const specifier = this.startNodeAt(this.state.lastTokStart, this.state.lastTokStartLoc);
  12719. this.next();
  12720. specifier.exported = this.parseModuleExportName();
  12721. node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
  12722. return true;
  12723. }
  12724. return false;
  12725. }
  12726. maybeParseExportNamedSpecifiers(node) {
  12727. if (this.match(5)) {
  12728. if (!node.specifiers) node.specifiers = [];
  12729. const isTypeExport = node.exportKind === "type";
  12730. node.specifiers.push(...this.parseExportSpecifiers(isTypeExport));
  12731. node.source = null;
  12732. node.declaration = null;
  12733. if (this.hasPlugin("importAssertions")) {
  12734. node.assertions = [];
  12735. }
  12736. return true;
  12737. }
  12738. return false;
  12739. }
  12740. maybeParseExportDeclaration(node) {
  12741. if (this.shouldParseExportDeclaration()) {
  12742. node.specifiers = [];
  12743. node.source = null;
  12744. if (this.hasPlugin("importAssertions")) {
  12745. node.assertions = [];
  12746. }
  12747. node.declaration = this.parseExportDeclaration(node);
  12748. return true;
  12749. }
  12750. return false;
  12751. }
  12752. isAsyncFunction() {
  12753. if (!this.isContextual(89)) return false;
  12754. const next = this.nextTokenStart();
  12755. return !lineBreak.test(this.input.slice(this.state.pos, next)) && this.isUnparsedContextual(next, "function");
  12756. }
  12757. parseExportDefaultExpression() {
  12758. const expr = this.startNode();
  12759. const isAsync = this.isAsyncFunction();
  12760. if (this.match(62) || isAsync) {
  12761. this.next();
  12762. if (isAsync) {
  12763. this.next();
  12764. }
  12765. return this.parseFunction(expr, FUNC_STATEMENT | FUNC_NULLABLE_ID, isAsync);
  12766. } else if (this.match(74)) {
  12767. return this.parseClass(expr, true, true);
  12768. } else if (this.match(24)) {
  12769. if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  12770. this.raise(this.state.start, ErrorMessages.DecoratorBeforeExport);
  12771. }
  12772. this.parseDecorators(false);
  12773. return this.parseClass(expr, true, true);
  12774. } else if (this.match(69) || this.match(68) || this.isLet()) {
  12775. throw this.raise(this.state.start, ErrorMessages.UnsupportedDefaultExport);
  12776. } else {
  12777. const res = this.parseMaybeAssignAllowIn();
  12778. this.semicolon();
  12779. return res;
  12780. }
  12781. }
  12782. parseExportDeclaration(node) {
  12783. return this.parseStatement(null);
  12784. }
  12785. isExportDefaultSpecifier() {
  12786. const {
  12787. type
  12788. } = this.state;
  12789. if (tokenIsIdentifier(type)) {
  12790. if (type === 89 && !this.state.containsEsc || type === 93) {
  12791. return false;
  12792. }
  12793. if ((type === 120 || type === 119) && !this.state.containsEsc) {
  12794. const {
  12795. type: nextType
  12796. } = this.lookahead();
  12797. if (tokenIsIdentifier(nextType) && nextType !== 91 || nextType === 5) {
  12798. this.expectOnePlugin(["flow", "typescript"]);
  12799. return false;
  12800. }
  12801. }
  12802. } else if (!this.match(59)) {
  12803. return false;
  12804. }
  12805. const next = this.nextTokenStart();
  12806. const hasFrom = this.isUnparsedContextual(next, "from");
  12807. if (this.input.charCodeAt(next) === 44 || tokenIsIdentifier(this.state.type) && hasFrom) {
  12808. return true;
  12809. }
  12810. if (this.match(59) && hasFrom) {
  12811. const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4));
  12812. return nextAfterFrom === 34 || nextAfterFrom === 39;
  12813. }
  12814. return false;
  12815. }
  12816. parseExportFrom(node, expect) {
  12817. if (this.eatContextual(91)) {
  12818. node.source = this.parseImportSource();
  12819. this.checkExport(node);
  12820. const assertions = this.maybeParseImportAssertions();
  12821. if (assertions) {
  12822. node.assertions = assertions;
  12823. }
  12824. } else if (expect) {
  12825. this.unexpected();
  12826. }
  12827. this.semicolon();
  12828. }
  12829. shouldParseExportDeclaration() {
  12830. const {
  12831. type
  12832. } = this.state;
  12833. if (type === 24) {
  12834. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  12835. if (this.hasPlugin("decorators")) {
  12836. if (this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  12837. this.unexpected(this.state.start, ErrorMessages.DecoratorBeforeExport);
  12838. } else {
  12839. return true;
  12840. }
  12841. }
  12842. }
  12843. return type === 68 || type === 69 || type === 62 || type === 74 || this.isLet() || this.isAsyncFunction();
  12844. }
  12845. checkExport(node, checkNames, isDefault, isFrom) {
  12846. if (checkNames) {
  12847. if (isDefault) {
  12848. this.checkDuplicateExports(node, "default");
  12849. if (this.hasPlugin("exportDefaultFrom")) {
  12850. var _declaration$extra;
  12851. const declaration = node.declaration;
  12852. if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 && !((_declaration$extra = declaration.extra) != null && _declaration$extra.parenthesized)) {
  12853. this.raise(declaration.start, ErrorMessages.ExportDefaultFromAsIdentifier);
  12854. }
  12855. }
  12856. } else if (node.specifiers && node.specifiers.length) {
  12857. for (const specifier of node.specifiers) {
  12858. const {
  12859. exported
  12860. } = specifier;
  12861. const exportedName = exported.type === "Identifier" ? exported.name : exported.value;
  12862. this.checkDuplicateExports(specifier, exportedName);
  12863. if (!isFrom && specifier.local) {
  12864. const {
  12865. local
  12866. } = specifier;
  12867. if (local.type !== "Identifier") {
  12868. this.raise(specifier.start, ErrorMessages.ExportBindingIsString, local.value, exportedName);
  12869. } else {
  12870. this.checkReservedWord(local.name, local.start, true, false);
  12871. this.scope.checkLocalExport(local);
  12872. }
  12873. }
  12874. }
  12875. } else if (node.declaration) {
  12876. if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") {
  12877. const id = node.declaration.id;
  12878. if (!id) throw new Error("Assertion failure");
  12879. this.checkDuplicateExports(node, id.name);
  12880. } else if (node.declaration.type === "VariableDeclaration") {
  12881. for (const declaration of node.declaration.declarations) {
  12882. this.checkDeclaration(declaration.id);
  12883. }
  12884. }
  12885. }
  12886. }
  12887. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  12888. if (currentContextDecorators.length) {
  12889. throw this.raise(node.start, ErrorMessages.UnsupportedDecoratorExport);
  12890. }
  12891. }
  12892. checkDeclaration(node) {
  12893. if (node.type === "Identifier") {
  12894. this.checkDuplicateExports(node, node.name);
  12895. } else if (node.type === "ObjectPattern") {
  12896. for (const prop of node.properties) {
  12897. this.checkDeclaration(prop);
  12898. }
  12899. } else if (node.type === "ArrayPattern") {
  12900. for (const elem of node.elements) {
  12901. if (elem) {
  12902. this.checkDeclaration(elem);
  12903. }
  12904. }
  12905. } else if (node.type === "ObjectProperty") {
  12906. this.checkDeclaration(node.value);
  12907. } else if (node.type === "RestElement") {
  12908. this.checkDeclaration(node.argument);
  12909. } else if (node.type === "AssignmentPattern") {
  12910. this.checkDeclaration(node.left);
  12911. }
  12912. }
  12913. checkDuplicateExports(node, name) {
  12914. if (this.exportedIdentifiers.has(name)) {
  12915. this.raise(node.start, name === "default" ? ErrorMessages.DuplicateDefaultExport : ErrorMessages.DuplicateExport, name);
  12916. }
  12917. this.exportedIdentifiers.add(name);
  12918. }
  12919. parseExportSpecifiers(isInTypeExport) {
  12920. const nodes = [];
  12921. let first = true;
  12922. this.expect(5);
  12923. while (!this.eat(8)) {
  12924. if (first) {
  12925. first = false;
  12926. } else {
  12927. this.expect(12);
  12928. if (this.eat(8)) break;
  12929. }
  12930. const isMaybeTypeOnly = this.isContextual(120);
  12931. const isString = this.match(123);
  12932. const node = this.startNode();
  12933. node.local = this.parseModuleExportName();
  12934. nodes.push(this.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly));
  12935. }
  12936. return nodes;
  12937. }
  12938. parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) {
  12939. if (this.eatContextual(87)) {
  12940. node.exported = this.parseModuleExportName();
  12941. } else if (isString) {
  12942. node.exported = cloneStringLiteral(node.local);
  12943. } else if (!node.exported) {
  12944. node.exported = cloneIdentifier(node.local);
  12945. }
  12946. return this.finishNode(node, "ExportSpecifier");
  12947. }
  12948. parseModuleExportName() {
  12949. if (this.match(123)) {
  12950. const result = this.parseStringLiteral(this.state.value);
  12951. const surrogate = result.value.match(loneSurrogate);
  12952. if (surrogate) {
  12953. this.raise(result.start, ErrorMessages.ModuleExportNameHasLoneSurrogate, surrogate[0].charCodeAt(0).toString(16));
  12954. }
  12955. return result;
  12956. }
  12957. return this.parseIdentifier(true);
  12958. }
  12959. parseImport(node) {
  12960. node.specifiers = [];
  12961. if (!this.match(123)) {
  12962. const hasDefault = this.maybeParseDefaultImportSpecifier(node);
  12963. const parseNext = !hasDefault || this.eat(12);
  12964. const hasStar = parseNext && this.maybeParseStarImportSpecifier(node);
  12965. if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node);
  12966. this.expectContextual(91);
  12967. }
  12968. node.source = this.parseImportSource();
  12969. const assertions = this.maybeParseImportAssertions();
  12970. if (assertions) {
  12971. node.assertions = assertions;
  12972. } else {
  12973. const attributes = this.maybeParseModuleAttributes();
  12974. if (attributes) {
  12975. node.attributes = attributes;
  12976. }
  12977. }
  12978. this.semicolon();
  12979. return this.finishNode(node, "ImportDeclaration");
  12980. }
  12981. parseImportSource() {
  12982. if (!this.match(123)) this.unexpected();
  12983. return this.parseExprAtom();
  12984. }
  12985. shouldParseDefaultImport(node) {
  12986. return tokenIsIdentifier(this.state.type);
  12987. }
  12988. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  12989. specifier.local = this.parseIdentifier();
  12990. this.checkLVal(specifier.local, contextDescription, BIND_LEXICAL);
  12991. node.specifiers.push(this.finishNode(specifier, type));
  12992. }
  12993. parseAssertEntries() {
  12994. const attrs = [];
  12995. const attrNames = new Set();
  12996. do {
  12997. if (this.match(8)) {
  12998. break;
  12999. }
  13000. const node = this.startNode();
  13001. const keyName = this.state.value;
  13002. if (attrNames.has(keyName)) {
  13003. this.raise(this.state.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, keyName);
  13004. }
  13005. attrNames.add(keyName);
  13006. if (this.match(123)) {
  13007. node.key = this.parseStringLiteral(keyName);
  13008. } else {
  13009. node.key = this.parseIdentifier(true);
  13010. }
  13011. this.expect(14);
  13012. if (!this.match(123)) {
  13013. throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue);
  13014. }
  13015. node.value = this.parseStringLiteral(this.state.value);
  13016. this.finishNode(node, "ImportAttribute");
  13017. attrs.push(node);
  13018. } while (this.eat(12));
  13019. return attrs;
  13020. }
  13021. maybeParseModuleAttributes() {
  13022. if (this.match(70) && !this.hasPrecedingLineBreak()) {
  13023. this.expectPlugin("moduleAttributes");
  13024. this.next();
  13025. } else {
  13026. if (this.hasPlugin("moduleAttributes")) return [];
  13027. return null;
  13028. }
  13029. const attrs = [];
  13030. const attributes = new Set();
  13031. do {
  13032. const node = this.startNode();
  13033. node.key = this.parseIdentifier(true);
  13034. if (node.key.name !== "type") {
  13035. this.raise(node.key.start, ErrorMessages.ModuleAttributeDifferentFromType, node.key.name);
  13036. }
  13037. if (attributes.has(node.key.name)) {
  13038. this.raise(node.key.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, node.key.name);
  13039. }
  13040. attributes.add(node.key.name);
  13041. this.expect(14);
  13042. if (!this.match(123)) {
  13043. throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue);
  13044. }
  13045. node.value = this.parseStringLiteral(this.state.value);
  13046. this.finishNode(node, "ImportAttribute");
  13047. attrs.push(node);
  13048. } while (this.eat(12));
  13049. return attrs;
  13050. }
  13051. maybeParseImportAssertions() {
  13052. if (this.isContextual(88) && !this.hasPrecedingLineBreak()) {
  13053. this.expectPlugin("importAssertions");
  13054. this.next();
  13055. } else {
  13056. if (this.hasPlugin("importAssertions")) return [];
  13057. return null;
  13058. }
  13059. this.eat(5);
  13060. const attrs = this.parseAssertEntries();
  13061. this.eat(8);
  13062. return attrs;
  13063. }
  13064. maybeParseDefaultImportSpecifier(node) {
  13065. if (this.shouldParseDefaultImport(node)) {
  13066. this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier", "default import specifier");
  13067. return true;
  13068. }
  13069. return false;
  13070. }
  13071. maybeParseStarImportSpecifier(node) {
  13072. if (this.match(49)) {
  13073. const specifier = this.startNode();
  13074. this.next();
  13075. this.expectContextual(87);
  13076. this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier", "import namespace specifier");
  13077. return true;
  13078. }
  13079. return false;
  13080. }
  13081. parseNamedImportSpecifiers(node) {
  13082. let first = true;
  13083. this.expect(5);
  13084. while (!this.eat(8)) {
  13085. if (first) {
  13086. first = false;
  13087. } else {
  13088. if (this.eat(14)) {
  13089. throw this.raise(this.state.start, ErrorMessages.DestructureNamedImport);
  13090. }
  13091. this.expect(12);
  13092. if (this.eat(8)) break;
  13093. }
  13094. const specifier = this.startNode();
  13095. const importedIsString = this.match(123);
  13096. const isMaybeTypeOnly = this.isContextual(120);
  13097. specifier.imported = this.parseModuleExportName();
  13098. const importSpecifier = this.parseImportSpecifier(specifier, importedIsString, node.importKind === "type" || node.importKind === "typeof", isMaybeTypeOnly);
  13099. node.specifiers.push(importSpecifier);
  13100. }
  13101. }
  13102. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly) {
  13103. if (this.eatContextual(87)) {
  13104. specifier.local = this.parseIdentifier();
  13105. } else {
  13106. const {
  13107. imported
  13108. } = specifier;
  13109. if (importedIsString) {
  13110. throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, imported.value);
  13111. }
  13112. this.checkReservedWord(imported.name, specifier.start, true, true);
  13113. if (!specifier.local) {
  13114. specifier.local = cloneIdentifier(imported);
  13115. }
  13116. }
  13117. this.checkLVal(specifier.local, "import specifier", BIND_LEXICAL);
  13118. return this.finishNode(specifier, "ImportSpecifier");
  13119. }
  13120. isThisParam(param) {
  13121. return param.type === "Identifier" && param.name === "this";
  13122. }
  13123. }
  13124. let Parser$2 = class Parser extends StatementParser {
  13125. constructor(options, input) {
  13126. options = getOptions(options);
  13127. super(options, input);
  13128. this.options = options;
  13129. this.initializeScopes();
  13130. this.plugins = pluginsMap(this.options.plugins);
  13131. this.filename = options.sourceFilename;
  13132. }
  13133. getScopeHandler() {
  13134. return ScopeHandler;
  13135. }
  13136. parse() {
  13137. this.enterInitialScopes();
  13138. const file = this.startNode();
  13139. const program = this.startNode();
  13140. this.nextToken();
  13141. file.errors = null;
  13142. this.parseTopLevel(file, program);
  13143. file.errors = this.state.errors;
  13144. return file;
  13145. }
  13146. };
  13147. function pluginsMap(plugins) {
  13148. const pluginMap = new Map();
  13149. for (const plugin of plugins) {
  13150. const [name, options] = Array.isArray(plugin) ? plugin : [plugin, {}];
  13151. if (!pluginMap.has(name)) pluginMap.set(name, options || {});
  13152. }
  13153. return pluginMap;
  13154. }
  13155. function parse$9(input, options) {
  13156. var _options;
  13157. if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") {
  13158. options = Object.assign({}, options);
  13159. try {
  13160. options.sourceType = "module";
  13161. const parser = getParser(options, input);
  13162. const ast = parser.parse();
  13163. if (parser.sawUnambiguousESM) {
  13164. return ast;
  13165. }
  13166. if (parser.ambiguousScriptDifferentAst) {
  13167. try {
  13168. options.sourceType = "script";
  13169. return getParser(options, input).parse();
  13170. } catch (_unused) {}
  13171. } else {
  13172. ast.program.sourceType = "script";
  13173. }
  13174. return ast;
  13175. } catch (moduleError) {
  13176. try {
  13177. options.sourceType = "script";
  13178. return getParser(options, input).parse();
  13179. } catch (_unused2) {}
  13180. throw moduleError;
  13181. }
  13182. } else {
  13183. return getParser(options, input).parse();
  13184. }
  13185. }
  13186. function parseExpression(input, options) {
  13187. const parser = getParser(options, input);
  13188. if (parser.options.strictMode) {
  13189. parser.state.strict = true;
  13190. }
  13191. return parser.getExpression();
  13192. }
  13193. function generateExportedTokenTypes(internalTokenTypes) {
  13194. const tokenTypes = {};
  13195. for (const typeName of Object.keys(internalTokenTypes)) {
  13196. tokenTypes[typeName] = getExportedToken(internalTokenTypes[typeName]);
  13197. }
  13198. return tokenTypes;
  13199. }
  13200. const tokTypes = generateExportedTokenTypes(tt);
  13201. function getParser(options, input) {
  13202. let cls = Parser$2;
  13203. if (options != null && options.plugins) {
  13204. validatePlugins(options.plugins);
  13205. cls = getParserClass(options.plugins);
  13206. }
  13207. return new cls(options, input);
  13208. }
  13209. const parserClassCache = {};
  13210. function getParserClass(pluginsFromOptions) {
  13211. const pluginList = mixinPluginNames.filter(name => hasPlugin(pluginsFromOptions, name));
  13212. const key = pluginList.join("/");
  13213. let cls = parserClassCache[key];
  13214. if (!cls) {
  13215. cls = Parser$2;
  13216. for (const plugin of pluginList) {
  13217. cls = mixinPlugins[plugin](cls);
  13218. }
  13219. parserClassCache[key] = cls;
  13220. }
  13221. return cls;
  13222. }
  13223. var parse_1$1 = lib.parse = parse$9;
  13224. var parseExpression_1 = lib.parseExpression = parseExpression;
  13225. lib.tokTypes = tokTypes;
  13226. const isStaticExp = (p) => p.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && p.isStatic;
  13227. const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
  13228. function isCoreComponent(tag) {
  13229. if (isBuiltInType(tag, 'Teleport')) {
  13230. return TELEPORT;
  13231. }
  13232. else if (isBuiltInType(tag, 'Suspense')) {
  13233. return SUSPENSE;
  13234. }
  13235. else if (isBuiltInType(tag, 'KeepAlive')) {
  13236. return KEEP_ALIVE;
  13237. }
  13238. else if (isBuiltInType(tag, 'BaseTransition')) {
  13239. return BASE_TRANSITION;
  13240. }
  13241. }
  13242. const nonIdentifierRE = /^\d|[^\$\w]/;
  13243. const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
  13244. const validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/;
  13245. const validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/;
  13246. const whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g;
  13247. /**
  13248. * Simple lexer to check if an expression is a member expression. This is
  13249. * lax and only checks validity at the root level (i.e. does not validate exps
  13250. * inside square brackets), but it's ok since these are only used on template
  13251. * expressions and false positives are invalid expressions in the first place.
  13252. */
  13253. const isMemberExpressionBrowser = (path) => {
  13254. // remove whitespaces around . or [ first
  13255. path = path.trim().replace(whitespaceRE, s => s.trim());
  13256. let state = 0 /* MemberExpLexState.inMemberExp */;
  13257. let stateStack = [];
  13258. let currentOpenBracketCount = 0;
  13259. let currentOpenParensCount = 0;
  13260. let currentStringType = null;
  13261. for (let i = 0; i < path.length; i++) {
  13262. const char = path.charAt(i);
  13263. switch (state) {
  13264. case 0 /* MemberExpLexState.inMemberExp */:
  13265. if (char === '[') {
  13266. stateStack.push(state);
  13267. state = 1 /* MemberExpLexState.inBrackets */;
  13268. currentOpenBracketCount++;
  13269. }
  13270. else if (char === '(') {
  13271. stateStack.push(state);
  13272. state = 2 /* MemberExpLexState.inParens */;
  13273. currentOpenParensCount++;
  13274. }
  13275. else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) {
  13276. return false;
  13277. }
  13278. break;
  13279. case 1 /* MemberExpLexState.inBrackets */:
  13280. if (char === `'` || char === `"` || char === '`') {
  13281. stateStack.push(state);
  13282. state = 3 /* MemberExpLexState.inString */;
  13283. currentStringType = char;
  13284. }
  13285. else if (char === `[`) {
  13286. currentOpenBracketCount++;
  13287. }
  13288. else if (char === `]`) {
  13289. if (!--currentOpenBracketCount) {
  13290. state = stateStack.pop();
  13291. }
  13292. }
  13293. break;
  13294. case 2 /* MemberExpLexState.inParens */:
  13295. if (char === `'` || char === `"` || char === '`') {
  13296. stateStack.push(state);
  13297. state = 3 /* MemberExpLexState.inString */;
  13298. currentStringType = char;
  13299. }
  13300. else if (char === `(`) {
  13301. currentOpenParensCount++;
  13302. }
  13303. else if (char === `)`) {
  13304. // if the exp ends as a call then it should not be considered valid
  13305. if (i === path.length - 1) {
  13306. return false;
  13307. }
  13308. if (!--currentOpenParensCount) {
  13309. state = stateStack.pop();
  13310. }
  13311. }
  13312. break;
  13313. case 3 /* MemberExpLexState.inString */:
  13314. if (char === currentStringType) {
  13315. state = stateStack.pop();
  13316. currentStringType = null;
  13317. }
  13318. break;
  13319. }
  13320. }
  13321. return !currentOpenBracketCount && !currentOpenParensCount;
  13322. };
  13323. const isMemberExpressionNode = (path, context) => {
  13324. try {
  13325. let ret = parseExpression_1(path, {
  13326. plugins: context.expressionPlugins
  13327. });
  13328. if (ret.type === 'TSAsExpression' || ret.type === 'TSTypeAssertion') {
  13329. ret = ret.expression;
  13330. }
  13331. return (ret.type === 'MemberExpression' ||
  13332. ret.type === 'OptionalMemberExpression' ||
  13333. ret.type === 'Identifier');
  13334. }
  13335. catch (e) {
  13336. return false;
  13337. }
  13338. };
  13339. const isMemberExpression = isMemberExpressionNode;
  13340. function getInnerRange(loc, offset, length) {
  13341. const source = loc.source.slice(offset, offset + length);
  13342. const newLoc = {
  13343. source,
  13344. start: advancePositionWithClone(loc.start, loc.source, offset),
  13345. end: loc.end
  13346. };
  13347. if (length != null) {
  13348. newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
  13349. }
  13350. return newLoc;
  13351. }
  13352. function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
  13353. return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
  13354. }
  13355. // advance by mutation without cloning (for performance reasons), since this
  13356. // gets called a lot in the parser
  13357. function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
  13358. let linesCount = 0;
  13359. let lastNewLinePos = -1;
  13360. for (let i = 0; i < numberOfCharacters; i++) {
  13361. if (source.charCodeAt(i) === 10 /* newline char code */) {
  13362. linesCount++;
  13363. lastNewLinePos = i;
  13364. }
  13365. }
  13366. pos.offset += numberOfCharacters;
  13367. pos.line += linesCount;
  13368. pos.column =
  13369. lastNewLinePos === -1
  13370. ? pos.column + numberOfCharacters
  13371. : numberOfCharacters - lastNewLinePos;
  13372. return pos;
  13373. }
  13374. function assert(condition, msg) {
  13375. /* istanbul ignore if */
  13376. if (!condition) {
  13377. throw new Error(msg || `unexpected compiler condition`);
  13378. }
  13379. }
  13380. function findDir(node, name, allowEmpty = false) {
  13381. for (let i = 0; i < node.props.length; i++) {
  13382. const p = node.props[i];
  13383. if (p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  13384. (allowEmpty || p.exp) &&
  13385. (isString$2(name) ? p.name === name : name.test(p.name))) {
  13386. return p;
  13387. }
  13388. }
  13389. }
  13390. function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
  13391. for (let i = 0; i < node.props.length; i++) {
  13392. const p = node.props[i];
  13393. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  13394. if (dynamicOnly)
  13395. continue;
  13396. if (p.name === name && (p.value || allowEmpty)) {
  13397. return p;
  13398. }
  13399. }
  13400. else if (p.name === 'bind' &&
  13401. (p.exp || allowEmpty) &&
  13402. isStaticArgOf(p.arg, name)) {
  13403. return p;
  13404. }
  13405. }
  13406. }
  13407. function isStaticArgOf(arg, name) {
  13408. return !!(arg && isStaticExp(arg) && arg.content === name);
  13409. }
  13410. function hasDynamicKeyVBind(node) {
  13411. return node.props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  13412. p.name === 'bind' &&
  13413. (!p.arg || // v-bind="obj"
  13414. p.arg.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
  13415. !p.arg.isStatic) // v-bind:[foo]
  13416. );
  13417. }
  13418. function isText$1(node) {
  13419. return node.type === 5 /* NodeTypes.INTERPOLATION */ || node.type === 2 /* NodeTypes.TEXT */;
  13420. }
  13421. function isVSlot(p) {
  13422. return p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'slot';
  13423. }
  13424. function isTemplateNode(node) {
  13425. return (node.type === 1 /* NodeTypes.ELEMENT */ && node.tagType === 3 /* ElementTypes.TEMPLATE */);
  13426. }
  13427. function isSlotOutlet(node) {
  13428. return node.type === 1 /* NodeTypes.ELEMENT */ && node.tagType === 2 /* ElementTypes.SLOT */;
  13429. }
  13430. function getVNodeHelper(ssr, isComponent) {
  13431. return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE;
  13432. }
  13433. function getVNodeBlockHelper(ssr, isComponent) {
  13434. return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK;
  13435. }
  13436. const propsHelperSet = new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]);
  13437. function getUnnormalizedProps(props, callPath = []) {
  13438. if (props &&
  13439. !isString$2(props) &&
  13440. props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  13441. const callee = props.callee;
  13442. if (!isString$2(callee) && propsHelperSet.has(callee)) {
  13443. return getUnnormalizedProps(props.arguments[0], callPath.concat(props));
  13444. }
  13445. }
  13446. return [props, callPath];
  13447. }
  13448. function injectProp(node, prop, context) {
  13449. let propsWithInjection;
  13450. /**
  13451. * 1. mergeProps(...)
  13452. * 2. toHandlers(...)
  13453. * 3. normalizeProps(...)
  13454. * 4. normalizeProps(guardReactiveProps(...))
  13455. *
  13456. * we need to get the real props before normalization
  13457. */
  13458. let props = node.type === 13 /* NodeTypes.VNODE_CALL */ ? node.props : node.arguments[2];
  13459. let callPath = [];
  13460. let parentCall;
  13461. if (props &&
  13462. !isString$2(props) &&
  13463. props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  13464. const ret = getUnnormalizedProps(props);
  13465. props = ret[0];
  13466. callPath = ret[1];
  13467. parentCall = callPath[callPath.length - 1];
  13468. }
  13469. if (props == null || isString$2(props)) {
  13470. propsWithInjection = createObjectExpression([prop]);
  13471. }
  13472. else if (props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  13473. // merged props... add ours
  13474. // only inject key to object literal if it's the first argument so that
  13475. // if doesn't override user provided keys
  13476. const first = props.arguments[0];
  13477. if (!isString$2(first) && first.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
  13478. // #6631
  13479. if (!hasProp(prop, first)) {
  13480. first.properties.unshift(prop);
  13481. }
  13482. }
  13483. else {
  13484. if (props.callee === TO_HANDLERS) {
  13485. // #2366
  13486. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  13487. createObjectExpression([prop]),
  13488. props
  13489. ]);
  13490. }
  13491. else {
  13492. props.arguments.unshift(createObjectExpression([prop]));
  13493. }
  13494. }
  13495. !propsWithInjection && (propsWithInjection = props);
  13496. }
  13497. else if (props.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
  13498. if (!hasProp(prop, props)) {
  13499. props.properties.unshift(prop);
  13500. }
  13501. propsWithInjection = props;
  13502. }
  13503. else {
  13504. // single v-bind with expression, return a merged replacement
  13505. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  13506. createObjectExpression([prop]),
  13507. props
  13508. ]);
  13509. // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(props))`,
  13510. // it will be rewritten as `normalizeProps(mergeProps({ key: 0 }, props))`,
  13511. // the `guardReactiveProps` will no longer be needed
  13512. if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) {
  13513. parentCall = callPath[callPath.length - 2];
  13514. }
  13515. }
  13516. if (node.type === 13 /* NodeTypes.VNODE_CALL */) {
  13517. if (parentCall) {
  13518. parentCall.arguments[0] = propsWithInjection;
  13519. }
  13520. else {
  13521. node.props = propsWithInjection;
  13522. }
  13523. }
  13524. else {
  13525. if (parentCall) {
  13526. parentCall.arguments[0] = propsWithInjection;
  13527. }
  13528. else {
  13529. node.arguments[2] = propsWithInjection;
  13530. }
  13531. }
  13532. }
  13533. // check existing key to avoid overriding user provided keys
  13534. function hasProp(prop, props) {
  13535. let result = false;
  13536. if (prop.key.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  13537. const propKeyName = prop.key.content;
  13538. result = props.properties.some(p => p.key.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  13539. p.key.content === propKeyName);
  13540. }
  13541. return result;
  13542. }
  13543. function toValidAssetId(name, type) {
  13544. // see issue#4422, we need adding identifier on validAssetId if variable `name` has specific character
  13545. return `_${type}_${name.replace(/[^\w]/g, (searchValue, replaceValue) => {
  13546. return searchValue === '-' ? '_' : name.charCodeAt(replaceValue).toString();
  13547. })}`;
  13548. }
  13549. // Check if a node contains expressions that reference current context scope ids
  13550. function hasScopeRef(node, ids) {
  13551. if (!node || Object.keys(ids).length === 0) {
  13552. return false;
  13553. }
  13554. switch (node.type) {
  13555. case 1 /* NodeTypes.ELEMENT */:
  13556. for (let i = 0; i < node.props.length; i++) {
  13557. const p = node.props[i];
  13558. if (p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  13559. (hasScopeRef(p.arg, ids) || hasScopeRef(p.exp, ids))) {
  13560. return true;
  13561. }
  13562. }
  13563. return node.children.some(c => hasScopeRef(c, ids));
  13564. case 11 /* NodeTypes.FOR */:
  13565. if (hasScopeRef(node.source, ids)) {
  13566. return true;
  13567. }
  13568. return node.children.some(c => hasScopeRef(c, ids));
  13569. case 9 /* NodeTypes.IF */:
  13570. return node.branches.some(b => hasScopeRef(b, ids));
  13571. case 10 /* NodeTypes.IF_BRANCH */:
  13572. if (hasScopeRef(node.condition, ids)) {
  13573. return true;
  13574. }
  13575. return node.children.some(c => hasScopeRef(c, ids));
  13576. case 4 /* NodeTypes.SIMPLE_EXPRESSION */:
  13577. return (!node.isStatic &&
  13578. isSimpleIdentifier(node.content) &&
  13579. !!ids[node.content]);
  13580. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  13581. return node.children.some(c => isObject$2(c) && hasScopeRef(c, ids));
  13582. case 5 /* NodeTypes.INTERPOLATION */:
  13583. case 12 /* NodeTypes.TEXT_CALL */:
  13584. return hasScopeRef(node.content, ids);
  13585. case 2 /* NodeTypes.TEXT */:
  13586. case 3 /* NodeTypes.COMMENT */:
  13587. return false;
  13588. default:
  13589. return false;
  13590. }
  13591. }
  13592. function getMemoedVNodeCall(node) {
  13593. if (node.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */ && node.callee === WITH_MEMO) {
  13594. return node.arguments[1].returns;
  13595. }
  13596. else {
  13597. return node;
  13598. }
  13599. }
  13600. function makeBlock(node, { helper, removeHelper, inSSR }) {
  13601. if (!node.isBlock) {
  13602. node.isBlock = true;
  13603. removeHelper(getVNodeHelper(inSSR, node.isComponent));
  13604. helper(OPEN_BLOCK);
  13605. helper(getVNodeBlockHelper(inSSR, node.isComponent));
  13606. }
  13607. }
  13608. const deprecationData = {
  13609. ["COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */]: {
  13610. message: `Platform-native elements with "is" prop will no longer be ` +
  13611. `treated as components in Vue 3 unless the "is" value is explicitly ` +
  13612. `prefixed with "vue:".`,
  13613. link: `https://v3-migration.vuejs.org/breaking-changes/custom-elements-interop.html`
  13614. },
  13615. ["COMPILER_V_BIND_SYNC" /* CompilerDeprecationTypes.COMPILER_V_BIND_SYNC */]: {
  13616. message: key => `.sync modifier for v-bind has been removed. Use v-model with ` +
  13617. `argument instead. \`v-bind:${key}.sync\` should be changed to ` +
  13618. `\`v-model:${key}\`.`,
  13619. link: `https://v3-migration.vuejs.org/breaking-changes/v-model.html`
  13620. },
  13621. ["COMPILER_V_BIND_PROP" /* CompilerDeprecationTypes.COMPILER_V_BIND_PROP */]: {
  13622. message: `.prop modifier for v-bind has been removed and no longer necessary. ` +
  13623. `Vue 3 will automatically set a binding as DOM property when appropriate.`
  13624. },
  13625. ["COMPILER_V_BIND_OBJECT_ORDER" /* CompilerDeprecationTypes.COMPILER_V_BIND_OBJECT_ORDER */]: {
  13626. message: `v-bind="obj" usage is now order sensitive and behaves like JavaScript ` +
  13627. `object spread: it will now overwrite an existing non-mergeable attribute ` +
  13628. `that appears before v-bind in the case of conflict. ` +
  13629. `To retain 2.x behavior, move v-bind to make it the first attribute. ` +
  13630. `You can also suppress this warning if the usage is intended.`,
  13631. link: `https://v3-migration.vuejs.org/breaking-changes/v-bind.html`
  13632. },
  13633. ["COMPILER_V_ON_NATIVE" /* CompilerDeprecationTypes.COMPILER_V_ON_NATIVE */]: {
  13634. message: `.native modifier for v-on has been removed as is no longer necessary.`,
  13635. link: `https://v3-migration.vuejs.org/breaking-changes/v-on-native-modifier-removed.html`
  13636. },
  13637. ["COMPILER_V_IF_V_FOR_PRECEDENCE" /* CompilerDeprecationTypes.COMPILER_V_IF_V_FOR_PRECEDENCE */]: {
  13638. message: `v-if / v-for precedence when used on the same element has changed ` +
  13639. `in Vue 3: v-if now takes higher precedence and will no longer have ` +
  13640. `access to v-for scope variables. It is best to avoid the ambiguity ` +
  13641. `with <template> tags or use a computed property that filters v-for ` +
  13642. `data source.`,
  13643. link: `https://v3-migration.vuejs.org/breaking-changes/v-if-v-for.html`
  13644. },
  13645. ["COMPILER_NATIVE_TEMPLATE" /* CompilerDeprecationTypes.COMPILER_NATIVE_TEMPLATE */]: {
  13646. message: `<template> with no special directives will render as a native template ` +
  13647. `element instead of its inner content in Vue 3.`
  13648. },
  13649. ["COMPILER_INLINE_TEMPLATE" /* CompilerDeprecationTypes.COMPILER_INLINE_TEMPLATE */]: {
  13650. message: `"inline-template" has been removed in Vue 3.`,
  13651. link: `https://v3-migration.vuejs.org/breaking-changes/inline-template-attribute.html`
  13652. },
  13653. ["COMPILER_FILTER" /* CompilerDeprecationTypes.COMPILER_FILTERS */]: {
  13654. message: `filters have been removed in Vue 3. ` +
  13655. `The "|" symbol will be treated as native JavaScript bitwise OR operator. ` +
  13656. `Use method calls or computed properties instead.`,
  13657. link: `https://v3-migration.vuejs.org/breaking-changes/filters.html`
  13658. }
  13659. };
  13660. function getCompatValue(key, context) {
  13661. const config = context.options
  13662. ? context.options.compatConfig
  13663. : context.compatConfig;
  13664. const value = config && config[key];
  13665. if (key === 'MODE') {
  13666. return value || 3; // compiler defaults to v3 behavior
  13667. }
  13668. else {
  13669. return value;
  13670. }
  13671. }
  13672. function isCompatEnabled(key, context) {
  13673. const mode = getCompatValue('MODE', context);
  13674. const value = getCompatValue(key, context);
  13675. // in v3 mode, only enable if explicitly set to true
  13676. // otherwise enable for any non-false value
  13677. return mode === 3 ? value === true : value !== false;
  13678. }
  13679. function checkCompatEnabled(key, context, loc, ...args) {
  13680. const enabled = isCompatEnabled(key, context);
  13681. if (enabled) {
  13682. warnDeprecation(key, context, loc, ...args);
  13683. }
  13684. return enabled;
  13685. }
  13686. function warnDeprecation(key, context, loc, ...args) {
  13687. const val = getCompatValue(key, context);
  13688. if (val === 'suppress-warning') {
  13689. return;
  13690. }
  13691. const { message, link } = deprecationData[key];
  13692. const msg = `(deprecation ${key}) ${typeof message === 'function' ? message(...args) : message}${link ? `\n Details: ${link}` : ``}`;
  13693. const err = new SyntaxError(msg);
  13694. err.code = key;
  13695. if (loc)
  13696. err.loc = loc;
  13697. context.onWarn(err);
  13698. }
  13699. // The default decoder only provides escapes for characters reserved as part of
  13700. // the template syntax, and is only used if the custom renderer did not provide
  13701. // a platform-specific decoder.
  13702. const decodeRE = /&(gt|lt|amp|apos|quot);/g;
  13703. const decodeMap = {
  13704. gt: '>',
  13705. lt: '<',
  13706. amp: '&',
  13707. apos: "'",
  13708. quot: '"'
  13709. };
  13710. const defaultParserOptions = {
  13711. delimiters: [`{{`, `}}`],
  13712. getNamespace: () => 0 /* Namespaces.HTML */,
  13713. getTextMode: () => 0 /* TextModes.DATA */,
  13714. isVoidTag: NO,
  13715. isPreTag: NO,
  13716. isCustomElement: NO,
  13717. decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
  13718. onError: defaultOnError,
  13719. onWarn: defaultOnWarn,
  13720. comments: true
  13721. };
  13722. function baseParse(content, options = {}) {
  13723. const context = createParserContext(content, options);
  13724. const start = getCursor(context);
  13725. return createRoot(parseChildren(context, 0 /* TextModes.DATA */, []), getSelection(context, start));
  13726. }
  13727. function createParserContext(content, rawOptions) {
  13728. const options = extend({}, defaultParserOptions);
  13729. let key;
  13730. for (key in rawOptions) {
  13731. // @ts-ignore
  13732. options[key] =
  13733. rawOptions[key] === undefined
  13734. ? defaultParserOptions[key]
  13735. : rawOptions[key];
  13736. }
  13737. return {
  13738. options,
  13739. column: 1,
  13740. line: 1,
  13741. offset: 0,
  13742. originalSource: content,
  13743. source: content,
  13744. inPre: false,
  13745. inVPre: false,
  13746. onWarn: options.onWarn
  13747. };
  13748. }
  13749. function parseChildren(context, mode, ancestors) {
  13750. const parent = last(ancestors);
  13751. const ns = parent ? parent.ns : 0 /* Namespaces.HTML */;
  13752. const nodes = [];
  13753. while (!isEnd(context, mode, ancestors)) {
  13754. const s = context.source;
  13755. let node = undefined;
  13756. if (mode === 0 /* TextModes.DATA */ || mode === 1 /* TextModes.RCDATA */) {
  13757. if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
  13758. // '{{'
  13759. node = parseInterpolation(context, mode);
  13760. }
  13761. else if (mode === 0 /* TextModes.DATA */ && s[0] === '<') {
  13762. // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
  13763. if (s.length === 1) {
  13764. emitError(context, 5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */, 1);
  13765. }
  13766. else if (s[1] === '!') {
  13767. // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
  13768. if (startsWith(s, '<!--')) {
  13769. node = parseComment(context);
  13770. }
  13771. else if (startsWith(s, '<!DOCTYPE')) {
  13772. // Ignore DOCTYPE by a limitation.
  13773. node = parseBogusComment(context);
  13774. }
  13775. else if (startsWith(s, '<![CDATA[')) {
  13776. if (ns !== 0 /* Namespaces.HTML */) {
  13777. node = parseCDATA(context, ancestors);
  13778. }
  13779. else {
  13780. emitError(context, 1 /* ErrorCodes.CDATA_IN_HTML_CONTENT */);
  13781. node = parseBogusComment(context);
  13782. }
  13783. }
  13784. else {
  13785. emitError(context, 11 /* ErrorCodes.INCORRECTLY_OPENED_COMMENT */);
  13786. node = parseBogusComment(context);
  13787. }
  13788. }
  13789. else if (s[1] === '/') {
  13790. // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
  13791. if (s.length === 2) {
  13792. emitError(context, 5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */, 2);
  13793. }
  13794. else if (s[2] === '>') {
  13795. emitError(context, 14 /* ErrorCodes.MISSING_END_TAG_NAME */, 2);
  13796. advanceBy(context, 3);
  13797. continue;
  13798. }
  13799. else if (/[a-z]/i.test(s[2])) {
  13800. emitError(context, 23 /* ErrorCodes.X_INVALID_END_TAG */);
  13801. parseTag(context, 1 /* TagType.End */, parent);
  13802. continue;
  13803. }
  13804. else {
  13805. emitError(context, 12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
  13806. node = parseBogusComment(context);
  13807. }
  13808. }
  13809. else if (/[a-z]/i.test(s[1])) {
  13810. node = parseElement(context, ancestors);
  13811. }
  13812. else if (s[1] === '?') {
  13813. emitError(context, 21 /* ErrorCodes.UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
  13814. node = parseBogusComment(context);
  13815. }
  13816. else {
  13817. emitError(context, 12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
  13818. }
  13819. }
  13820. }
  13821. if (!node) {
  13822. node = parseText(context, mode);
  13823. }
  13824. if (isArray$3(node)) {
  13825. for (let i = 0; i < node.length; i++) {
  13826. pushNode(nodes, node[i]);
  13827. }
  13828. }
  13829. else {
  13830. pushNode(nodes, node);
  13831. }
  13832. }
  13833. // Whitespace handling strategy like v2
  13834. let removedWhitespace = false;
  13835. if (mode !== 2 /* TextModes.RAWTEXT */ && mode !== 1 /* TextModes.RCDATA */) {
  13836. const shouldCondense = context.options.whitespace !== 'preserve';
  13837. for (let i = 0; i < nodes.length; i++) {
  13838. const node = nodes[i];
  13839. if (node.type === 2 /* NodeTypes.TEXT */) {
  13840. if (!context.inPre) {
  13841. if (!/[^\t\r\n\f ]/.test(node.content)) {
  13842. const prev = nodes[i - 1];
  13843. const next = nodes[i + 1];
  13844. // Remove if:
  13845. // - the whitespace is the first or last node, or:
  13846. // - (condense mode) the whitespace is between twos comments, or:
  13847. // - (condense mode) the whitespace is between comment and element, or:
  13848. // - (condense mode) the whitespace is between two elements AND contains newline
  13849. if (!prev ||
  13850. !next ||
  13851. (shouldCondense &&
  13852. ((prev.type === 3 /* NodeTypes.COMMENT */ &&
  13853. next.type === 3 /* NodeTypes.COMMENT */) ||
  13854. (prev.type === 3 /* NodeTypes.COMMENT */ &&
  13855. next.type === 1 /* NodeTypes.ELEMENT */) ||
  13856. (prev.type === 1 /* NodeTypes.ELEMENT */ &&
  13857. next.type === 3 /* NodeTypes.COMMENT */) ||
  13858. (prev.type === 1 /* NodeTypes.ELEMENT */ &&
  13859. next.type === 1 /* NodeTypes.ELEMENT */ &&
  13860. /[\r\n]/.test(node.content))))) {
  13861. removedWhitespace = true;
  13862. nodes[i] = null;
  13863. }
  13864. else {
  13865. // Otherwise, the whitespace is condensed into a single space
  13866. node.content = ' ';
  13867. }
  13868. }
  13869. else if (shouldCondense) {
  13870. // in condense mode, consecutive whitespaces in text are condensed
  13871. // down to a single space.
  13872. node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
  13873. }
  13874. }
  13875. else {
  13876. // #6410 normalize windows newlines in <pre>:
  13877. // in SSR, browsers normalize server-rendered \r\n into a single \n
  13878. // in the DOM
  13879. node.content = node.content.replace(/\r\n/g, '\n');
  13880. }
  13881. }
  13882. // Remove comment nodes if desired by configuration.
  13883. else if (node.type === 3 /* NodeTypes.COMMENT */ && !context.options.comments) {
  13884. removedWhitespace = true;
  13885. nodes[i] = null;
  13886. }
  13887. }
  13888. if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
  13889. // remove leading newline per html spec
  13890. // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
  13891. const first = nodes[0];
  13892. if (first && first.type === 2 /* NodeTypes.TEXT */) {
  13893. first.content = first.content.replace(/^\r?\n/, '');
  13894. }
  13895. }
  13896. }
  13897. return removedWhitespace ? nodes.filter(Boolean) : nodes;
  13898. }
  13899. function pushNode(nodes, node) {
  13900. if (node.type === 2 /* NodeTypes.TEXT */) {
  13901. const prev = last(nodes);
  13902. // Merge if both this and the previous node are text and those are
  13903. // consecutive. This happens for cases like "a < b".
  13904. if (prev &&
  13905. prev.type === 2 /* NodeTypes.TEXT */ &&
  13906. prev.loc.end.offset === node.loc.start.offset) {
  13907. prev.content += node.content;
  13908. prev.loc.end = node.loc.end;
  13909. prev.loc.source += node.loc.source;
  13910. return;
  13911. }
  13912. }
  13913. nodes.push(node);
  13914. }
  13915. function parseCDATA(context, ancestors) {
  13916. advanceBy(context, 9);
  13917. const nodes = parseChildren(context, 3 /* TextModes.CDATA */, ancestors);
  13918. if (context.source.length === 0) {
  13919. emitError(context, 6 /* ErrorCodes.EOF_IN_CDATA */);
  13920. }
  13921. else {
  13922. advanceBy(context, 3);
  13923. }
  13924. return nodes;
  13925. }
  13926. function parseComment(context) {
  13927. const start = getCursor(context);
  13928. let content;
  13929. // Regular comment.
  13930. const match = /--(\!)?>/.exec(context.source);
  13931. if (!match) {
  13932. content = context.source.slice(4);
  13933. advanceBy(context, context.source.length);
  13934. emitError(context, 7 /* ErrorCodes.EOF_IN_COMMENT */);
  13935. }
  13936. else {
  13937. if (match.index <= 3) {
  13938. emitError(context, 0 /* ErrorCodes.ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
  13939. }
  13940. if (match[1]) {
  13941. emitError(context, 10 /* ErrorCodes.INCORRECTLY_CLOSED_COMMENT */);
  13942. }
  13943. content = context.source.slice(4, match.index);
  13944. // Advancing with reporting nested comments.
  13945. const s = context.source.slice(0, match.index);
  13946. let prevIndex = 1, nestedIndex = 0;
  13947. while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
  13948. advanceBy(context, nestedIndex - prevIndex + 1);
  13949. if (nestedIndex + 4 < s.length) {
  13950. emitError(context, 16 /* ErrorCodes.NESTED_COMMENT */);
  13951. }
  13952. prevIndex = nestedIndex + 1;
  13953. }
  13954. advanceBy(context, match.index + match[0].length - prevIndex + 1);
  13955. }
  13956. return {
  13957. type: 3 /* NodeTypes.COMMENT */,
  13958. content,
  13959. loc: getSelection(context, start)
  13960. };
  13961. }
  13962. function parseBogusComment(context) {
  13963. const start = getCursor(context);
  13964. const contentStart = context.source[1] === '?' ? 1 : 2;
  13965. let content;
  13966. const closeIndex = context.source.indexOf('>');
  13967. if (closeIndex === -1) {
  13968. content = context.source.slice(contentStart);
  13969. advanceBy(context, context.source.length);
  13970. }
  13971. else {
  13972. content = context.source.slice(contentStart, closeIndex);
  13973. advanceBy(context, closeIndex + 1);
  13974. }
  13975. return {
  13976. type: 3 /* NodeTypes.COMMENT */,
  13977. content,
  13978. loc: getSelection(context, start)
  13979. };
  13980. }
  13981. function parseElement(context, ancestors) {
  13982. // Start tag.
  13983. const wasInPre = context.inPre;
  13984. const wasInVPre = context.inVPre;
  13985. const parent = last(ancestors);
  13986. const element = parseTag(context, 0 /* TagType.Start */, parent);
  13987. const isPreBoundary = context.inPre && !wasInPre;
  13988. const isVPreBoundary = context.inVPre && !wasInVPre;
  13989. if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
  13990. // #4030 self-closing <pre> tag
  13991. if (isPreBoundary) {
  13992. context.inPre = false;
  13993. }
  13994. if (isVPreBoundary) {
  13995. context.inVPre = false;
  13996. }
  13997. return element;
  13998. }
  13999. // Children.
  14000. ancestors.push(element);
  14001. const mode = context.options.getTextMode(element, parent);
  14002. const children = parseChildren(context, mode, ancestors);
  14003. ancestors.pop();
  14004. element.children = children;
  14005. // End tag.
  14006. if (startsWithEndTagOpen(context.source, element.tag)) {
  14007. parseTag(context, 1 /* TagType.End */, parent);
  14008. }
  14009. else {
  14010. emitError(context, 24 /* ErrorCodes.X_MISSING_END_TAG */, 0, element.loc.start);
  14011. if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
  14012. const first = children[0];
  14013. if (first && startsWith(first.loc.source, '<!--')) {
  14014. emitError(context, 8 /* ErrorCodes.EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
  14015. }
  14016. }
  14017. }
  14018. element.loc = getSelection(context, element.loc.start);
  14019. if (isPreBoundary) {
  14020. context.inPre = false;
  14021. }
  14022. if (isVPreBoundary) {
  14023. context.inVPre = false;
  14024. }
  14025. return element;
  14026. }
  14027. const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
  14028. function parseTag(context, type, parent) {
  14029. // Tag open.
  14030. const start = getCursor(context);
  14031. const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
  14032. const tag = match[1];
  14033. const ns = context.options.getNamespace(tag, parent);
  14034. advanceBy(context, match[0].length);
  14035. advanceSpaces(context);
  14036. // save current state in case we need to re-parse attributes with v-pre
  14037. const cursor = getCursor(context);
  14038. const currentSource = context.source;
  14039. // check <pre> tag
  14040. if (context.options.isPreTag(tag)) {
  14041. context.inPre = true;
  14042. }
  14043. // Attributes.
  14044. let props = parseAttributes(context, type);
  14045. // check v-pre
  14046. if (type === 0 /* TagType.Start */ &&
  14047. !context.inVPre &&
  14048. props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'pre')) {
  14049. context.inVPre = true;
  14050. // reset context
  14051. extend(context, cursor);
  14052. context.source = currentSource;
  14053. // re-parse attrs and filter out v-pre itself
  14054. props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
  14055. }
  14056. // Tag close.
  14057. let isSelfClosing = false;
  14058. if (context.source.length === 0) {
  14059. emitError(context, 9 /* ErrorCodes.EOF_IN_TAG */);
  14060. }
  14061. else {
  14062. isSelfClosing = startsWith(context.source, '/>');
  14063. if (type === 1 /* TagType.End */ && isSelfClosing) {
  14064. emitError(context, 4 /* ErrorCodes.END_TAG_WITH_TRAILING_SOLIDUS */);
  14065. }
  14066. advanceBy(context, isSelfClosing ? 2 : 1);
  14067. }
  14068. if (type === 1 /* TagType.End */) {
  14069. return;
  14070. }
  14071. let tagType = 0 /* ElementTypes.ELEMENT */;
  14072. if (!context.inVPre) {
  14073. if (tag === 'slot') {
  14074. tagType = 2 /* ElementTypes.SLOT */;
  14075. }
  14076. else if (tag === 'template') {
  14077. if (props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ && isSpecialTemplateDirective(p.name))) {
  14078. tagType = 3 /* ElementTypes.TEMPLATE */;
  14079. }
  14080. }
  14081. else if (isComponent(tag, props, context)) {
  14082. tagType = 1 /* ElementTypes.COMPONENT */;
  14083. }
  14084. }
  14085. return {
  14086. type: 1 /* NodeTypes.ELEMENT */,
  14087. ns,
  14088. tag,
  14089. tagType,
  14090. props,
  14091. isSelfClosing,
  14092. children: [],
  14093. loc: getSelection(context, start),
  14094. codegenNode: undefined // to be created during transform phase
  14095. };
  14096. }
  14097. function isComponent(tag, props, context) {
  14098. const options = context.options;
  14099. if (options.isCustomElement(tag)) {
  14100. return false;
  14101. }
  14102. if (tag === 'component' ||
  14103. /^[A-Z]/.test(tag) ||
  14104. isCoreComponent(tag) ||
  14105. (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
  14106. (options.isNativeTag && !options.isNativeTag(tag))) {
  14107. return true;
  14108. }
  14109. // at this point the tag should be a native tag, but check for potential "is"
  14110. // casting
  14111. for (let i = 0; i < props.length; i++) {
  14112. const p = props[i];
  14113. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  14114. if (p.name === 'is' && p.value) {
  14115. if (p.value.content.startsWith('vue:')) {
  14116. return true;
  14117. }
  14118. }
  14119. }
  14120. else {
  14121. // directive
  14122. // v-is (TODO Deprecate)
  14123. if (p.name === 'is') {
  14124. return true;
  14125. }
  14126. else if (
  14127. // :is on plain element - only treat as component in compat mode
  14128. p.name === 'bind' &&
  14129. isStaticArgOf(p.arg, 'is') &&
  14130. false &&
  14131. checkCompatEnabled("COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */, context, p.loc)) {
  14132. return true;
  14133. }
  14134. }
  14135. }
  14136. }
  14137. function parseAttributes(context, type) {
  14138. const props = [];
  14139. const attributeNames = new Set();
  14140. while (context.source.length > 0 &&
  14141. !startsWith(context.source, '>') &&
  14142. !startsWith(context.source, '/>')) {
  14143. if (startsWith(context.source, '/')) {
  14144. emitError(context, 22 /* ErrorCodes.UNEXPECTED_SOLIDUS_IN_TAG */);
  14145. advanceBy(context, 1);
  14146. advanceSpaces(context);
  14147. continue;
  14148. }
  14149. if (type === 1 /* TagType.End */) {
  14150. emitError(context, 3 /* ErrorCodes.END_TAG_WITH_ATTRIBUTES */);
  14151. }
  14152. const attr = parseAttribute(context, attributeNames);
  14153. // Trim whitespace between class
  14154. // https://github.com/vuejs/core/issues/4251
  14155. if (attr.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  14156. attr.value &&
  14157. attr.name === 'class') {
  14158. attr.value.content = attr.value.content.replace(/\s+/g, ' ').trim();
  14159. }
  14160. if (type === 0 /* TagType.Start */) {
  14161. props.push(attr);
  14162. }
  14163. if (/^[^\t\r\n\f />]/.test(context.source)) {
  14164. emitError(context, 15 /* ErrorCodes.MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
  14165. }
  14166. advanceSpaces(context);
  14167. }
  14168. return props;
  14169. }
  14170. function parseAttribute(context, nameSet) {
  14171. // Name.
  14172. const start = getCursor(context);
  14173. const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
  14174. const name = match[0];
  14175. if (nameSet.has(name)) {
  14176. emitError(context, 2 /* ErrorCodes.DUPLICATE_ATTRIBUTE */);
  14177. }
  14178. nameSet.add(name);
  14179. if (name[0] === '=') {
  14180. emitError(context, 19 /* ErrorCodes.UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
  14181. }
  14182. {
  14183. const pattern = /["'<]/g;
  14184. let m;
  14185. while ((m = pattern.exec(name))) {
  14186. emitError(context, 17 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
  14187. }
  14188. }
  14189. advanceBy(context, name.length);
  14190. // Value
  14191. let value = undefined;
  14192. if (/^[\t\r\n\f ]*=/.test(context.source)) {
  14193. advanceSpaces(context);
  14194. advanceBy(context, 1);
  14195. advanceSpaces(context);
  14196. value = parseAttributeValue(context);
  14197. if (!value) {
  14198. emitError(context, 13 /* ErrorCodes.MISSING_ATTRIBUTE_VALUE */);
  14199. }
  14200. }
  14201. const loc = getSelection(context, start);
  14202. if (!context.inVPre && /^(v-[A-Za-z0-9-]|:|\.|@|#)/.test(name)) {
  14203. const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^\.|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
  14204. let isPropShorthand = startsWith(name, '.');
  14205. let dirName = match[1] ||
  14206. (isPropShorthand || startsWith(name, ':')
  14207. ? 'bind'
  14208. : startsWith(name, '@')
  14209. ? 'on'
  14210. : 'slot');
  14211. let arg;
  14212. if (match[2]) {
  14213. const isSlot = dirName === 'slot';
  14214. const startOffset = name.lastIndexOf(match[2]);
  14215. const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
  14216. let content = match[2];
  14217. let isStatic = true;
  14218. if (content.startsWith('[')) {
  14219. isStatic = false;
  14220. if (!content.endsWith(']')) {
  14221. emitError(context, 27 /* ErrorCodes.X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
  14222. content = content.slice(1);
  14223. }
  14224. else {
  14225. content = content.slice(1, content.length - 1);
  14226. }
  14227. }
  14228. else if (isSlot) {
  14229. // #1241 special case for v-slot: vuetify relies extensively on slot
  14230. // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
  14231. // supports such usage so we are keeping it consistent with 2.x.
  14232. content += match[3] || '';
  14233. }
  14234. arg = {
  14235. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  14236. content,
  14237. isStatic,
  14238. constType: isStatic
  14239. ? 3 /* ConstantTypes.CAN_STRINGIFY */
  14240. : 0 /* ConstantTypes.NOT_CONSTANT */,
  14241. loc
  14242. };
  14243. }
  14244. if (value && value.isQuoted) {
  14245. const valueLoc = value.loc;
  14246. valueLoc.start.offset++;
  14247. valueLoc.start.column++;
  14248. valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
  14249. valueLoc.source = valueLoc.source.slice(1, -1);
  14250. }
  14251. const modifiers = match[3] ? match[3].slice(1).split('.') : [];
  14252. if (isPropShorthand)
  14253. modifiers.push('prop');
  14254. return {
  14255. type: 7 /* NodeTypes.DIRECTIVE */,
  14256. name: dirName,
  14257. exp: value && {
  14258. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  14259. content: value.content,
  14260. isStatic: false,
  14261. // Treat as non-constant by default. This can be potentially set to
  14262. // other values by `transformExpression` to make it eligible for hoisting.
  14263. constType: 0 /* ConstantTypes.NOT_CONSTANT */,
  14264. loc: value.loc
  14265. },
  14266. arg,
  14267. modifiers,
  14268. loc
  14269. };
  14270. }
  14271. // missing directive name or illegal directive name
  14272. if (!context.inVPre && startsWith(name, 'v-')) {
  14273. emitError(context, 26 /* ErrorCodes.X_MISSING_DIRECTIVE_NAME */);
  14274. }
  14275. return {
  14276. type: 6 /* NodeTypes.ATTRIBUTE */,
  14277. name,
  14278. value: value && {
  14279. type: 2 /* NodeTypes.TEXT */,
  14280. content: value.content,
  14281. loc: value.loc
  14282. },
  14283. loc
  14284. };
  14285. }
  14286. function parseAttributeValue(context) {
  14287. const start = getCursor(context);
  14288. let content;
  14289. const quote = context.source[0];
  14290. const isQuoted = quote === `"` || quote === `'`;
  14291. if (isQuoted) {
  14292. // Quoted value.
  14293. advanceBy(context, 1);
  14294. const endIndex = context.source.indexOf(quote);
  14295. if (endIndex === -1) {
  14296. content = parseTextData(context, context.source.length, 4 /* TextModes.ATTRIBUTE_VALUE */);
  14297. }
  14298. else {
  14299. content = parseTextData(context, endIndex, 4 /* TextModes.ATTRIBUTE_VALUE */);
  14300. advanceBy(context, 1);
  14301. }
  14302. }
  14303. else {
  14304. // Unquoted
  14305. const match = /^[^\t\r\n\f >]+/.exec(context.source);
  14306. if (!match) {
  14307. return undefined;
  14308. }
  14309. const unexpectedChars = /["'<=`]/g;
  14310. let m;
  14311. while ((m = unexpectedChars.exec(match[0]))) {
  14312. emitError(context, 18 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
  14313. }
  14314. content = parseTextData(context, match[0].length, 4 /* TextModes.ATTRIBUTE_VALUE */);
  14315. }
  14316. return { content, isQuoted, loc: getSelection(context, start) };
  14317. }
  14318. function parseInterpolation(context, mode) {
  14319. const [open, close] = context.options.delimiters;
  14320. const closeIndex = context.source.indexOf(close, open.length);
  14321. if (closeIndex === -1) {
  14322. emitError(context, 25 /* ErrorCodes.X_MISSING_INTERPOLATION_END */);
  14323. return undefined;
  14324. }
  14325. const start = getCursor(context);
  14326. advanceBy(context, open.length);
  14327. const innerStart = getCursor(context);
  14328. const innerEnd = getCursor(context);
  14329. const rawContentLength = closeIndex - open.length;
  14330. const rawContent = context.source.slice(0, rawContentLength);
  14331. const preTrimContent = parseTextData(context, rawContentLength, mode);
  14332. const content = preTrimContent.trim();
  14333. const startOffset = preTrimContent.indexOf(content);
  14334. if (startOffset > 0) {
  14335. advancePositionWithMutation(innerStart, rawContent, startOffset);
  14336. }
  14337. const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
  14338. advancePositionWithMutation(innerEnd, rawContent, endOffset);
  14339. advanceBy(context, close.length);
  14340. return {
  14341. type: 5 /* NodeTypes.INTERPOLATION */,
  14342. content: {
  14343. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  14344. isStatic: false,
  14345. // Set `isConstant` to false by default and will decide in transformExpression
  14346. constType: 0 /* ConstantTypes.NOT_CONSTANT */,
  14347. content,
  14348. loc: getSelection(context, innerStart, innerEnd)
  14349. },
  14350. loc: getSelection(context, start)
  14351. };
  14352. }
  14353. function parseText(context, mode) {
  14354. const endTokens = mode === 3 /* TextModes.CDATA */ ? [']]>'] : ['<', context.options.delimiters[0]];
  14355. let endIndex = context.source.length;
  14356. for (let i = 0; i < endTokens.length; i++) {
  14357. const index = context.source.indexOf(endTokens[i], 1);
  14358. if (index !== -1 && endIndex > index) {
  14359. endIndex = index;
  14360. }
  14361. }
  14362. const start = getCursor(context);
  14363. const content = parseTextData(context, endIndex, mode);
  14364. return {
  14365. type: 2 /* NodeTypes.TEXT */,
  14366. content,
  14367. loc: getSelection(context, start)
  14368. };
  14369. }
  14370. /**
  14371. * Get text data with a given length from the current location.
  14372. * This translates HTML entities in the text data.
  14373. */
  14374. function parseTextData(context, length, mode) {
  14375. const rawText = context.source.slice(0, length);
  14376. advanceBy(context, length);
  14377. if (mode === 2 /* TextModes.RAWTEXT */ ||
  14378. mode === 3 /* TextModes.CDATA */ ||
  14379. !rawText.includes('&')) {
  14380. return rawText;
  14381. }
  14382. else {
  14383. // DATA or RCDATA containing "&"". Entity decoding required.
  14384. return context.options.decodeEntities(rawText, mode === 4 /* TextModes.ATTRIBUTE_VALUE */);
  14385. }
  14386. }
  14387. function getCursor(context) {
  14388. const { column, line, offset } = context;
  14389. return { column, line, offset };
  14390. }
  14391. function getSelection(context, start, end) {
  14392. end = end || getCursor(context);
  14393. return {
  14394. start,
  14395. end,
  14396. source: context.originalSource.slice(start.offset, end.offset)
  14397. };
  14398. }
  14399. function last(xs) {
  14400. return xs[xs.length - 1];
  14401. }
  14402. function startsWith(source, searchString) {
  14403. return source.startsWith(searchString);
  14404. }
  14405. function advanceBy(context, numberOfCharacters) {
  14406. const { source } = context;
  14407. advancePositionWithMutation(context, source, numberOfCharacters);
  14408. context.source = source.slice(numberOfCharacters);
  14409. }
  14410. function advanceSpaces(context) {
  14411. const match = /^[\t\r\n\f ]+/.exec(context.source);
  14412. if (match) {
  14413. advanceBy(context, match[0].length);
  14414. }
  14415. }
  14416. function getNewPosition(context, start, numberOfCharacters) {
  14417. return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
  14418. }
  14419. function emitError(context, code, offset, loc = getCursor(context)) {
  14420. if (offset) {
  14421. loc.offset += offset;
  14422. loc.column += offset;
  14423. }
  14424. context.options.onError(createCompilerError(code, {
  14425. start: loc,
  14426. end: loc,
  14427. source: ''
  14428. }));
  14429. }
  14430. function isEnd(context, mode, ancestors) {
  14431. const s = context.source;
  14432. switch (mode) {
  14433. case 0 /* TextModes.DATA */:
  14434. if (startsWith(s, '</')) {
  14435. // TODO: probably bad performance
  14436. for (let i = ancestors.length - 1; i >= 0; --i) {
  14437. if (startsWithEndTagOpen(s, ancestors[i].tag)) {
  14438. return true;
  14439. }
  14440. }
  14441. }
  14442. break;
  14443. case 1 /* TextModes.RCDATA */:
  14444. case 2 /* TextModes.RAWTEXT */: {
  14445. const parent = last(ancestors);
  14446. if (parent && startsWithEndTagOpen(s, parent.tag)) {
  14447. return true;
  14448. }
  14449. break;
  14450. }
  14451. case 3 /* TextModes.CDATA */:
  14452. if (startsWith(s, ']]>')) {
  14453. return true;
  14454. }
  14455. break;
  14456. }
  14457. return !s;
  14458. }
  14459. function startsWithEndTagOpen(source, tag) {
  14460. return (startsWith(source, '</') &&
  14461. source.slice(2, 2 + tag.length).toLowerCase() === tag.toLowerCase() &&
  14462. /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
  14463. }
  14464. function hoistStatic(root, context) {
  14465. walk$2(root, context,
  14466. // Root node is unfortunately non-hoistable due to potential parent
  14467. // fallthrough attributes.
  14468. isSingleElementRoot(root, root.children[0]));
  14469. }
  14470. function isSingleElementRoot(root, child) {
  14471. const { children } = root;
  14472. return (children.length === 1 &&
  14473. child.type === 1 /* NodeTypes.ELEMENT */ &&
  14474. !isSlotOutlet(child));
  14475. }
  14476. function walk$2(node, context, doNotHoistNode = false) {
  14477. const { children } = node;
  14478. const originalCount = children.length;
  14479. let hoistedCount = 0;
  14480. for (let i = 0; i < children.length; i++) {
  14481. const child = children[i];
  14482. // only plain elements & text calls are eligible for hoisting.
  14483. if (child.type === 1 /* NodeTypes.ELEMENT */ &&
  14484. child.tagType === 0 /* ElementTypes.ELEMENT */) {
  14485. const constantType = doNotHoistNode
  14486. ? 0 /* ConstantTypes.NOT_CONSTANT */
  14487. : getConstantType(child, context);
  14488. if (constantType > 0 /* ConstantTypes.NOT_CONSTANT */) {
  14489. if (constantType >= 2 /* ConstantTypes.CAN_HOIST */) {
  14490. child.codegenNode.patchFlag =
  14491. -1 /* PatchFlags.HOISTED */ + (` /* HOISTED */` );
  14492. child.codegenNode = context.hoist(child.codegenNode);
  14493. hoistedCount++;
  14494. continue;
  14495. }
  14496. }
  14497. else {
  14498. // node may contain dynamic children, but its props may be eligible for
  14499. // hoisting.
  14500. const codegenNode = child.codegenNode;
  14501. if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  14502. const flag = getPatchFlag(codegenNode);
  14503. if ((!flag ||
  14504. flag === 512 /* PatchFlags.NEED_PATCH */ ||
  14505. flag === 1 /* PatchFlags.TEXT */) &&
  14506. getGeneratedPropsConstantType(child, context) >=
  14507. 2 /* ConstantTypes.CAN_HOIST */) {
  14508. const props = getNodeProps(child);
  14509. if (props) {
  14510. codegenNode.props = context.hoist(props);
  14511. }
  14512. }
  14513. if (codegenNode.dynamicProps) {
  14514. codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps);
  14515. }
  14516. }
  14517. }
  14518. }
  14519. // walk further
  14520. if (child.type === 1 /* NodeTypes.ELEMENT */) {
  14521. const isComponent = child.tagType === 1 /* ElementTypes.COMPONENT */;
  14522. if (isComponent) {
  14523. context.scopes.vSlot++;
  14524. }
  14525. walk$2(child, context);
  14526. if (isComponent) {
  14527. context.scopes.vSlot--;
  14528. }
  14529. }
  14530. else if (child.type === 11 /* NodeTypes.FOR */) {
  14531. // Do not hoist v-for single child because it has to be a block
  14532. walk$2(child, context, child.children.length === 1);
  14533. }
  14534. else if (child.type === 9 /* NodeTypes.IF */) {
  14535. for (let i = 0; i < child.branches.length; i++) {
  14536. // Do not hoist v-if single child because it has to be a block
  14537. walk$2(child.branches[i], context, child.branches[i].children.length === 1);
  14538. }
  14539. }
  14540. }
  14541. if (hoistedCount && context.transformHoist) {
  14542. context.transformHoist(children, context, node);
  14543. }
  14544. // all children were hoisted - the entire children array is hoistable.
  14545. if (hoistedCount &&
  14546. hoistedCount === originalCount &&
  14547. node.type === 1 /* NodeTypes.ELEMENT */ &&
  14548. node.tagType === 0 /* ElementTypes.ELEMENT */ &&
  14549. node.codegenNode &&
  14550. node.codegenNode.type === 13 /* NodeTypes.VNODE_CALL */ &&
  14551. isArray$3(node.codegenNode.children)) {
  14552. node.codegenNode.children = context.hoist(createArrayExpression(node.codegenNode.children));
  14553. }
  14554. }
  14555. function getConstantType(node, context) {
  14556. const { constantCache } = context;
  14557. switch (node.type) {
  14558. case 1 /* NodeTypes.ELEMENT */:
  14559. if (node.tagType !== 0 /* ElementTypes.ELEMENT */) {
  14560. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14561. }
  14562. const cached = constantCache.get(node);
  14563. if (cached !== undefined) {
  14564. return cached;
  14565. }
  14566. const codegenNode = node.codegenNode;
  14567. if (codegenNode.type !== 13 /* NodeTypes.VNODE_CALL */) {
  14568. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14569. }
  14570. if (codegenNode.isBlock &&
  14571. node.tag !== 'svg' &&
  14572. node.tag !== 'foreignObject') {
  14573. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14574. }
  14575. const flag = getPatchFlag(codegenNode);
  14576. if (!flag) {
  14577. let returnType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  14578. // Element itself has no patch flag. However we still need to check:
  14579. // 1. Even for a node with no patch flag, it is possible for it to contain
  14580. // non-hoistable expressions that refers to scope variables, e.g. compiler
  14581. // injected keys or cached event handlers. Therefore we need to always
  14582. // check the codegenNode's props to be sure.
  14583. const generatedPropsType = getGeneratedPropsConstantType(node, context);
  14584. if (generatedPropsType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  14585. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  14586. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14587. }
  14588. if (generatedPropsType < returnType) {
  14589. returnType = generatedPropsType;
  14590. }
  14591. // 2. its children.
  14592. for (let i = 0; i < node.children.length; i++) {
  14593. const childType = getConstantType(node.children[i], context);
  14594. if (childType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  14595. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  14596. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14597. }
  14598. if (childType < returnType) {
  14599. returnType = childType;
  14600. }
  14601. }
  14602. // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
  14603. // type, check if any of the props can cause the type to be lowered
  14604. // we can skip can_patch because it's guaranteed by the absence of a
  14605. // patchFlag.
  14606. if (returnType > 1 /* ConstantTypes.CAN_SKIP_PATCH */) {
  14607. for (let i = 0; i < node.props.length; i++) {
  14608. const p = node.props[i];
  14609. if (p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'bind' && p.exp) {
  14610. const expType = getConstantType(p.exp, context);
  14611. if (expType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  14612. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  14613. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14614. }
  14615. if (expType < returnType) {
  14616. returnType = expType;
  14617. }
  14618. }
  14619. }
  14620. }
  14621. // only svg/foreignObject could be block here, however if they are
  14622. // static then they don't need to be blocks since there will be no
  14623. // nested updates.
  14624. if (codegenNode.isBlock) {
  14625. // except set custom directives.
  14626. for (let i = 0; i < node.props.length; i++) {
  14627. const p = node.props[i];
  14628. if (p.type === 7 /* NodeTypes.DIRECTIVE */) {
  14629. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  14630. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14631. }
  14632. }
  14633. context.removeHelper(OPEN_BLOCK);
  14634. context.removeHelper(getVNodeBlockHelper(context.inSSR, codegenNode.isComponent));
  14635. codegenNode.isBlock = false;
  14636. context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent));
  14637. }
  14638. constantCache.set(node, returnType);
  14639. return returnType;
  14640. }
  14641. else {
  14642. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  14643. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14644. }
  14645. case 2 /* NodeTypes.TEXT */:
  14646. case 3 /* NodeTypes.COMMENT */:
  14647. return 3 /* ConstantTypes.CAN_STRINGIFY */;
  14648. case 9 /* NodeTypes.IF */:
  14649. case 11 /* NodeTypes.FOR */:
  14650. case 10 /* NodeTypes.IF_BRANCH */:
  14651. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14652. case 5 /* NodeTypes.INTERPOLATION */:
  14653. case 12 /* NodeTypes.TEXT_CALL */:
  14654. return getConstantType(node.content, context);
  14655. case 4 /* NodeTypes.SIMPLE_EXPRESSION */:
  14656. return node.constType;
  14657. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  14658. let returnType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  14659. for (let i = 0; i < node.children.length; i++) {
  14660. const child = node.children[i];
  14661. if (isString$2(child) || isSymbol$1(child)) {
  14662. continue;
  14663. }
  14664. const childType = getConstantType(child, context);
  14665. if (childType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  14666. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14667. }
  14668. else if (childType < returnType) {
  14669. returnType = childType;
  14670. }
  14671. }
  14672. return returnType;
  14673. default:
  14674. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14675. }
  14676. }
  14677. const allowHoistedHelperSet = new Set([
  14678. NORMALIZE_CLASS,
  14679. NORMALIZE_STYLE,
  14680. NORMALIZE_PROPS,
  14681. GUARD_REACTIVE_PROPS
  14682. ]);
  14683. function getConstantTypeOfHelperCall(value, context) {
  14684. if (value.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */ &&
  14685. !isString$2(value.callee) &&
  14686. allowHoistedHelperSet.has(value.callee)) {
  14687. const arg = value.arguments[0];
  14688. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  14689. return getConstantType(arg, context);
  14690. }
  14691. else if (arg.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  14692. // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(exp))`
  14693. return getConstantTypeOfHelperCall(arg, context);
  14694. }
  14695. }
  14696. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14697. }
  14698. function getGeneratedPropsConstantType(node, context) {
  14699. let returnType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  14700. const props = getNodeProps(node);
  14701. if (props && props.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
  14702. const { properties } = props;
  14703. for (let i = 0; i < properties.length; i++) {
  14704. const { key, value } = properties[i];
  14705. const keyType = getConstantType(key, context);
  14706. if (keyType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  14707. return keyType;
  14708. }
  14709. if (keyType < returnType) {
  14710. returnType = keyType;
  14711. }
  14712. let valueType;
  14713. if (value.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  14714. valueType = getConstantType(value, context);
  14715. }
  14716. else if (value.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  14717. // some helper calls can be hoisted,
  14718. // such as the `normalizeProps` generated by the compiler for pre-normalize class,
  14719. // in this case we need to respect the ConstantType of the helper's arguments
  14720. valueType = getConstantTypeOfHelperCall(value, context);
  14721. }
  14722. else {
  14723. valueType = 0 /* ConstantTypes.NOT_CONSTANT */;
  14724. }
  14725. if (valueType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  14726. return valueType;
  14727. }
  14728. if (valueType < returnType) {
  14729. returnType = valueType;
  14730. }
  14731. }
  14732. }
  14733. return returnType;
  14734. }
  14735. function getNodeProps(node) {
  14736. const codegenNode = node.codegenNode;
  14737. if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  14738. return codegenNode.props;
  14739. }
  14740. }
  14741. function getPatchFlag(node) {
  14742. const flag = node.patchFlag;
  14743. return flag ? parseInt(flag, 10) : undefined;
  14744. }
  14745. function createTransformContext(root, { filename = '', prefixIdentifiers = false, hoistStatic = false, cacheHandlers = false, nodeTransforms = [], directiveTransforms = {}, transformHoist = null, isBuiltInComponent = NOOP, isCustomElement = NOOP, expressionPlugins = [], scopeId = null, slotted = true, ssr = false, inSSR = false, ssrCssVars = ``, bindingMetadata = EMPTY_OBJ, inline = false, isTS = false, onError = defaultOnError, onWarn = defaultOnWarn, compatConfig }) {
  14746. const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
  14747. const context = {
  14748. // options
  14749. selfName: nameMatch && capitalize$1(camelize(nameMatch[1])),
  14750. prefixIdentifiers,
  14751. hoistStatic,
  14752. cacheHandlers,
  14753. nodeTransforms,
  14754. directiveTransforms,
  14755. transformHoist,
  14756. isBuiltInComponent,
  14757. isCustomElement,
  14758. expressionPlugins,
  14759. scopeId,
  14760. slotted,
  14761. ssr,
  14762. inSSR,
  14763. ssrCssVars,
  14764. bindingMetadata,
  14765. inline,
  14766. isTS,
  14767. onError,
  14768. onWarn,
  14769. compatConfig,
  14770. // state
  14771. root,
  14772. helpers: new Map(),
  14773. components: new Set(),
  14774. directives: new Set(),
  14775. hoists: [],
  14776. imports: [],
  14777. constantCache: new Map(),
  14778. temps: 0,
  14779. cached: 0,
  14780. identifiers: Object.create(null),
  14781. scopes: {
  14782. vFor: 0,
  14783. vSlot: 0,
  14784. vPre: 0,
  14785. vOnce: 0
  14786. },
  14787. parent: null,
  14788. currentNode: root,
  14789. childIndex: 0,
  14790. inVOnce: false,
  14791. // methods
  14792. helper(name) {
  14793. const count = context.helpers.get(name) || 0;
  14794. context.helpers.set(name, count + 1);
  14795. return name;
  14796. },
  14797. removeHelper(name) {
  14798. const count = context.helpers.get(name);
  14799. if (count) {
  14800. const currentCount = count - 1;
  14801. if (!currentCount) {
  14802. context.helpers.delete(name);
  14803. }
  14804. else {
  14805. context.helpers.set(name, currentCount);
  14806. }
  14807. }
  14808. },
  14809. helperString(name) {
  14810. return `_${helperNameMap[context.helper(name)]}`;
  14811. },
  14812. replaceNode(node) {
  14813. /* istanbul ignore if */
  14814. {
  14815. if (!context.currentNode) {
  14816. throw new Error(`Node being replaced is already removed.`);
  14817. }
  14818. if (!context.parent) {
  14819. throw new Error(`Cannot replace root node.`);
  14820. }
  14821. }
  14822. context.parent.children[context.childIndex] = context.currentNode = node;
  14823. },
  14824. removeNode(node) {
  14825. if (!context.parent) {
  14826. throw new Error(`Cannot remove root node.`);
  14827. }
  14828. const list = context.parent.children;
  14829. const removalIndex = node
  14830. ? list.indexOf(node)
  14831. : context.currentNode
  14832. ? context.childIndex
  14833. : -1;
  14834. /* istanbul ignore if */
  14835. if (removalIndex < 0) {
  14836. throw new Error(`node being removed is not a child of current parent`);
  14837. }
  14838. if (!node || node === context.currentNode) {
  14839. // current node removed
  14840. context.currentNode = null;
  14841. context.onNodeRemoved();
  14842. }
  14843. else {
  14844. // sibling node removed
  14845. if (context.childIndex > removalIndex) {
  14846. context.childIndex--;
  14847. context.onNodeRemoved();
  14848. }
  14849. }
  14850. context.parent.children.splice(removalIndex, 1);
  14851. },
  14852. onNodeRemoved: () => { },
  14853. addIdentifiers(exp) {
  14854. // identifier tracking only happens in non-browser builds.
  14855. {
  14856. if (isString$2(exp)) {
  14857. addId(exp);
  14858. }
  14859. else if (exp.identifiers) {
  14860. exp.identifiers.forEach(addId);
  14861. }
  14862. else if (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  14863. addId(exp.content);
  14864. }
  14865. }
  14866. },
  14867. removeIdentifiers(exp) {
  14868. {
  14869. if (isString$2(exp)) {
  14870. removeId(exp);
  14871. }
  14872. else if (exp.identifiers) {
  14873. exp.identifiers.forEach(removeId);
  14874. }
  14875. else if (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  14876. removeId(exp.content);
  14877. }
  14878. }
  14879. },
  14880. hoist(exp) {
  14881. if (isString$2(exp))
  14882. exp = createSimpleExpression(exp);
  14883. context.hoists.push(exp);
  14884. const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* ConstantTypes.CAN_HOIST */);
  14885. identifier.hoisted = exp;
  14886. return identifier;
  14887. },
  14888. cache(exp, isVNode = false) {
  14889. return createCacheExpression(context.cached++, exp, isVNode);
  14890. }
  14891. };
  14892. function addId(id) {
  14893. const { identifiers } = context;
  14894. if (identifiers[id] === undefined) {
  14895. identifiers[id] = 0;
  14896. }
  14897. identifiers[id]++;
  14898. }
  14899. function removeId(id) {
  14900. context.identifiers[id]--;
  14901. }
  14902. return context;
  14903. }
  14904. function transform$1(root, options) {
  14905. const context = createTransformContext(root, options);
  14906. traverseNode(root, context);
  14907. if (options.hoistStatic) {
  14908. hoistStatic(root, context);
  14909. }
  14910. if (!options.ssr) {
  14911. createRootCodegen(root, context);
  14912. }
  14913. // finalize meta information
  14914. root.helpers = new Set([...context.helpers.keys()]);
  14915. root.components = [...context.components];
  14916. root.directives = [...context.directives];
  14917. root.imports = context.imports;
  14918. root.hoists = context.hoists;
  14919. root.temps = context.temps;
  14920. root.cached = context.cached;
  14921. }
  14922. function createRootCodegen(root, context) {
  14923. const { helper } = context;
  14924. const { children } = root;
  14925. if (children.length === 1) {
  14926. const child = children[0];
  14927. // if the single child is an element, turn it into a block.
  14928. if (isSingleElementRoot(root, child) && child.codegenNode) {
  14929. // single element root is never hoisted so codegenNode will never be
  14930. // SimpleExpressionNode
  14931. const codegenNode = child.codegenNode;
  14932. if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  14933. makeBlock(codegenNode, context);
  14934. }
  14935. root.codegenNode = codegenNode;
  14936. }
  14937. else {
  14938. // - single <slot/>, IfNode, ForNode: already blocks.
  14939. // - single text node: always patched.
  14940. // root codegen falls through via genNode()
  14941. root.codegenNode = child;
  14942. }
  14943. }
  14944. else if (children.length > 1) {
  14945. // root has multiple nodes - return a fragment block.
  14946. let patchFlag = 64 /* PatchFlags.STABLE_FRAGMENT */;
  14947. let patchFlagText = PatchFlagNames[64 /* PatchFlags.STABLE_FRAGMENT */];
  14948. // check if the fragment actually contains a single valid child with
  14949. // the rest being comments
  14950. if (children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */).length === 1) {
  14951. patchFlag |= 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */;
  14952. patchFlagText += `, ${PatchFlagNames[2048 /* PatchFlags.DEV_ROOT_FRAGMENT */]}`;
  14953. }
  14954. root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, undefined, false /* isComponent */);
  14955. }
  14956. else ;
  14957. }
  14958. function traverseChildren(parent, context) {
  14959. let i = 0;
  14960. const nodeRemoved = () => {
  14961. i--;
  14962. };
  14963. for (; i < parent.children.length; i++) {
  14964. const child = parent.children[i];
  14965. if (isString$2(child))
  14966. continue;
  14967. context.parent = parent;
  14968. context.childIndex = i;
  14969. context.onNodeRemoved = nodeRemoved;
  14970. traverseNode(child, context);
  14971. }
  14972. }
  14973. function traverseNode(node, context) {
  14974. context.currentNode = node;
  14975. // apply transform plugins
  14976. const { nodeTransforms } = context;
  14977. const exitFns = [];
  14978. for (let i = 0; i < nodeTransforms.length; i++) {
  14979. const onExit = nodeTransforms[i](node, context);
  14980. if (onExit) {
  14981. if (isArray$3(onExit)) {
  14982. exitFns.push(...onExit);
  14983. }
  14984. else {
  14985. exitFns.push(onExit);
  14986. }
  14987. }
  14988. if (!context.currentNode) {
  14989. // node was removed
  14990. return;
  14991. }
  14992. else {
  14993. // node may have been replaced
  14994. node = context.currentNode;
  14995. }
  14996. }
  14997. switch (node.type) {
  14998. case 3 /* NodeTypes.COMMENT */:
  14999. if (!context.ssr) {
  15000. // inject import for the Comment symbol, which is needed for creating
  15001. // comment nodes with `createVNode`
  15002. context.helper(CREATE_COMMENT);
  15003. }
  15004. break;
  15005. case 5 /* NodeTypes.INTERPOLATION */:
  15006. // no need to traverse, but we need to inject toString helper
  15007. if (!context.ssr) {
  15008. context.helper(TO_DISPLAY_STRING);
  15009. }
  15010. break;
  15011. // for container types, further traverse downwards
  15012. case 9 /* NodeTypes.IF */:
  15013. for (let i = 0; i < node.branches.length; i++) {
  15014. traverseNode(node.branches[i], context);
  15015. }
  15016. break;
  15017. case 10 /* NodeTypes.IF_BRANCH */:
  15018. case 11 /* NodeTypes.FOR */:
  15019. case 1 /* NodeTypes.ELEMENT */:
  15020. case 0 /* NodeTypes.ROOT */:
  15021. traverseChildren(node, context);
  15022. break;
  15023. }
  15024. // exit transforms
  15025. context.currentNode = node;
  15026. let i = exitFns.length;
  15027. while (i--) {
  15028. exitFns[i]();
  15029. }
  15030. }
  15031. function createStructuralDirectiveTransform(name, fn) {
  15032. const matches = isString$2(name)
  15033. ? (n) => n === name
  15034. : (n) => name.test(n);
  15035. return (node, context) => {
  15036. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  15037. const { props } = node;
  15038. // structural directive transforms are not concerned with slots
  15039. // as they are handled separately in vSlot.ts
  15040. if (node.tagType === 3 /* ElementTypes.TEMPLATE */ && props.some(isVSlot)) {
  15041. return;
  15042. }
  15043. const exitFns = [];
  15044. for (let i = 0; i < props.length; i++) {
  15045. const prop = props[i];
  15046. if (prop.type === 7 /* NodeTypes.DIRECTIVE */ && matches(prop.name)) {
  15047. // structural directives are removed to avoid infinite recursion
  15048. // also we remove them *before* applying so that it can further
  15049. // traverse itself in case it moves the node around
  15050. props.splice(i, 1);
  15051. i--;
  15052. const onExit = fn(node, prop, context);
  15053. if (onExit)
  15054. exitFns.push(onExit);
  15055. }
  15056. }
  15057. return exitFns;
  15058. }
  15059. };
  15060. }
  15061. var sourceMap$2 = {};
  15062. var sourceMapGenerator$1 = {};
  15063. var base64Vlq$1 = {};
  15064. var base64$3 = {};
  15065. /* -*- Mode: js; js-indent-level: 2; -*- */
  15066. /*
  15067. * Copyright 2011 Mozilla Foundation and contributors
  15068. * Licensed under the New BSD license. See LICENSE or:
  15069. * http://opensource.org/licenses/BSD-3-Clause
  15070. */
  15071. var intToCharMap$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  15072. /**
  15073. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  15074. */
  15075. base64$3.encode = function (number) {
  15076. if (0 <= number && number < intToCharMap$1.length) {
  15077. return intToCharMap$1[number];
  15078. }
  15079. throw new TypeError("Must be between 0 and 63: " + number);
  15080. };
  15081. /**
  15082. * Decode a single base 64 character code digit to an integer. Returns -1 on
  15083. * failure.
  15084. */
  15085. base64$3.decode = function (charCode) {
  15086. var bigA = 65; // 'A'
  15087. var bigZ = 90; // 'Z'
  15088. var littleA = 97; // 'a'
  15089. var littleZ = 122; // 'z'
  15090. var zero = 48; // '0'
  15091. var nine = 57; // '9'
  15092. var plus = 43; // '+'
  15093. var slash = 47; // '/'
  15094. var littleOffset = 26;
  15095. var numberOffset = 52;
  15096. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  15097. if (bigA <= charCode && charCode <= bigZ) {
  15098. return (charCode - bigA);
  15099. }
  15100. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  15101. if (littleA <= charCode && charCode <= littleZ) {
  15102. return (charCode - littleA + littleOffset);
  15103. }
  15104. // 52 - 61: 0123456789
  15105. if (zero <= charCode && charCode <= nine) {
  15106. return (charCode - zero + numberOffset);
  15107. }
  15108. // 62: +
  15109. if (charCode == plus) {
  15110. return 62;
  15111. }
  15112. // 63: /
  15113. if (charCode == slash) {
  15114. return 63;
  15115. }
  15116. // Invalid base64 digit.
  15117. return -1;
  15118. };
  15119. /* -*- Mode: js; js-indent-level: 2; -*- */
  15120. /*
  15121. * Copyright 2011 Mozilla Foundation and contributors
  15122. * Licensed under the New BSD license. See LICENSE or:
  15123. * http://opensource.org/licenses/BSD-3-Clause
  15124. *
  15125. * Based on the Base 64 VLQ implementation in Closure Compiler:
  15126. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  15127. *
  15128. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  15129. * Redistribution and use in source and binary forms, with or without
  15130. * modification, are permitted provided that the following conditions are
  15131. * met:
  15132. *
  15133. * * Redistributions of source code must retain the above copyright
  15134. * notice, this list of conditions and the following disclaimer.
  15135. * * Redistributions in binary form must reproduce the above
  15136. * copyright notice, this list of conditions and the following
  15137. * disclaimer in the documentation and/or other materials provided
  15138. * with the distribution.
  15139. * * Neither the name of Google Inc. nor the names of its
  15140. * contributors may be used to endorse or promote products derived
  15141. * from this software without specific prior written permission.
  15142. *
  15143. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  15144. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  15145. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  15146. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  15147. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  15148. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  15149. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  15150. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  15151. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  15152. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  15153. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  15154. */
  15155. var base64$2 = base64$3;
  15156. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  15157. // length quantities we use in the source map spec, the first bit is the sign,
  15158. // the next four bits are the actual value, and the 6th bit is the
  15159. // continuation bit. The continuation bit tells us whether there are more
  15160. // digits in this value following this digit.
  15161. //
  15162. // Continuation
  15163. // | Sign
  15164. // | |
  15165. // V V
  15166. // 101011
  15167. var VLQ_BASE_SHIFT$1 = 5;
  15168. // binary: 100000
  15169. var VLQ_BASE$1 = 1 << VLQ_BASE_SHIFT$1;
  15170. // binary: 011111
  15171. var VLQ_BASE_MASK$1 = VLQ_BASE$1 - 1;
  15172. // binary: 100000
  15173. var VLQ_CONTINUATION_BIT$1 = VLQ_BASE$1;
  15174. /**
  15175. * Converts from a two-complement value to a value where the sign bit is
  15176. * placed in the least significant bit. For example, as decimals:
  15177. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  15178. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  15179. */
  15180. function toVLQSigned$1(aValue) {
  15181. return aValue < 0
  15182. ? ((-aValue) << 1) + 1
  15183. : (aValue << 1) + 0;
  15184. }
  15185. /**
  15186. * Converts to a two-complement value from a value where the sign bit is
  15187. * placed in the least significant bit. For example, as decimals:
  15188. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  15189. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  15190. */
  15191. function fromVLQSigned$1(aValue) {
  15192. var isNegative = (aValue & 1) === 1;
  15193. var shifted = aValue >> 1;
  15194. return isNegative
  15195. ? -shifted
  15196. : shifted;
  15197. }
  15198. /**
  15199. * Returns the base 64 VLQ encoded value.
  15200. */
  15201. base64Vlq$1.encode = function base64VLQ_encode(aValue) {
  15202. var encoded = "";
  15203. var digit;
  15204. var vlq = toVLQSigned$1(aValue);
  15205. do {
  15206. digit = vlq & VLQ_BASE_MASK$1;
  15207. vlq >>>= VLQ_BASE_SHIFT$1;
  15208. if (vlq > 0) {
  15209. // There are still more digits in this value, so we must make sure the
  15210. // continuation bit is marked.
  15211. digit |= VLQ_CONTINUATION_BIT$1;
  15212. }
  15213. encoded += base64$2.encode(digit);
  15214. } while (vlq > 0);
  15215. return encoded;
  15216. };
  15217. /**
  15218. * Decodes the next base 64 VLQ value from the given string and returns the
  15219. * value and the rest of the string via the out parameter.
  15220. */
  15221. base64Vlq$1.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  15222. var strLen = aStr.length;
  15223. var result = 0;
  15224. var shift = 0;
  15225. var continuation, digit;
  15226. do {
  15227. if (aIndex >= strLen) {
  15228. throw new Error("Expected more digits in base 64 VLQ value.");
  15229. }
  15230. digit = base64$2.decode(aStr.charCodeAt(aIndex++));
  15231. if (digit === -1) {
  15232. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  15233. }
  15234. continuation = !!(digit & VLQ_CONTINUATION_BIT$1);
  15235. digit &= VLQ_BASE_MASK$1;
  15236. result = result + (digit << shift);
  15237. shift += VLQ_BASE_SHIFT$1;
  15238. } while (continuation);
  15239. aOutParam.value = fromVLQSigned$1(result);
  15240. aOutParam.rest = aIndex;
  15241. };
  15242. var util$c = {};
  15243. /* -*- Mode: js; js-indent-level: 2; -*- */
  15244. (function (exports) {
  15245. /*
  15246. * Copyright 2011 Mozilla Foundation and contributors
  15247. * Licensed under the New BSD license. See LICENSE or:
  15248. * http://opensource.org/licenses/BSD-3-Clause
  15249. */
  15250. /**
  15251. * This is a helper function for getting values from parameter/options
  15252. * objects.
  15253. *
  15254. * @param args The object we are extracting values from
  15255. * @param name The name of the property we are getting.
  15256. * @param defaultValue An optional value to return if the property is missing
  15257. * from the object. If this is not specified and the property is missing, an
  15258. * error will be thrown.
  15259. */
  15260. function getArg(aArgs, aName, aDefaultValue) {
  15261. if (aName in aArgs) {
  15262. return aArgs[aName];
  15263. } else if (arguments.length === 3) {
  15264. return aDefaultValue;
  15265. } else {
  15266. throw new Error('"' + aName + '" is a required argument.');
  15267. }
  15268. }
  15269. exports.getArg = getArg;
  15270. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  15271. var dataUrlRegexp = /^data:.+\,.+$/;
  15272. function urlParse(aUrl) {
  15273. var match = aUrl.match(urlRegexp);
  15274. if (!match) {
  15275. return null;
  15276. }
  15277. return {
  15278. scheme: match[1],
  15279. auth: match[2],
  15280. host: match[3],
  15281. port: match[4],
  15282. path: match[5]
  15283. };
  15284. }
  15285. exports.urlParse = urlParse;
  15286. function urlGenerate(aParsedUrl) {
  15287. var url = '';
  15288. if (aParsedUrl.scheme) {
  15289. url += aParsedUrl.scheme + ':';
  15290. }
  15291. url += '//';
  15292. if (aParsedUrl.auth) {
  15293. url += aParsedUrl.auth + '@';
  15294. }
  15295. if (aParsedUrl.host) {
  15296. url += aParsedUrl.host;
  15297. }
  15298. if (aParsedUrl.port) {
  15299. url += ":" + aParsedUrl.port;
  15300. }
  15301. if (aParsedUrl.path) {
  15302. url += aParsedUrl.path;
  15303. }
  15304. return url;
  15305. }
  15306. exports.urlGenerate = urlGenerate;
  15307. /**
  15308. * Normalizes a path, or the path portion of a URL:
  15309. *
  15310. * - Replaces consecutive slashes with one slash.
  15311. * - Removes unnecessary '.' parts.
  15312. * - Removes unnecessary '<dir>/..' parts.
  15313. *
  15314. * Based on code in the Node.js 'path' core module.
  15315. *
  15316. * @param aPath The path or url to normalize.
  15317. */
  15318. function normalize(aPath) {
  15319. var path = aPath;
  15320. var url = urlParse(aPath);
  15321. if (url) {
  15322. if (!url.path) {
  15323. return aPath;
  15324. }
  15325. path = url.path;
  15326. }
  15327. var isAbsolute = exports.isAbsolute(path);
  15328. var parts = path.split(/\/+/);
  15329. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  15330. part = parts[i];
  15331. if (part === '.') {
  15332. parts.splice(i, 1);
  15333. } else if (part === '..') {
  15334. up++;
  15335. } else if (up > 0) {
  15336. if (part === '') {
  15337. // The first part is blank if the path is absolute. Trying to go
  15338. // above the root is a no-op. Therefore we can remove all '..' parts
  15339. // directly after the root.
  15340. parts.splice(i + 1, up);
  15341. up = 0;
  15342. } else {
  15343. parts.splice(i, 2);
  15344. up--;
  15345. }
  15346. }
  15347. }
  15348. path = parts.join('/');
  15349. if (path === '') {
  15350. path = isAbsolute ? '/' : '.';
  15351. }
  15352. if (url) {
  15353. url.path = path;
  15354. return urlGenerate(url);
  15355. }
  15356. return path;
  15357. }
  15358. exports.normalize = normalize;
  15359. /**
  15360. * Joins two paths/URLs.
  15361. *
  15362. * @param aRoot The root path or URL.
  15363. * @param aPath The path or URL to be joined with the root.
  15364. *
  15365. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  15366. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  15367. * first.
  15368. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  15369. * is updated with the result and aRoot is returned. Otherwise the result
  15370. * is returned.
  15371. * - If aPath is absolute, the result is aPath.
  15372. * - Otherwise the two paths are joined with a slash.
  15373. * - Joining for example 'http://' and 'www.example.com' is also supported.
  15374. */
  15375. function join(aRoot, aPath) {
  15376. if (aRoot === "") {
  15377. aRoot = ".";
  15378. }
  15379. if (aPath === "") {
  15380. aPath = ".";
  15381. }
  15382. var aPathUrl = urlParse(aPath);
  15383. var aRootUrl = urlParse(aRoot);
  15384. if (aRootUrl) {
  15385. aRoot = aRootUrl.path || '/';
  15386. }
  15387. // `join(foo, '//www.example.org')`
  15388. if (aPathUrl && !aPathUrl.scheme) {
  15389. if (aRootUrl) {
  15390. aPathUrl.scheme = aRootUrl.scheme;
  15391. }
  15392. return urlGenerate(aPathUrl);
  15393. }
  15394. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  15395. return aPath;
  15396. }
  15397. // `join('http://', 'www.example.com')`
  15398. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  15399. aRootUrl.host = aPath;
  15400. return urlGenerate(aRootUrl);
  15401. }
  15402. var joined = aPath.charAt(0) === '/'
  15403. ? aPath
  15404. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  15405. if (aRootUrl) {
  15406. aRootUrl.path = joined;
  15407. return urlGenerate(aRootUrl);
  15408. }
  15409. return joined;
  15410. }
  15411. exports.join = join;
  15412. exports.isAbsolute = function (aPath) {
  15413. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  15414. };
  15415. /**
  15416. * Make a path relative to a URL or another path.
  15417. *
  15418. * @param aRoot The root path or URL.
  15419. * @param aPath The path or URL to be made relative to aRoot.
  15420. */
  15421. function relative(aRoot, aPath) {
  15422. if (aRoot === "") {
  15423. aRoot = ".";
  15424. }
  15425. aRoot = aRoot.replace(/\/$/, '');
  15426. // It is possible for the path to be above the root. In this case, simply
  15427. // checking whether the root is a prefix of the path won't work. Instead, we
  15428. // need to remove components from the root one by one, until either we find
  15429. // a prefix that fits, or we run out of components to remove.
  15430. var level = 0;
  15431. while (aPath.indexOf(aRoot + '/') !== 0) {
  15432. var index = aRoot.lastIndexOf("/");
  15433. if (index < 0) {
  15434. return aPath;
  15435. }
  15436. // If the only part of the root that is left is the scheme (i.e. http://,
  15437. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  15438. // have exhausted all components, so the path is not relative to the root.
  15439. aRoot = aRoot.slice(0, index);
  15440. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  15441. return aPath;
  15442. }
  15443. ++level;
  15444. }
  15445. // Make sure we add a "../" for each component we removed from the root.
  15446. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  15447. }
  15448. exports.relative = relative;
  15449. var supportsNullProto = (function () {
  15450. var obj = Object.create(null);
  15451. return !('__proto__' in obj);
  15452. }());
  15453. function identity (s) {
  15454. return s;
  15455. }
  15456. /**
  15457. * Because behavior goes wacky when you set `__proto__` on objects, we
  15458. * have to prefix all the strings in our set with an arbitrary character.
  15459. *
  15460. * See https://github.com/mozilla/source-map/pull/31 and
  15461. * https://github.com/mozilla/source-map/issues/30
  15462. *
  15463. * @param String aStr
  15464. */
  15465. function toSetString(aStr) {
  15466. if (isProtoString(aStr)) {
  15467. return '$' + aStr;
  15468. }
  15469. return aStr;
  15470. }
  15471. exports.toSetString = supportsNullProto ? identity : toSetString;
  15472. function fromSetString(aStr) {
  15473. if (isProtoString(aStr)) {
  15474. return aStr.slice(1);
  15475. }
  15476. return aStr;
  15477. }
  15478. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  15479. function isProtoString(s) {
  15480. if (!s) {
  15481. return false;
  15482. }
  15483. var length = s.length;
  15484. if (length < 9 /* "__proto__".length */) {
  15485. return false;
  15486. }
  15487. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  15488. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  15489. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  15490. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  15491. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  15492. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  15493. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  15494. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  15495. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  15496. return false;
  15497. }
  15498. for (var i = length - 10; i >= 0; i--) {
  15499. if (s.charCodeAt(i) !== 36 /* '$' */) {
  15500. return false;
  15501. }
  15502. }
  15503. return true;
  15504. }
  15505. /**
  15506. * Comparator between two mappings where the original positions are compared.
  15507. *
  15508. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  15509. * mappings with the same original source/line/column, but different generated
  15510. * line and column the same. Useful when searching for a mapping with a
  15511. * stubbed out mapping.
  15512. */
  15513. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  15514. var cmp = strcmp(mappingA.source, mappingB.source);
  15515. if (cmp !== 0) {
  15516. return cmp;
  15517. }
  15518. cmp = mappingA.originalLine - mappingB.originalLine;
  15519. if (cmp !== 0) {
  15520. return cmp;
  15521. }
  15522. cmp = mappingA.originalColumn - mappingB.originalColumn;
  15523. if (cmp !== 0 || onlyCompareOriginal) {
  15524. return cmp;
  15525. }
  15526. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  15527. if (cmp !== 0) {
  15528. return cmp;
  15529. }
  15530. cmp = mappingA.generatedLine - mappingB.generatedLine;
  15531. if (cmp !== 0) {
  15532. return cmp;
  15533. }
  15534. return strcmp(mappingA.name, mappingB.name);
  15535. }
  15536. exports.compareByOriginalPositions = compareByOriginalPositions;
  15537. /**
  15538. * Comparator between two mappings with deflated source and name indices where
  15539. * the generated positions are compared.
  15540. *
  15541. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  15542. * mappings with the same generated line and column, but different
  15543. * source/name/original line and column the same. Useful when searching for a
  15544. * mapping with a stubbed out mapping.
  15545. */
  15546. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  15547. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  15548. if (cmp !== 0) {
  15549. return cmp;
  15550. }
  15551. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  15552. if (cmp !== 0 || onlyCompareGenerated) {
  15553. return cmp;
  15554. }
  15555. cmp = strcmp(mappingA.source, mappingB.source);
  15556. if (cmp !== 0) {
  15557. return cmp;
  15558. }
  15559. cmp = mappingA.originalLine - mappingB.originalLine;
  15560. if (cmp !== 0) {
  15561. return cmp;
  15562. }
  15563. cmp = mappingA.originalColumn - mappingB.originalColumn;
  15564. if (cmp !== 0) {
  15565. return cmp;
  15566. }
  15567. return strcmp(mappingA.name, mappingB.name);
  15568. }
  15569. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  15570. function strcmp(aStr1, aStr2) {
  15571. if (aStr1 === aStr2) {
  15572. return 0;
  15573. }
  15574. if (aStr1 === null) {
  15575. return 1; // aStr2 !== null
  15576. }
  15577. if (aStr2 === null) {
  15578. return -1; // aStr1 !== null
  15579. }
  15580. if (aStr1 > aStr2) {
  15581. return 1;
  15582. }
  15583. return -1;
  15584. }
  15585. /**
  15586. * Comparator between two mappings with inflated source and name strings where
  15587. * the generated positions are compared.
  15588. */
  15589. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  15590. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  15591. if (cmp !== 0) {
  15592. return cmp;
  15593. }
  15594. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  15595. if (cmp !== 0) {
  15596. return cmp;
  15597. }
  15598. cmp = strcmp(mappingA.source, mappingB.source);
  15599. if (cmp !== 0) {
  15600. return cmp;
  15601. }
  15602. cmp = mappingA.originalLine - mappingB.originalLine;
  15603. if (cmp !== 0) {
  15604. return cmp;
  15605. }
  15606. cmp = mappingA.originalColumn - mappingB.originalColumn;
  15607. if (cmp !== 0) {
  15608. return cmp;
  15609. }
  15610. return strcmp(mappingA.name, mappingB.name);
  15611. }
  15612. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  15613. /**
  15614. * Strip any JSON XSSI avoidance prefix from the string (as documented
  15615. * in the source maps specification), and then parse the string as
  15616. * JSON.
  15617. */
  15618. function parseSourceMapInput(str) {
  15619. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  15620. }
  15621. exports.parseSourceMapInput = parseSourceMapInput;
  15622. /**
  15623. * Compute the URL of a source given the the source root, the source's
  15624. * URL, and the source map's URL.
  15625. */
  15626. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  15627. sourceURL = sourceURL || '';
  15628. if (sourceRoot) {
  15629. // This follows what Chrome does.
  15630. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  15631. sourceRoot += '/';
  15632. }
  15633. // The spec says:
  15634. // Line 4: An optional source root, useful for relocating source
  15635. // files on a server or removing repeated values in the
  15636. // “sources” entry. This value is prepended to the individual
  15637. // entries in the “source” field.
  15638. sourceURL = sourceRoot + sourceURL;
  15639. }
  15640. // Historically, SourceMapConsumer did not take the sourceMapURL as
  15641. // a parameter. This mode is still somewhat supported, which is why
  15642. // this code block is conditional. However, it's preferable to pass
  15643. // the source map URL to SourceMapConsumer, so that this function
  15644. // can implement the source URL resolution algorithm as outlined in
  15645. // the spec. This block is basically the equivalent of:
  15646. // new URL(sourceURL, sourceMapURL).toString()
  15647. // ... except it avoids using URL, which wasn't available in the
  15648. // older releases of node still supported by this library.
  15649. //
  15650. // The spec says:
  15651. // If the sources are not absolute URLs after prepending of the
  15652. // “sourceRoot”, the sources are resolved relative to the
  15653. // SourceMap (like resolving script src in a html document).
  15654. if (sourceMapURL) {
  15655. var parsed = urlParse(sourceMapURL);
  15656. if (!parsed) {
  15657. throw new Error("sourceMapURL could not be parsed");
  15658. }
  15659. if (parsed.path) {
  15660. // Strip the last path component, but keep the "/".
  15661. var index = parsed.path.lastIndexOf('/');
  15662. if (index >= 0) {
  15663. parsed.path = parsed.path.substring(0, index + 1);
  15664. }
  15665. }
  15666. sourceURL = join(urlGenerate(parsed), sourceURL);
  15667. }
  15668. return normalize(sourceURL);
  15669. }
  15670. exports.computeSourceURL = computeSourceURL;
  15671. } (util$c));
  15672. var arraySet$1 = {};
  15673. /* -*- Mode: js; js-indent-level: 2; -*- */
  15674. /*
  15675. * Copyright 2011 Mozilla Foundation and contributors
  15676. * Licensed under the New BSD license. See LICENSE or:
  15677. * http://opensource.org/licenses/BSD-3-Clause
  15678. */
  15679. var util$b = util$c;
  15680. var has$1 = Object.prototype.hasOwnProperty;
  15681. var hasNativeMap$1 = typeof Map !== "undefined";
  15682. /**
  15683. * A data structure which is a combination of an array and a set. Adding a new
  15684. * member is O(1), testing for membership is O(1), and finding the index of an
  15685. * element is O(1). Removing elements from the set is not supported. Only
  15686. * strings are supported for membership.
  15687. */
  15688. function ArraySet$5() {
  15689. this._array = [];
  15690. this._set = hasNativeMap$1 ? new Map() : Object.create(null);
  15691. }
  15692. /**
  15693. * Static method for creating ArraySet instances from an existing array.
  15694. */
  15695. ArraySet$5.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  15696. var set = new ArraySet$5();
  15697. for (var i = 0, len = aArray.length; i < len; i++) {
  15698. set.add(aArray[i], aAllowDuplicates);
  15699. }
  15700. return set;
  15701. };
  15702. /**
  15703. * Return how many unique items are in this ArraySet. If duplicates have been
  15704. * added, than those do not count towards the size.
  15705. *
  15706. * @returns Number
  15707. */
  15708. ArraySet$5.prototype.size = function ArraySet_size() {
  15709. return hasNativeMap$1 ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  15710. };
  15711. /**
  15712. * Add the given string to this set.
  15713. *
  15714. * @param String aStr
  15715. */
  15716. ArraySet$5.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  15717. var sStr = hasNativeMap$1 ? aStr : util$b.toSetString(aStr);
  15718. var isDuplicate = hasNativeMap$1 ? this.has(aStr) : has$1.call(this._set, sStr);
  15719. var idx = this._array.length;
  15720. if (!isDuplicate || aAllowDuplicates) {
  15721. this._array.push(aStr);
  15722. }
  15723. if (!isDuplicate) {
  15724. if (hasNativeMap$1) {
  15725. this._set.set(aStr, idx);
  15726. } else {
  15727. this._set[sStr] = idx;
  15728. }
  15729. }
  15730. };
  15731. /**
  15732. * Is the given string a member of this set?
  15733. *
  15734. * @param String aStr
  15735. */
  15736. ArraySet$5.prototype.has = function ArraySet_has(aStr) {
  15737. if (hasNativeMap$1) {
  15738. return this._set.has(aStr);
  15739. } else {
  15740. var sStr = util$b.toSetString(aStr);
  15741. return has$1.call(this._set, sStr);
  15742. }
  15743. };
  15744. /**
  15745. * What is the index of the given string in the array?
  15746. *
  15747. * @param String aStr
  15748. */
  15749. ArraySet$5.prototype.indexOf = function ArraySet_indexOf(aStr) {
  15750. if (hasNativeMap$1) {
  15751. var idx = this._set.get(aStr);
  15752. if (idx >= 0) {
  15753. return idx;
  15754. }
  15755. } else {
  15756. var sStr = util$b.toSetString(aStr);
  15757. if (has$1.call(this._set, sStr)) {
  15758. return this._set[sStr];
  15759. }
  15760. }
  15761. throw new Error('"' + aStr + '" is not in the set.');
  15762. };
  15763. /**
  15764. * What is the element at the given index?
  15765. *
  15766. * @param Number aIdx
  15767. */
  15768. ArraySet$5.prototype.at = function ArraySet_at(aIdx) {
  15769. if (aIdx >= 0 && aIdx < this._array.length) {
  15770. return this._array[aIdx];
  15771. }
  15772. throw new Error('No element indexed by ' + aIdx);
  15773. };
  15774. /**
  15775. * Returns the array representation of this set (which has the proper indices
  15776. * indicated by indexOf). Note that this is a copy of the internal array used
  15777. * for storing the members so that no one can mess with internal state.
  15778. */
  15779. ArraySet$5.prototype.toArray = function ArraySet_toArray() {
  15780. return this._array.slice();
  15781. };
  15782. arraySet$1.ArraySet = ArraySet$5;
  15783. var mappingList$1 = {};
  15784. /* -*- Mode: js; js-indent-level: 2; -*- */
  15785. /*
  15786. * Copyright 2014 Mozilla Foundation and contributors
  15787. * Licensed under the New BSD license. See LICENSE or:
  15788. * http://opensource.org/licenses/BSD-3-Clause
  15789. */
  15790. var util$a = util$c;
  15791. /**
  15792. * Determine whether mappingB is after mappingA with respect to generated
  15793. * position.
  15794. */
  15795. function generatedPositionAfter$1(mappingA, mappingB) {
  15796. // Optimized for most common case
  15797. var lineA = mappingA.generatedLine;
  15798. var lineB = mappingB.generatedLine;
  15799. var columnA = mappingA.generatedColumn;
  15800. var columnB = mappingB.generatedColumn;
  15801. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  15802. util$a.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  15803. }
  15804. /**
  15805. * A data structure to provide a sorted view of accumulated mappings in a
  15806. * performance conscious manner. It trades a neglibable overhead in general
  15807. * case for a large speedup in case of mappings being added in order.
  15808. */
  15809. function MappingList$3() {
  15810. this._array = [];
  15811. this._sorted = true;
  15812. // Serves as infimum
  15813. this._last = {generatedLine: -1, generatedColumn: 0};
  15814. }
  15815. /**
  15816. * Iterate through internal items. This method takes the same arguments that
  15817. * `Array.prototype.forEach` takes.
  15818. *
  15819. * NOTE: The order of the mappings is NOT guaranteed.
  15820. */
  15821. MappingList$3.prototype.unsortedForEach =
  15822. function MappingList_forEach(aCallback, aThisArg) {
  15823. this._array.forEach(aCallback, aThisArg);
  15824. };
  15825. /**
  15826. * Add the given source mapping.
  15827. *
  15828. * @param Object aMapping
  15829. */
  15830. MappingList$3.prototype.add = function MappingList_add(aMapping) {
  15831. if (generatedPositionAfter$1(this._last, aMapping)) {
  15832. this._last = aMapping;
  15833. this._array.push(aMapping);
  15834. } else {
  15835. this._sorted = false;
  15836. this._array.push(aMapping);
  15837. }
  15838. };
  15839. /**
  15840. * Returns the flat, sorted array of mappings. The mappings are sorted by
  15841. * generated position.
  15842. *
  15843. * WARNING: This method returns internal data without copying, for
  15844. * performance. The return value must NOT be mutated, and should be treated as
  15845. * an immutable borrow. If you want to take ownership, you must make your own
  15846. * copy.
  15847. */
  15848. MappingList$3.prototype.toArray = function MappingList_toArray() {
  15849. if (!this._sorted) {
  15850. this._array.sort(util$a.compareByGeneratedPositionsInflated);
  15851. this._sorted = true;
  15852. }
  15853. return this._array;
  15854. };
  15855. mappingList$1.MappingList = MappingList$3;
  15856. /* -*- Mode: js; js-indent-level: 2; -*- */
  15857. /*
  15858. * Copyright 2011 Mozilla Foundation and contributors
  15859. * Licensed under the New BSD license. See LICENSE or:
  15860. * http://opensource.org/licenses/BSD-3-Clause
  15861. */
  15862. var base64VLQ$3 = base64Vlq$1;
  15863. var util$9 = util$c;
  15864. var ArraySet$4 = arraySet$1.ArraySet;
  15865. var MappingList$2 = mappingList$1.MappingList;
  15866. /**
  15867. * An instance of the SourceMapGenerator represents a source map which is
  15868. * being built incrementally. You may pass an object with the following
  15869. * properties:
  15870. *
  15871. * - file: The filename of the generated source.
  15872. * - sourceRoot: A root for all relative URLs in this source map.
  15873. */
  15874. function SourceMapGenerator$8(aArgs) {
  15875. if (!aArgs) {
  15876. aArgs = {};
  15877. }
  15878. this._file = util$9.getArg(aArgs, 'file', null);
  15879. this._sourceRoot = util$9.getArg(aArgs, 'sourceRoot', null);
  15880. this._skipValidation = util$9.getArg(aArgs, 'skipValidation', false);
  15881. this._sources = new ArraySet$4();
  15882. this._names = new ArraySet$4();
  15883. this._mappings = new MappingList$2();
  15884. this._sourcesContents = null;
  15885. }
  15886. SourceMapGenerator$8.prototype._version = 3;
  15887. /**
  15888. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  15889. *
  15890. * @param aSourceMapConsumer The SourceMap.
  15891. */
  15892. SourceMapGenerator$8.fromSourceMap =
  15893. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  15894. var sourceRoot = aSourceMapConsumer.sourceRoot;
  15895. var generator = new SourceMapGenerator$8({
  15896. file: aSourceMapConsumer.file,
  15897. sourceRoot: sourceRoot
  15898. });
  15899. aSourceMapConsumer.eachMapping(function (mapping) {
  15900. var newMapping = {
  15901. generated: {
  15902. line: mapping.generatedLine,
  15903. column: mapping.generatedColumn
  15904. }
  15905. };
  15906. if (mapping.source != null) {
  15907. newMapping.source = mapping.source;
  15908. if (sourceRoot != null) {
  15909. newMapping.source = util$9.relative(sourceRoot, newMapping.source);
  15910. }
  15911. newMapping.original = {
  15912. line: mapping.originalLine,
  15913. column: mapping.originalColumn
  15914. };
  15915. if (mapping.name != null) {
  15916. newMapping.name = mapping.name;
  15917. }
  15918. }
  15919. generator.addMapping(newMapping);
  15920. });
  15921. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  15922. var sourceRelative = sourceFile;
  15923. if (sourceRoot !== null) {
  15924. sourceRelative = util$9.relative(sourceRoot, sourceFile);
  15925. }
  15926. if (!generator._sources.has(sourceRelative)) {
  15927. generator._sources.add(sourceRelative);
  15928. }
  15929. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  15930. if (content != null) {
  15931. generator.setSourceContent(sourceFile, content);
  15932. }
  15933. });
  15934. return generator;
  15935. };
  15936. /**
  15937. * Add a single mapping from original source line and column to the generated
  15938. * source's line and column for this source map being created. The mapping
  15939. * object should have the following properties:
  15940. *
  15941. * - generated: An object with the generated line and column positions.
  15942. * - original: An object with the original line and column positions.
  15943. * - source: The original source file (relative to the sourceRoot).
  15944. * - name: An optional original token name for this mapping.
  15945. */
  15946. SourceMapGenerator$8.prototype.addMapping =
  15947. function SourceMapGenerator_addMapping(aArgs) {
  15948. var generated = util$9.getArg(aArgs, 'generated');
  15949. var original = util$9.getArg(aArgs, 'original', null);
  15950. var source = util$9.getArg(aArgs, 'source', null);
  15951. var name = util$9.getArg(aArgs, 'name', null);
  15952. if (!this._skipValidation) {
  15953. this._validateMapping(generated, original, source, name);
  15954. }
  15955. if (source != null) {
  15956. source = String(source);
  15957. if (!this._sources.has(source)) {
  15958. this._sources.add(source);
  15959. }
  15960. }
  15961. if (name != null) {
  15962. name = String(name);
  15963. if (!this._names.has(name)) {
  15964. this._names.add(name);
  15965. }
  15966. }
  15967. this._mappings.add({
  15968. generatedLine: generated.line,
  15969. generatedColumn: generated.column,
  15970. originalLine: original != null && original.line,
  15971. originalColumn: original != null && original.column,
  15972. source: source,
  15973. name: name
  15974. });
  15975. };
  15976. /**
  15977. * Set the source content for a source file.
  15978. */
  15979. SourceMapGenerator$8.prototype.setSourceContent =
  15980. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  15981. var source = aSourceFile;
  15982. if (this._sourceRoot != null) {
  15983. source = util$9.relative(this._sourceRoot, source);
  15984. }
  15985. if (aSourceContent != null) {
  15986. // Add the source content to the _sourcesContents map.
  15987. // Create a new _sourcesContents map if the property is null.
  15988. if (!this._sourcesContents) {
  15989. this._sourcesContents = Object.create(null);
  15990. }
  15991. this._sourcesContents[util$9.toSetString(source)] = aSourceContent;
  15992. } else if (this._sourcesContents) {
  15993. // Remove the source file from the _sourcesContents map.
  15994. // If the _sourcesContents map is empty, set the property to null.
  15995. delete this._sourcesContents[util$9.toSetString(source)];
  15996. if (Object.keys(this._sourcesContents).length === 0) {
  15997. this._sourcesContents = null;
  15998. }
  15999. }
  16000. };
  16001. /**
  16002. * Applies the mappings of a sub-source-map for a specific source file to the
  16003. * source map being generated. Each mapping to the supplied source file is
  16004. * rewritten using the supplied source map. Note: The resolution for the
  16005. * resulting mappings is the minimium of this map and the supplied map.
  16006. *
  16007. * @param aSourceMapConsumer The source map to be applied.
  16008. * @param aSourceFile Optional. The filename of the source file.
  16009. * If omitted, SourceMapConsumer's file property will be used.
  16010. * @param aSourceMapPath Optional. The dirname of the path to the source map
  16011. * to be applied. If relative, it is relative to the SourceMapConsumer.
  16012. * This parameter is needed when the two source maps aren't in the same
  16013. * directory, and the source map to be applied contains relative source
  16014. * paths. If so, those relative source paths need to be rewritten
  16015. * relative to the SourceMapGenerator.
  16016. */
  16017. SourceMapGenerator$8.prototype.applySourceMap =
  16018. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  16019. var sourceFile = aSourceFile;
  16020. // If aSourceFile is omitted, we will use the file property of the SourceMap
  16021. if (aSourceFile == null) {
  16022. if (aSourceMapConsumer.file == null) {
  16023. throw new Error(
  16024. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  16025. 'or the source map\'s "file" property. Both were omitted.'
  16026. );
  16027. }
  16028. sourceFile = aSourceMapConsumer.file;
  16029. }
  16030. var sourceRoot = this._sourceRoot;
  16031. // Make "sourceFile" relative if an absolute Url is passed.
  16032. if (sourceRoot != null) {
  16033. sourceFile = util$9.relative(sourceRoot, sourceFile);
  16034. }
  16035. // Applying the SourceMap can add and remove items from the sources and
  16036. // the names array.
  16037. var newSources = new ArraySet$4();
  16038. var newNames = new ArraySet$4();
  16039. // Find mappings for the "sourceFile"
  16040. this._mappings.unsortedForEach(function (mapping) {
  16041. if (mapping.source === sourceFile && mapping.originalLine != null) {
  16042. // Check if it can be mapped by the source map, then update the mapping.
  16043. var original = aSourceMapConsumer.originalPositionFor({
  16044. line: mapping.originalLine,
  16045. column: mapping.originalColumn
  16046. });
  16047. if (original.source != null) {
  16048. // Copy mapping
  16049. mapping.source = original.source;
  16050. if (aSourceMapPath != null) {
  16051. mapping.source = util$9.join(aSourceMapPath, mapping.source);
  16052. }
  16053. if (sourceRoot != null) {
  16054. mapping.source = util$9.relative(sourceRoot, mapping.source);
  16055. }
  16056. mapping.originalLine = original.line;
  16057. mapping.originalColumn = original.column;
  16058. if (original.name != null) {
  16059. mapping.name = original.name;
  16060. }
  16061. }
  16062. }
  16063. var source = mapping.source;
  16064. if (source != null && !newSources.has(source)) {
  16065. newSources.add(source);
  16066. }
  16067. var name = mapping.name;
  16068. if (name != null && !newNames.has(name)) {
  16069. newNames.add(name);
  16070. }
  16071. }, this);
  16072. this._sources = newSources;
  16073. this._names = newNames;
  16074. // Copy sourcesContents of applied map.
  16075. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  16076. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  16077. if (content != null) {
  16078. if (aSourceMapPath != null) {
  16079. sourceFile = util$9.join(aSourceMapPath, sourceFile);
  16080. }
  16081. if (sourceRoot != null) {
  16082. sourceFile = util$9.relative(sourceRoot, sourceFile);
  16083. }
  16084. this.setSourceContent(sourceFile, content);
  16085. }
  16086. }, this);
  16087. };
  16088. /**
  16089. * A mapping can have one of the three levels of data:
  16090. *
  16091. * 1. Just the generated position.
  16092. * 2. The Generated position, original position, and original source.
  16093. * 3. Generated and original position, original source, as well as a name
  16094. * token.
  16095. *
  16096. * To maintain consistency, we validate that any new mapping being added falls
  16097. * in to one of these categories.
  16098. */
  16099. SourceMapGenerator$8.prototype._validateMapping =
  16100. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  16101. aName) {
  16102. // When aOriginal is truthy but has empty values for .line and .column,
  16103. // it is most likely a programmer error. In this case we throw a very
  16104. // specific error message to try to guide them the right way.
  16105. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  16106. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  16107. throw new Error(
  16108. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  16109. 'the original mapping entirely and only map the generated position. If so, pass ' +
  16110. 'null for the original mapping instead of an object with empty or null values.'
  16111. );
  16112. }
  16113. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  16114. && aGenerated.line > 0 && aGenerated.column >= 0
  16115. && !aOriginal && !aSource && !aName) {
  16116. // Case 1.
  16117. return;
  16118. }
  16119. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  16120. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  16121. && aGenerated.line > 0 && aGenerated.column >= 0
  16122. && aOriginal.line > 0 && aOriginal.column >= 0
  16123. && aSource) {
  16124. // Cases 2 and 3.
  16125. return;
  16126. }
  16127. else {
  16128. throw new Error('Invalid mapping: ' + JSON.stringify({
  16129. generated: aGenerated,
  16130. source: aSource,
  16131. original: aOriginal,
  16132. name: aName
  16133. }));
  16134. }
  16135. };
  16136. /**
  16137. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  16138. * specified by the source map format.
  16139. */
  16140. SourceMapGenerator$8.prototype._serializeMappings =
  16141. function SourceMapGenerator_serializeMappings() {
  16142. var previousGeneratedColumn = 0;
  16143. var previousGeneratedLine = 1;
  16144. var previousOriginalColumn = 0;
  16145. var previousOriginalLine = 0;
  16146. var previousName = 0;
  16147. var previousSource = 0;
  16148. var result = '';
  16149. var next;
  16150. var mapping;
  16151. var nameIdx;
  16152. var sourceIdx;
  16153. var mappings = this._mappings.toArray();
  16154. for (var i = 0, len = mappings.length; i < len; i++) {
  16155. mapping = mappings[i];
  16156. next = '';
  16157. if (mapping.generatedLine !== previousGeneratedLine) {
  16158. previousGeneratedColumn = 0;
  16159. while (mapping.generatedLine !== previousGeneratedLine) {
  16160. next += ';';
  16161. previousGeneratedLine++;
  16162. }
  16163. }
  16164. else {
  16165. if (i > 0) {
  16166. if (!util$9.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  16167. continue;
  16168. }
  16169. next += ',';
  16170. }
  16171. }
  16172. next += base64VLQ$3.encode(mapping.generatedColumn
  16173. - previousGeneratedColumn);
  16174. previousGeneratedColumn = mapping.generatedColumn;
  16175. if (mapping.source != null) {
  16176. sourceIdx = this._sources.indexOf(mapping.source);
  16177. next += base64VLQ$3.encode(sourceIdx - previousSource);
  16178. previousSource = sourceIdx;
  16179. // lines are stored 0-based in SourceMap spec version 3
  16180. next += base64VLQ$3.encode(mapping.originalLine - 1
  16181. - previousOriginalLine);
  16182. previousOriginalLine = mapping.originalLine - 1;
  16183. next += base64VLQ$3.encode(mapping.originalColumn
  16184. - previousOriginalColumn);
  16185. previousOriginalColumn = mapping.originalColumn;
  16186. if (mapping.name != null) {
  16187. nameIdx = this._names.indexOf(mapping.name);
  16188. next += base64VLQ$3.encode(nameIdx - previousName);
  16189. previousName = nameIdx;
  16190. }
  16191. }
  16192. result += next;
  16193. }
  16194. return result;
  16195. };
  16196. SourceMapGenerator$8.prototype._generateSourcesContent =
  16197. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  16198. return aSources.map(function (source) {
  16199. if (!this._sourcesContents) {
  16200. return null;
  16201. }
  16202. if (aSourceRoot != null) {
  16203. source = util$9.relative(aSourceRoot, source);
  16204. }
  16205. var key = util$9.toSetString(source);
  16206. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  16207. ? this._sourcesContents[key]
  16208. : null;
  16209. }, this);
  16210. };
  16211. /**
  16212. * Externalize the source map.
  16213. */
  16214. SourceMapGenerator$8.prototype.toJSON =
  16215. function SourceMapGenerator_toJSON() {
  16216. var map = {
  16217. version: this._version,
  16218. sources: this._sources.toArray(),
  16219. names: this._names.toArray(),
  16220. mappings: this._serializeMappings()
  16221. };
  16222. if (this._file != null) {
  16223. map.file = this._file;
  16224. }
  16225. if (this._sourceRoot != null) {
  16226. map.sourceRoot = this._sourceRoot;
  16227. }
  16228. if (this._sourcesContents) {
  16229. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  16230. }
  16231. return map;
  16232. };
  16233. /**
  16234. * Render the source map being generated to a string.
  16235. */
  16236. SourceMapGenerator$8.prototype.toString =
  16237. function SourceMapGenerator_toString() {
  16238. return JSON.stringify(this.toJSON());
  16239. };
  16240. sourceMapGenerator$1.SourceMapGenerator = SourceMapGenerator$8;
  16241. var sourceMapConsumer$1 = {};
  16242. var binarySearch$3 = {};
  16243. /* -*- Mode: js; js-indent-level: 2; -*- */
  16244. (function (exports) {
  16245. /*
  16246. * Copyright 2011 Mozilla Foundation and contributors
  16247. * Licensed under the New BSD license. See LICENSE or:
  16248. * http://opensource.org/licenses/BSD-3-Clause
  16249. */
  16250. exports.GREATEST_LOWER_BOUND = 1;
  16251. exports.LEAST_UPPER_BOUND = 2;
  16252. /**
  16253. * Recursive implementation of binary search.
  16254. *
  16255. * @param aLow Indices here and lower do not contain the needle.
  16256. * @param aHigh Indices here and higher do not contain the needle.
  16257. * @param aNeedle The element being searched for.
  16258. * @param aHaystack The non-empty array being searched.
  16259. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  16260. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  16261. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  16262. * closest element that is smaller than or greater than the one we are
  16263. * searching for, respectively, if the exact element cannot be found.
  16264. */
  16265. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  16266. // This function terminates when one of the following is true:
  16267. //
  16268. // 1. We find the exact element we are looking for.
  16269. //
  16270. // 2. We did not find the exact element, but we can return the index of
  16271. // the next-closest element.
  16272. //
  16273. // 3. We did not find the exact element, and there is no next-closest
  16274. // element than the one we are searching for, so we return -1.
  16275. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  16276. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  16277. if (cmp === 0) {
  16278. // Found the element we are looking for.
  16279. return mid;
  16280. }
  16281. else if (cmp > 0) {
  16282. // Our needle is greater than aHaystack[mid].
  16283. if (aHigh - mid > 1) {
  16284. // The element is in the upper half.
  16285. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  16286. }
  16287. // The exact needle element was not found in this haystack. Determine if
  16288. // we are in termination case (3) or (2) and return the appropriate thing.
  16289. if (aBias == exports.LEAST_UPPER_BOUND) {
  16290. return aHigh < aHaystack.length ? aHigh : -1;
  16291. } else {
  16292. return mid;
  16293. }
  16294. }
  16295. else {
  16296. // Our needle is less than aHaystack[mid].
  16297. if (mid - aLow > 1) {
  16298. // The element is in the lower half.
  16299. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  16300. }
  16301. // we are in termination case (3) or (2) and return the appropriate thing.
  16302. if (aBias == exports.LEAST_UPPER_BOUND) {
  16303. return mid;
  16304. } else {
  16305. return aLow < 0 ? -1 : aLow;
  16306. }
  16307. }
  16308. }
  16309. /**
  16310. * This is an implementation of binary search which will always try and return
  16311. * the index of the closest element if there is no exact hit. This is because
  16312. * mappings between original and generated line/col pairs are single points,
  16313. * and there is an implicit region between each of them, so a miss just means
  16314. * that you aren't on the very start of a region.
  16315. *
  16316. * @param aNeedle The element you are looking for.
  16317. * @param aHaystack The array that is being searched.
  16318. * @param aCompare A function which takes the needle and an element in the
  16319. * array and returns -1, 0, or 1 depending on whether the needle is less
  16320. * than, equal to, or greater than the element, respectively.
  16321. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  16322. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  16323. * closest element that is smaller than or greater than the one we are
  16324. * searching for, respectively, if the exact element cannot be found.
  16325. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  16326. */
  16327. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  16328. if (aHaystack.length === 0) {
  16329. return -1;
  16330. }
  16331. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  16332. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  16333. if (index < 0) {
  16334. return -1;
  16335. }
  16336. // We have found either the exact element, or the next-closest element than
  16337. // the one we are searching for. However, there may be more than one such
  16338. // element. Make sure we always return the smallest of these.
  16339. while (index - 1 >= 0) {
  16340. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  16341. break;
  16342. }
  16343. --index;
  16344. }
  16345. return index;
  16346. };
  16347. } (binarySearch$3));
  16348. var quickSort$3 = {};
  16349. /* -*- Mode: js; js-indent-level: 2; -*- */
  16350. /*
  16351. * Copyright 2011 Mozilla Foundation and contributors
  16352. * Licensed under the New BSD license. See LICENSE or:
  16353. * http://opensource.org/licenses/BSD-3-Clause
  16354. */
  16355. // It turns out that some (most?) JavaScript engines don't self-host
  16356. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  16357. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  16358. // custom comparator function, calling back and forth between the VM's C++ and
  16359. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  16360. // worse generated code for the comparator function than would be optimal. In
  16361. // fact, when sorting with a comparator, these costs outweigh the benefits of
  16362. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  16363. // a ~3500ms mean speed-up in `bench/bench.html`.
  16364. /**
  16365. * Swap the elements indexed by `x` and `y` in the array `ary`.
  16366. *
  16367. * @param {Array} ary
  16368. * The array.
  16369. * @param {Number} x
  16370. * The index of the first item.
  16371. * @param {Number} y
  16372. * The index of the second item.
  16373. */
  16374. function swap$1(ary, x, y) {
  16375. var temp = ary[x];
  16376. ary[x] = ary[y];
  16377. ary[y] = temp;
  16378. }
  16379. /**
  16380. * Returns a random integer within the range `low .. high` inclusive.
  16381. *
  16382. * @param {Number} low
  16383. * The lower bound on the range.
  16384. * @param {Number} high
  16385. * The upper bound on the range.
  16386. */
  16387. function randomIntInRange(low, high) {
  16388. return Math.round(low + (Math.random() * (high - low)));
  16389. }
  16390. /**
  16391. * The Quick Sort algorithm.
  16392. *
  16393. * @param {Array} ary
  16394. * An array to sort.
  16395. * @param {function} comparator
  16396. * Function to use to compare two items.
  16397. * @param {Number} p
  16398. * Start index of the array
  16399. * @param {Number} r
  16400. * End index of the array
  16401. */
  16402. function doQuickSort(ary, comparator, p, r) {
  16403. // If our lower bound is less than our upper bound, we (1) partition the
  16404. // array into two pieces and (2) recurse on each half. If it is not, this is
  16405. // the empty array and our base case.
  16406. if (p < r) {
  16407. // (1) Partitioning.
  16408. //
  16409. // The partitioning chooses a pivot between `p` and `r` and moves all
  16410. // elements that are less than or equal to the pivot to the before it, and
  16411. // all the elements that are greater than it after it. The effect is that
  16412. // once partition is done, the pivot is in the exact place it will be when
  16413. // the array is put in sorted order, and it will not need to be moved
  16414. // again. This runs in O(n) time.
  16415. // Always choose a random pivot so that an input array which is reverse
  16416. // sorted does not cause O(n^2) running time.
  16417. var pivotIndex = randomIntInRange(p, r);
  16418. var i = p - 1;
  16419. swap$1(ary, pivotIndex, r);
  16420. var pivot = ary[r];
  16421. // Immediately after `j` is incremented in this loop, the following hold
  16422. // true:
  16423. //
  16424. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  16425. //
  16426. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  16427. for (var j = p; j < r; j++) {
  16428. if (comparator(ary[j], pivot) <= 0) {
  16429. i += 1;
  16430. swap$1(ary, i, j);
  16431. }
  16432. }
  16433. swap$1(ary, i + 1, j);
  16434. var q = i + 1;
  16435. // (2) Recurse on each half.
  16436. doQuickSort(ary, comparator, p, q - 1);
  16437. doQuickSort(ary, comparator, q + 1, r);
  16438. }
  16439. }
  16440. /**
  16441. * Sort the given array in-place with the given comparator function.
  16442. *
  16443. * @param {Array} ary
  16444. * An array to sort.
  16445. * @param {function} comparator
  16446. * Function to use to compare two items.
  16447. */
  16448. quickSort$3.quickSort = function (ary, comparator) {
  16449. doQuickSort(ary, comparator, 0, ary.length - 1);
  16450. };
  16451. /* -*- Mode: js; js-indent-level: 2; -*- */
  16452. /*
  16453. * Copyright 2011 Mozilla Foundation and contributors
  16454. * Licensed under the New BSD license. See LICENSE or:
  16455. * http://opensource.org/licenses/BSD-3-Clause
  16456. */
  16457. var util$8 = util$c;
  16458. var binarySearch$2 = binarySearch$3;
  16459. var ArraySet$3 = arraySet$1.ArraySet;
  16460. var base64VLQ$2 = base64Vlq$1;
  16461. var quickSort$2 = quickSort$3.quickSort;
  16462. function SourceMapConsumer$6(aSourceMap, aSourceMapURL) {
  16463. var sourceMap = aSourceMap;
  16464. if (typeof aSourceMap === 'string') {
  16465. sourceMap = util$8.parseSourceMapInput(aSourceMap);
  16466. }
  16467. return sourceMap.sections != null
  16468. ? new IndexedSourceMapConsumer$1(sourceMap, aSourceMapURL)
  16469. : new BasicSourceMapConsumer$1(sourceMap, aSourceMapURL);
  16470. }
  16471. SourceMapConsumer$6.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  16472. return BasicSourceMapConsumer$1.fromSourceMap(aSourceMap, aSourceMapURL);
  16473. };
  16474. /**
  16475. * The version of the source mapping spec that we are consuming.
  16476. */
  16477. SourceMapConsumer$6.prototype._version = 3;
  16478. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  16479. // parsed mapping coordinates from the source map's "mappings" attribute. They
  16480. // are lazily instantiated, accessed via the `_generatedMappings` and
  16481. // `_originalMappings` getters respectively, and we only parse the mappings
  16482. // and create these arrays once queried for a source location. We jump through
  16483. // these hoops because there can be many thousands of mappings, and parsing
  16484. // them is expensive, so we only want to do it if we must.
  16485. //
  16486. // Each object in the arrays is of the form:
  16487. //
  16488. // {
  16489. // generatedLine: The line number in the generated code,
  16490. // generatedColumn: The column number in the generated code,
  16491. // source: The path to the original source file that generated this
  16492. // chunk of code,
  16493. // originalLine: The line number in the original source that
  16494. // corresponds to this chunk of generated code,
  16495. // originalColumn: The column number in the original source that
  16496. // corresponds to this chunk of generated code,
  16497. // name: The name of the original symbol which generated this chunk of
  16498. // code.
  16499. // }
  16500. //
  16501. // All properties except for `generatedLine` and `generatedColumn` can be
  16502. // `null`.
  16503. //
  16504. // `_generatedMappings` is ordered by the generated positions.
  16505. //
  16506. // `_originalMappings` is ordered by the original positions.
  16507. SourceMapConsumer$6.prototype.__generatedMappings = null;
  16508. Object.defineProperty(SourceMapConsumer$6.prototype, '_generatedMappings', {
  16509. configurable: true,
  16510. enumerable: true,
  16511. get: function () {
  16512. if (!this.__generatedMappings) {
  16513. this._parseMappings(this._mappings, this.sourceRoot);
  16514. }
  16515. return this.__generatedMappings;
  16516. }
  16517. });
  16518. SourceMapConsumer$6.prototype.__originalMappings = null;
  16519. Object.defineProperty(SourceMapConsumer$6.prototype, '_originalMappings', {
  16520. configurable: true,
  16521. enumerable: true,
  16522. get: function () {
  16523. if (!this.__originalMappings) {
  16524. this._parseMappings(this._mappings, this.sourceRoot);
  16525. }
  16526. return this.__originalMappings;
  16527. }
  16528. });
  16529. SourceMapConsumer$6.prototype._charIsMappingSeparator =
  16530. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  16531. var c = aStr.charAt(index);
  16532. return c === ";" || c === ",";
  16533. };
  16534. /**
  16535. * Parse the mappings in a string in to a data structure which we can easily
  16536. * query (the ordered arrays in the `this.__generatedMappings` and
  16537. * `this.__originalMappings` properties).
  16538. */
  16539. SourceMapConsumer$6.prototype._parseMappings =
  16540. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  16541. throw new Error("Subclasses must implement _parseMappings");
  16542. };
  16543. SourceMapConsumer$6.GENERATED_ORDER = 1;
  16544. SourceMapConsumer$6.ORIGINAL_ORDER = 2;
  16545. SourceMapConsumer$6.GREATEST_LOWER_BOUND = 1;
  16546. SourceMapConsumer$6.LEAST_UPPER_BOUND = 2;
  16547. /**
  16548. * Iterate over each mapping between an original source/line/column and a
  16549. * generated line/column in this source map.
  16550. *
  16551. * @param Function aCallback
  16552. * The function that is called with each mapping.
  16553. * @param Object aContext
  16554. * Optional. If specified, this object will be the value of `this` every
  16555. * time that `aCallback` is called.
  16556. * @param aOrder
  16557. * Either `SourceMapConsumer.GENERATED_ORDER` or
  16558. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  16559. * iterate over the mappings sorted by the generated file's line/column
  16560. * order or the original's source/line/column order, respectively. Defaults to
  16561. * `SourceMapConsumer.GENERATED_ORDER`.
  16562. */
  16563. SourceMapConsumer$6.prototype.eachMapping =
  16564. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  16565. var context = aContext || null;
  16566. var order = aOrder || SourceMapConsumer$6.GENERATED_ORDER;
  16567. var mappings;
  16568. switch (order) {
  16569. case SourceMapConsumer$6.GENERATED_ORDER:
  16570. mappings = this._generatedMappings;
  16571. break;
  16572. case SourceMapConsumer$6.ORIGINAL_ORDER:
  16573. mappings = this._originalMappings;
  16574. break;
  16575. default:
  16576. throw new Error("Unknown order of iteration.");
  16577. }
  16578. var sourceRoot = this.sourceRoot;
  16579. mappings.map(function (mapping) {
  16580. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  16581. source = util$8.computeSourceURL(sourceRoot, source, this._sourceMapURL);
  16582. return {
  16583. source: source,
  16584. generatedLine: mapping.generatedLine,
  16585. generatedColumn: mapping.generatedColumn,
  16586. originalLine: mapping.originalLine,
  16587. originalColumn: mapping.originalColumn,
  16588. name: mapping.name === null ? null : this._names.at(mapping.name)
  16589. };
  16590. }, this).forEach(aCallback, context);
  16591. };
  16592. /**
  16593. * Returns all generated line and column information for the original source,
  16594. * line, and column provided. If no column is provided, returns all mappings
  16595. * corresponding to a either the line we are searching for or the next
  16596. * closest line that has any mappings. Otherwise, returns all mappings
  16597. * corresponding to the given line and either the column we are searching for
  16598. * or the next closest column that has any offsets.
  16599. *
  16600. * The only argument is an object with the following properties:
  16601. *
  16602. * - source: The filename of the original source.
  16603. * - line: The line number in the original source. The line number is 1-based.
  16604. * - column: Optional. the column number in the original source.
  16605. * The column number is 0-based.
  16606. *
  16607. * and an array of objects is returned, each with the following properties:
  16608. *
  16609. * - line: The line number in the generated source, or null. The
  16610. * line number is 1-based.
  16611. * - column: The column number in the generated source, or null.
  16612. * The column number is 0-based.
  16613. */
  16614. SourceMapConsumer$6.prototype.allGeneratedPositionsFor =
  16615. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  16616. var line = util$8.getArg(aArgs, 'line');
  16617. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  16618. // returns the index of the closest mapping less than the needle. By
  16619. // setting needle.originalColumn to 0, we thus find the last mapping for
  16620. // the given line, provided such a mapping exists.
  16621. var needle = {
  16622. source: util$8.getArg(aArgs, 'source'),
  16623. originalLine: line,
  16624. originalColumn: util$8.getArg(aArgs, 'column', 0)
  16625. };
  16626. needle.source = this._findSourceIndex(needle.source);
  16627. if (needle.source < 0) {
  16628. return [];
  16629. }
  16630. var mappings = [];
  16631. var index = this._findMapping(needle,
  16632. this._originalMappings,
  16633. "originalLine",
  16634. "originalColumn",
  16635. util$8.compareByOriginalPositions,
  16636. binarySearch$2.LEAST_UPPER_BOUND);
  16637. if (index >= 0) {
  16638. var mapping = this._originalMappings[index];
  16639. if (aArgs.column === undefined) {
  16640. var originalLine = mapping.originalLine;
  16641. // Iterate until either we run out of mappings, or we run into
  16642. // a mapping for a different line than the one we found. Since
  16643. // mappings are sorted, this is guaranteed to find all mappings for
  16644. // the line we found.
  16645. while (mapping && mapping.originalLine === originalLine) {
  16646. mappings.push({
  16647. line: util$8.getArg(mapping, 'generatedLine', null),
  16648. column: util$8.getArg(mapping, 'generatedColumn', null),
  16649. lastColumn: util$8.getArg(mapping, 'lastGeneratedColumn', null)
  16650. });
  16651. mapping = this._originalMappings[++index];
  16652. }
  16653. } else {
  16654. var originalColumn = mapping.originalColumn;
  16655. // Iterate until either we run out of mappings, or we run into
  16656. // a mapping for a different line than the one we were searching for.
  16657. // Since mappings are sorted, this is guaranteed to find all mappings for
  16658. // the line we are searching for.
  16659. while (mapping &&
  16660. mapping.originalLine === line &&
  16661. mapping.originalColumn == originalColumn) {
  16662. mappings.push({
  16663. line: util$8.getArg(mapping, 'generatedLine', null),
  16664. column: util$8.getArg(mapping, 'generatedColumn', null),
  16665. lastColumn: util$8.getArg(mapping, 'lastGeneratedColumn', null)
  16666. });
  16667. mapping = this._originalMappings[++index];
  16668. }
  16669. }
  16670. }
  16671. return mappings;
  16672. };
  16673. sourceMapConsumer$1.SourceMapConsumer = SourceMapConsumer$6;
  16674. /**
  16675. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  16676. * query for information about the original file positions by giving it a file
  16677. * position in the generated source.
  16678. *
  16679. * The first parameter is the raw source map (either as a JSON string, or
  16680. * already parsed to an object). According to the spec, source maps have the
  16681. * following attributes:
  16682. *
  16683. * - version: Which version of the source map spec this map is following.
  16684. * - sources: An array of URLs to the original source files.
  16685. * - names: An array of identifiers which can be referrenced by individual mappings.
  16686. * - sourceRoot: Optional. The URL root from which all sources are relative.
  16687. * - sourcesContent: Optional. An array of contents of the original source files.
  16688. * - mappings: A string of base64 VLQs which contain the actual mappings.
  16689. * - file: Optional. The generated file this source map is associated with.
  16690. *
  16691. * Here is an example source map, taken from the source map spec[0]:
  16692. *
  16693. * {
  16694. * version : 3,
  16695. * file: "out.js",
  16696. * sourceRoot : "",
  16697. * sources: ["foo.js", "bar.js"],
  16698. * names: ["src", "maps", "are", "fun"],
  16699. * mappings: "AA,AB;;ABCDE;"
  16700. * }
  16701. *
  16702. * The second parameter, if given, is a string whose value is the URL
  16703. * at which the source map was found. This URL is used to compute the
  16704. * sources array.
  16705. *
  16706. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  16707. */
  16708. function BasicSourceMapConsumer$1(aSourceMap, aSourceMapURL) {
  16709. var sourceMap = aSourceMap;
  16710. if (typeof aSourceMap === 'string') {
  16711. sourceMap = util$8.parseSourceMapInput(aSourceMap);
  16712. }
  16713. var version = util$8.getArg(sourceMap, 'version');
  16714. var sources = util$8.getArg(sourceMap, 'sources');
  16715. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  16716. // requires the array) to play nice here.
  16717. var names = util$8.getArg(sourceMap, 'names', []);
  16718. var sourceRoot = util$8.getArg(sourceMap, 'sourceRoot', null);
  16719. var sourcesContent = util$8.getArg(sourceMap, 'sourcesContent', null);
  16720. var mappings = util$8.getArg(sourceMap, 'mappings');
  16721. var file = util$8.getArg(sourceMap, 'file', null);
  16722. // Once again, Sass deviates from the spec and supplies the version as a
  16723. // string rather than a number, so we use loose equality checking here.
  16724. if (version != this._version) {
  16725. throw new Error('Unsupported version: ' + version);
  16726. }
  16727. if (sourceRoot) {
  16728. sourceRoot = util$8.normalize(sourceRoot);
  16729. }
  16730. sources = sources
  16731. .map(String)
  16732. // Some source maps produce relative source paths like "./foo.js" instead of
  16733. // "foo.js". Normalize these first so that future comparisons will succeed.
  16734. // See bugzil.la/1090768.
  16735. .map(util$8.normalize)
  16736. // Always ensure that absolute sources are internally stored relative to
  16737. // the source root, if the source root is absolute. Not doing this would
  16738. // be particularly problematic when the source root is a prefix of the
  16739. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  16740. .map(function (source) {
  16741. return sourceRoot && util$8.isAbsolute(sourceRoot) && util$8.isAbsolute(source)
  16742. ? util$8.relative(sourceRoot, source)
  16743. : source;
  16744. });
  16745. // Pass `true` below to allow duplicate names and sources. While source maps
  16746. // are intended to be compressed and deduplicated, the TypeScript compiler
  16747. // sometimes generates source maps with duplicates in them. See Github issue
  16748. // #72 and bugzil.la/889492.
  16749. this._names = ArraySet$3.fromArray(names.map(String), true);
  16750. this._sources = ArraySet$3.fromArray(sources, true);
  16751. this._absoluteSources = this._sources.toArray().map(function (s) {
  16752. return util$8.computeSourceURL(sourceRoot, s, aSourceMapURL);
  16753. });
  16754. this.sourceRoot = sourceRoot;
  16755. this.sourcesContent = sourcesContent;
  16756. this._mappings = mappings;
  16757. this._sourceMapURL = aSourceMapURL;
  16758. this.file = file;
  16759. }
  16760. BasicSourceMapConsumer$1.prototype = Object.create(SourceMapConsumer$6.prototype);
  16761. BasicSourceMapConsumer$1.prototype.consumer = SourceMapConsumer$6;
  16762. /**
  16763. * Utility function to find the index of a source. Returns -1 if not
  16764. * found.
  16765. */
  16766. BasicSourceMapConsumer$1.prototype._findSourceIndex = function(aSource) {
  16767. var relativeSource = aSource;
  16768. if (this.sourceRoot != null) {
  16769. relativeSource = util$8.relative(this.sourceRoot, relativeSource);
  16770. }
  16771. if (this._sources.has(relativeSource)) {
  16772. return this._sources.indexOf(relativeSource);
  16773. }
  16774. // Maybe aSource is an absolute URL as returned by |sources|. In
  16775. // this case we can't simply undo the transform.
  16776. var i;
  16777. for (i = 0; i < this._absoluteSources.length; ++i) {
  16778. if (this._absoluteSources[i] == aSource) {
  16779. return i;
  16780. }
  16781. }
  16782. return -1;
  16783. };
  16784. /**
  16785. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  16786. *
  16787. * @param SourceMapGenerator aSourceMap
  16788. * The source map that will be consumed.
  16789. * @param String aSourceMapURL
  16790. * The URL at which the source map can be found (optional)
  16791. * @returns BasicSourceMapConsumer
  16792. */
  16793. BasicSourceMapConsumer$1.fromSourceMap =
  16794. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  16795. var smc = Object.create(BasicSourceMapConsumer$1.prototype);
  16796. var names = smc._names = ArraySet$3.fromArray(aSourceMap._names.toArray(), true);
  16797. var sources = smc._sources = ArraySet$3.fromArray(aSourceMap._sources.toArray(), true);
  16798. smc.sourceRoot = aSourceMap._sourceRoot;
  16799. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  16800. smc.sourceRoot);
  16801. smc.file = aSourceMap._file;
  16802. smc._sourceMapURL = aSourceMapURL;
  16803. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  16804. return util$8.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  16805. });
  16806. // Because we are modifying the entries (by converting string sources and
  16807. // names to indices into the sources and names ArraySets), we have to make
  16808. // a copy of the entry or else bad things happen. Shared mutable state
  16809. // strikes again! See github issue #191.
  16810. var generatedMappings = aSourceMap._mappings.toArray().slice();
  16811. var destGeneratedMappings = smc.__generatedMappings = [];
  16812. var destOriginalMappings = smc.__originalMappings = [];
  16813. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  16814. var srcMapping = generatedMappings[i];
  16815. var destMapping = new Mapping$1;
  16816. destMapping.generatedLine = srcMapping.generatedLine;
  16817. destMapping.generatedColumn = srcMapping.generatedColumn;
  16818. if (srcMapping.source) {
  16819. destMapping.source = sources.indexOf(srcMapping.source);
  16820. destMapping.originalLine = srcMapping.originalLine;
  16821. destMapping.originalColumn = srcMapping.originalColumn;
  16822. if (srcMapping.name) {
  16823. destMapping.name = names.indexOf(srcMapping.name);
  16824. }
  16825. destOriginalMappings.push(destMapping);
  16826. }
  16827. destGeneratedMappings.push(destMapping);
  16828. }
  16829. quickSort$2(smc.__originalMappings, util$8.compareByOriginalPositions);
  16830. return smc;
  16831. };
  16832. /**
  16833. * The version of the source mapping spec that we are consuming.
  16834. */
  16835. BasicSourceMapConsumer$1.prototype._version = 3;
  16836. /**
  16837. * The list of original sources.
  16838. */
  16839. Object.defineProperty(BasicSourceMapConsumer$1.prototype, 'sources', {
  16840. get: function () {
  16841. return this._absoluteSources.slice();
  16842. }
  16843. });
  16844. /**
  16845. * Provide the JIT with a nice shape / hidden class.
  16846. */
  16847. function Mapping$1() {
  16848. this.generatedLine = 0;
  16849. this.generatedColumn = 0;
  16850. this.source = null;
  16851. this.originalLine = null;
  16852. this.originalColumn = null;
  16853. this.name = null;
  16854. }
  16855. /**
  16856. * Parse the mappings in a string in to a data structure which we can easily
  16857. * query (the ordered arrays in the `this.__generatedMappings` and
  16858. * `this.__originalMappings` properties).
  16859. */
  16860. BasicSourceMapConsumer$1.prototype._parseMappings =
  16861. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  16862. var generatedLine = 1;
  16863. var previousGeneratedColumn = 0;
  16864. var previousOriginalLine = 0;
  16865. var previousOriginalColumn = 0;
  16866. var previousSource = 0;
  16867. var previousName = 0;
  16868. var length = aStr.length;
  16869. var index = 0;
  16870. var cachedSegments = {};
  16871. var temp = {};
  16872. var originalMappings = [];
  16873. var generatedMappings = [];
  16874. var mapping, str, segment, end, value;
  16875. while (index < length) {
  16876. if (aStr.charAt(index) === ';') {
  16877. generatedLine++;
  16878. index++;
  16879. previousGeneratedColumn = 0;
  16880. }
  16881. else if (aStr.charAt(index) === ',') {
  16882. index++;
  16883. }
  16884. else {
  16885. mapping = new Mapping$1();
  16886. mapping.generatedLine = generatedLine;
  16887. // Because each offset is encoded relative to the previous one,
  16888. // many segments often have the same encoding. We can exploit this
  16889. // fact by caching the parsed variable length fields of each segment,
  16890. // allowing us to avoid a second parse if we encounter the same
  16891. // segment again.
  16892. for (end = index; end < length; end++) {
  16893. if (this._charIsMappingSeparator(aStr, end)) {
  16894. break;
  16895. }
  16896. }
  16897. str = aStr.slice(index, end);
  16898. segment = cachedSegments[str];
  16899. if (segment) {
  16900. index += str.length;
  16901. } else {
  16902. segment = [];
  16903. while (index < end) {
  16904. base64VLQ$2.decode(aStr, index, temp);
  16905. value = temp.value;
  16906. index = temp.rest;
  16907. segment.push(value);
  16908. }
  16909. if (segment.length === 2) {
  16910. throw new Error('Found a source, but no line and column');
  16911. }
  16912. if (segment.length === 3) {
  16913. throw new Error('Found a source and line, but no column');
  16914. }
  16915. cachedSegments[str] = segment;
  16916. }
  16917. // Generated column.
  16918. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  16919. previousGeneratedColumn = mapping.generatedColumn;
  16920. if (segment.length > 1) {
  16921. // Original source.
  16922. mapping.source = previousSource + segment[1];
  16923. previousSource += segment[1];
  16924. // Original line.
  16925. mapping.originalLine = previousOriginalLine + segment[2];
  16926. previousOriginalLine = mapping.originalLine;
  16927. // Lines are stored 0-based
  16928. mapping.originalLine += 1;
  16929. // Original column.
  16930. mapping.originalColumn = previousOriginalColumn + segment[3];
  16931. previousOriginalColumn = mapping.originalColumn;
  16932. if (segment.length > 4) {
  16933. // Original name.
  16934. mapping.name = previousName + segment[4];
  16935. previousName += segment[4];
  16936. }
  16937. }
  16938. generatedMappings.push(mapping);
  16939. if (typeof mapping.originalLine === 'number') {
  16940. originalMappings.push(mapping);
  16941. }
  16942. }
  16943. }
  16944. quickSort$2(generatedMappings, util$8.compareByGeneratedPositionsDeflated);
  16945. this.__generatedMappings = generatedMappings;
  16946. quickSort$2(originalMappings, util$8.compareByOriginalPositions);
  16947. this.__originalMappings = originalMappings;
  16948. };
  16949. /**
  16950. * Find the mapping that best matches the hypothetical "needle" mapping that
  16951. * we are searching for in the given "haystack" of mappings.
  16952. */
  16953. BasicSourceMapConsumer$1.prototype._findMapping =
  16954. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  16955. aColumnName, aComparator, aBias) {
  16956. // To return the position we are searching for, we must first find the
  16957. // mapping for the given position and then return the opposite position it
  16958. // points to. Because the mappings are sorted, we can use binary search to
  16959. // find the best mapping.
  16960. if (aNeedle[aLineName] <= 0) {
  16961. throw new TypeError('Line must be greater than or equal to 1, got '
  16962. + aNeedle[aLineName]);
  16963. }
  16964. if (aNeedle[aColumnName] < 0) {
  16965. throw new TypeError('Column must be greater than or equal to 0, got '
  16966. + aNeedle[aColumnName]);
  16967. }
  16968. return binarySearch$2.search(aNeedle, aMappings, aComparator, aBias);
  16969. };
  16970. /**
  16971. * Compute the last column for each generated mapping. The last column is
  16972. * inclusive.
  16973. */
  16974. BasicSourceMapConsumer$1.prototype.computeColumnSpans =
  16975. function SourceMapConsumer_computeColumnSpans() {
  16976. for (var index = 0; index < this._generatedMappings.length; ++index) {
  16977. var mapping = this._generatedMappings[index];
  16978. // Mappings do not contain a field for the last generated columnt. We
  16979. // can come up with an optimistic estimate, however, by assuming that
  16980. // mappings are contiguous (i.e. given two consecutive mappings, the
  16981. // first mapping ends where the second one starts).
  16982. if (index + 1 < this._generatedMappings.length) {
  16983. var nextMapping = this._generatedMappings[index + 1];
  16984. if (mapping.generatedLine === nextMapping.generatedLine) {
  16985. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  16986. continue;
  16987. }
  16988. }
  16989. // The last mapping for each line spans the entire line.
  16990. mapping.lastGeneratedColumn = Infinity;
  16991. }
  16992. };
  16993. /**
  16994. * Returns the original source, line, and column information for the generated
  16995. * source's line and column positions provided. The only argument is an object
  16996. * with the following properties:
  16997. *
  16998. * - line: The line number in the generated source. The line number
  16999. * is 1-based.
  17000. * - column: The column number in the generated source. The column
  17001. * number is 0-based.
  17002. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  17003. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  17004. * closest element that is smaller than or greater than the one we are
  17005. * searching for, respectively, if the exact element cannot be found.
  17006. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  17007. *
  17008. * and an object is returned with the following properties:
  17009. *
  17010. * - source: The original source file, or null.
  17011. * - line: The line number in the original source, or null. The
  17012. * line number is 1-based.
  17013. * - column: The column number in the original source, or null. The
  17014. * column number is 0-based.
  17015. * - name: The original identifier, or null.
  17016. */
  17017. BasicSourceMapConsumer$1.prototype.originalPositionFor =
  17018. function SourceMapConsumer_originalPositionFor(aArgs) {
  17019. var needle = {
  17020. generatedLine: util$8.getArg(aArgs, 'line'),
  17021. generatedColumn: util$8.getArg(aArgs, 'column')
  17022. };
  17023. var index = this._findMapping(
  17024. needle,
  17025. this._generatedMappings,
  17026. "generatedLine",
  17027. "generatedColumn",
  17028. util$8.compareByGeneratedPositionsDeflated,
  17029. util$8.getArg(aArgs, 'bias', SourceMapConsumer$6.GREATEST_LOWER_BOUND)
  17030. );
  17031. if (index >= 0) {
  17032. var mapping = this._generatedMappings[index];
  17033. if (mapping.generatedLine === needle.generatedLine) {
  17034. var source = util$8.getArg(mapping, 'source', null);
  17035. if (source !== null) {
  17036. source = this._sources.at(source);
  17037. source = util$8.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  17038. }
  17039. var name = util$8.getArg(mapping, 'name', null);
  17040. if (name !== null) {
  17041. name = this._names.at(name);
  17042. }
  17043. return {
  17044. source: source,
  17045. line: util$8.getArg(mapping, 'originalLine', null),
  17046. column: util$8.getArg(mapping, 'originalColumn', null),
  17047. name: name
  17048. };
  17049. }
  17050. }
  17051. return {
  17052. source: null,
  17053. line: null,
  17054. column: null,
  17055. name: null
  17056. };
  17057. };
  17058. /**
  17059. * Return true if we have the source content for every source in the source
  17060. * map, false otherwise.
  17061. */
  17062. BasicSourceMapConsumer$1.prototype.hasContentsOfAllSources =
  17063. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  17064. if (!this.sourcesContent) {
  17065. return false;
  17066. }
  17067. return this.sourcesContent.length >= this._sources.size() &&
  17068. !this.sourcesContent.some(function (sc) { return sc == null; });
  17069. };
  17070. /**
  17071. * Returns the original source content. The only argument is the url of the
  17072. * original source file. Returns null if no original source content is
  17073. * available.
  17074. */
  17075. BasicSourceMapConsumer$1.prototype.sourceContentFor =
  17076. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  17077. if (!this.sourcesContent) {
  17078. return null;
  17079. }
  17080. var index = this._findSourceIndex(aSource);
  17081. if (index >= 0) {
  17082. return this.sourcesContent[index];
  17083. }
  17084. var relativeSource = aSource;
  17085. if (this.sourceRoot != null) {
  17086. relativeSource = util$8.relative(this.sourceRoot, relativeSource);
  17087. }
  17088. var url;
  17089. if (this.sourceRoot != null
  17090. && (url = util$8.urlParse(this.sourceRoot))) {
  17091. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  17092. // many users. We can help them out when they expect file:// URIs to
  17093. // behave like it would if they were running a local HTTP server. See
  17094. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  17095. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  17096. if (url.scheme == "file"
  17097. && this._sources.has(fileUriAbsPath)) {
  17098. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  17099. }
  17100. if ((!url.path || url.path == "/")
  17101. && this._sources.has("/" + relativeSource)) {
  17102. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  17103. }
  17104. }
  17105. // This function is used recursively from
  17106. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  17107. // don't want to throw if we can't find the source - we just want to
  17108. // return null, so we provide a flag to exit gracefully.
  17109. if (nullOnMissing) {
  17110. return null;
  17111. }
  17112. else {
  17113. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  17114. }
  17115. };
  17116. /**
  17117. * Returns the generated line and column information for the original source,
  17118. * line, and column positions provided. The only argument is an object with
  17119. * the following properties:
  17120. *
  17121. * - source: The filename of the original source.
  17122. * - line: The line number in the original source. The line number
  17123. * is 1-based.
  17124. * - column: The column number in the original source. The column
  17125. * number is 0-based.
  17126. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  17127. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  17128. * closest element that is smaller than or greater than the one we are
  17129. * searching for, respectively, if the exact element cannot be found.
  17130. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  17131. *
  17132. * and an object is returned with the following properties:
  17133. *
  17134. * - line: The line number in the generated source, or null. The
  17135. * line number is 1-based.
  17136. * - column: The column number in the generated source, or null.
  17137. * The column number is 0-based.
  17138. */
  17139. BasicSourceMapConsumer$1.prototype.generatedPositionFor =
  17140. function SourceMapConsumer_generatedPositionFor(aArgs) {
  17141. var source = util$8.getArg(aArgs, 'source');
  17142. source = this._findSourceIndex(source);
  17143. if (source < 0) {
  17144. return {
  17145. line: null,
  17146. column: null,
  17147. lastColumn: null
  17148. };
  17149. }
  17150. var needle = {
  17151. source: source,
  17152. originalLine: util$8.getArg(aArgs, 'line'),
  17153. originalColumn: util$8.getArg(aArgs, 'column')
  17154. };
  17155. var index = this._findMapping(
  17156. needle,
  17157. this._originalMappings,
  17158. "originalLine",
  17159. "originalColumn",
  17160. util$8.compareByOriginalPositions,
  17161. util$8.getArg(aArgs, 'bias', SourceMapConsumer$6.GREATEST_LOWER_BOUND)
  17162. );
  17163. if (index >= 0) {
  17164. var mapping = this._originalMappings[index];
  17165. if (mapping.source === needle.source) {
  17166. return {
  17167. line: util$8.getArg(mapping, 'generatedLine', null),
  17168. column: util$8.getArg(mapping, 'generatedColumn', null),
  17169. lastColumn: util$8.getArg(mapping, 'lastGeneratedColumn', null)
  17170. };
  17171. }
  17172. }
  17173. return {
  17174. line: null,
  17175. column: null,
  17176. lastColumn: null
  17177. };
  17178. };
  17179. sourceMapConsumer$1.BasicSourceMapConsumer = BasicSourceMapConsumer$1;
  17180. /**
  17181. * An IndexedSourceMapConsumer instance represents a parsed source map which
  17182. * we can query for information. It differs from BasicSourceMapConsumer in
  17183. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  17184. * input.
  17185. *
  17186. * The first parameter is a raw source map (either as a JSON string, or already
  17187. * parsed to an object). According to the spec for indexed source maps, they
  17188. * have the following attributes:
  17189. *
  17190. * - version: Which version of the source map spec this map is following.
  17191. * - file: Optional. The generated file this source map is associated with.
  17192. * - sections: A list of section definitions.
  17193. *
  17194. * Each value under the "sections" field has two fields:
  17195. * - offset: The offset into the original specified at which this section
  17196. * begins to apply, defined as an object with a "line" and "column"
  17197. * field.
  17198. * - map: A source map definition. This source map could also be indexed,
  17199. * but doesn't have to be.
  17200. *
  17201. * Instead of the "map" field, it's also possible to have a "url" field
  17202. * specifying a URL to retrieve a source map from, but that's currently
  17203. * unsupported.
  17204. *
  17205. * Here's an example source map, taken from the source map spec[0], but
  17206. * modified to omit a section which uses the "url" field.
  17207. *
  17208. * {
  17209. * version : 3,
  17210. * file: "app.js",
  17211. * sections: [{
  17212. * offset: {line:100, column:10},
  17213. * map: {
  17214. * version : 3,
  17215. * file: "section.js",
  17216. * sources: ["foo.js", "bar.js"],
  17217. * names: ["src", "maps", "are", "fun"],
  17218. * mappings: "AAAA,E;;ABCDE;"
  17219. * }
  17220. * }],
  17221. * }
  17222. *
  17223. * The second parameter, if given, is a string whose value is the URL
  17224. * at which the source map was found. This URL is used to compute the
  17225. * sources array.
  17226. *
  17227. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  17228. */
  17229. function IndexedSourceMapConsumer$1(aSourceMap, aSourceMapURL) {
  17230. var sourceMap = aSourceMap;
  17231. if (typeof aSourceMap === 'string') {
  17232. sourceMap = util$8.parseSourceMapInput(aSourceMap);
  17233. }
  17234. var version = util$8.getArg(sourceMap, 'version');
  17235. var sections = util$8.getArg(sourceMap, 'sections');
  17236. if (version != this._version) {
  17237. throw new Error('Unsupported version: ' + version);
  17238. }
  17239. this._sources = new ArraySet$3();
  17240. this._names = new ArraySet$3();
  17241. var lastOffset = {
  17242. line: -1,
  17243. column: 0
  17244. };
  17245. this._sections = sections.map(function (s) {
  17246. if (s.url) {
  17247. // The url field will require support for asynchronicity.
  17248. // See https://github.com/mozilla/source-map/issues/16
  17249. throw new Error('Support for url field in sections not implemented.');
  17250. }
  17251. var offset = util$8.getArg(s, 'offset');
  17252. var offsetLine = util$8.getArg(offset, 'line');
  17253. var offsetColumn = util$8.getArg(offset, 'column');
  17254. if (offsetLine < lastOffset.line ||
  17255. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  17256. throw new Error('Section offsets must be ordered and non-overlapping.');
  17257. }
  17258. lastOffset = offset;
  17259. return {
  17260. generatedOffset: {
  17261. // The offset fields are 0-based, but we use 1-based indices when
  17262. // encoding/decoding from VLQ.
  17263. generatedLine: offsetLine + 1,
  17264. generatedColumn: offsetColumn + 1
  17265. },
  17266. consumer: new SourceMapConsumer$6(util$8.getArg(s, 'map'), aSourceMapURL)
  17267. }
  17268. });
  17269. }
  17270. IndexedSourceMapConsumer$1.prototype = Object.create(SourceMapConsumer$6.prototype);
  17271. IndexedSourceMapConsumer$1.prototype.constructor = SourceMapConsumer$6;
  17272. /**
  17273. * The version of the source mapping spec that we are consuming.
  17274. */
  17275. IndexedSourceMapConsumer$1.prototype._version = 3;
  17276. /**
  17277. * The list of original sources.
  17278. */
  17279. Object.defineProperty(IndexedSourceMapConsumer$1.prototype, 'sources', {
  17280. get: function () {
  17281. var sources = [];
  17282. for (var i = 0; i < this._sections.length; i++) {
  17283. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  17284. sources.push(this._sections[i].consumer.sources[j]);
  17285. }
  17286. }
  17287. return sources;
  17288. }
  17289. });
  17290. /**
  17291. * Returns the original source, line, and column information for the generated
  17292. * source's line and column positions provided. The only argument is an object
  17293. * with the following properties:
  17294. *
  17295. * - line: The line number in the generated source. The line number
  17296. * is 1-based.
  17297. * - column: The column number in the generated source. The column
  17298. * number is 0-based.
  17299. *
  17300. * and an object is returned with the following properties:
  17301. *
  17302. * - source: The original source file, or null.
  17303. * - line: The line number in the original source, or null. The
  17304. * line number is 1-based.
  17305. * - column: The column number in the original source, or null. The
  17306. * column number is 0-based.
  17307. * - name: The original identifier, or null.
  17308. */
  17309. IndexedSourceMapConsumer$1.prototype.originalPositionFor =
  17310. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  17311. var needle = {
  17312. generatedLine: util$8.getArg(aArgs, 'line'),
  17313. generatedColumn: util$8.getArg(aArgs, 'column')
  17314. };
  17315. // Find the section containing the generated position we're trying to map
  17316. // to an original position.
  17317. var sectionIndex = binarySearch$2.search(needle, this._sections,
  17318. function(needle, section) {
  17319. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  17320. if (cmp) {
  17321. return cmp;
  17322. }
  17323. return (needle.generatedColumn -
  17324. section.generatedOffset.generatedColumn);
  17325. });
  17326. var section = this._sections[sectionIndex];
  17327. if (!section) {
  17328. return {
  17329. source: null,
  17330. line: null,
  17331. column: null,
  17332. name: null
  17333. };
  17334. }
  17335. return section.consumer.originalPositionFor({
  17336. line: needle.generatedLine -
  17337. (section.generatedOffset.generatedLine - 1),
  17338. column: needle.generatedColumn -
  17339. (section.generatedOffset.generatedLine === needle.generatedLine
  17340. ? section.generatedOffset.generatedColumn - 1
  17341. : 0),
  17342. bias: aArgs.bias
  17343. });
  17344. };
  17345. /**
  17346. * Return true if we have the source content for every source in the source
  17347. * map, false otherwise.
  17348. */
  17349. IndexedSourceMapConsumer$1.prototype.hasContentsOfAllSources =
  17350. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  17351. return this._sections.every(function (s) {
  17352. return s.consumer.hasContentsOfAllSources();
  17353. });
  17354. };
  17355. /**
  17356. * Returns the original source content. The only argument is the url of the
  17357. * original source file. Returns null if no original source content is
  17358. * available.
  17359. */
  17360. IndexedSourceMapConsumer$1.prototype.sourceContentFor =
  17361. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  17362. for (var i = 0; i < this._sections.length; i++) {
  17363. var section = this._sections[i];
  17364. var content = section.consumer.sourceContentFor(aSource, true);
  17365. if (content) {
  17366. return content;
  17367. }
  17368. }
  17369. if (nullOnMissing) {
  17370. return null;
  17371. }
  17372. else {
  17373. throw new Error('"' + aSource + '" is not in the SourceMap.');
  17374. }
  17375. };
  17376. /**
  17377. * Returns the generated line and column information for the original source,
  17378. * line, and column positions provided. The only argument is an object with
  17379. * the following properties:
  17380. *
  17381. * - source: The filename of the original source.
  17382. * - line: The line number in the original source. The line number
  17383. * is 1-based.
  17384. * - column: The column number in the original source. The column
  17385. * number is 0-based.
  17386. *
  17387. * and an object is returned with the following properties:
  17388. *
  17389. * - line: The line number in the generated source, or null. The
  17390. * line number is 1-based.
  17391. * - column: The column number in the generated source, or null.
  17392. * The column number is 0-based.
  17393. */
  17394. IndexedSourceMapConsumer$1.prototype.generatedPositionFor =
  17395. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  17396. for (var i = 0; i < this._sections.length; i++) {
  17397. var section = this._sections[i];
  17398. // Only consider this section if the requested source is in the list of
  17399. // sources of the consumer.
  17400. if (section.consumer._findSourceIndex(util$8.getArg(aArgs, 'source')) === -1) {
  17401. continue;
  17402. }
  17403. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  17404. if (generatedPosition) {
  17405. var ret = {
  17406. line: generatedPosition.line +
  17407. (section.generatedOffset.generatedLine - 1),
  17408. column: generatedPosition.column +
  17409. (section.generatedOffset.generatedLine === generatedPosition.line
  17410. ? section.generatedOffset.generatedColumn - 1
  17411. : 0)
  17412. };
  17413. return ret;
  17414. }
  17415. }
  17416. return {
  17417. line: null,
  17418. column: null
  17419. };
  17420. };
  17421. /**
  17422. * Parse the mappings in a string in to a data structure which we can easily
  17423. * query (the ordered arrays in the `this.__generatedMappings` and
  17424. * `this.__originalMappings` properties).
  17425. */
  17426. IndexedSourceMapConsumer$1.prototype._parseMappings =
  17427. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  17428. this.__generatedMappings = [];
  17429. this.__originalMappings = [];
  17430. for (var i = 0; i < this._sections.length; i++) {
  17431. var section = this._sections[i];
  17432. var sectionMappings = section.consumer._generatedMappings;
  17433. for (var j = 0; j < sectionMappings.length; j++) {
  17434. var mapping = sectionMappings[j];
  17435. var source = section.consumer._sources.at(mapping.source);
  17436. source = util$8.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  17437. this._sources.add(source);
  17438. source = this._sources.indexOf(source);
  17439. var name = null;
  17440. if (mapping.name) {
  17441. name = section.consumer._names.at(mapping.name);
  17442. this._names.add(name);
  17443. name = this._names.indexOf(name);
  17444. }
  17445. // The mappings coming from the consumer for the section have
  17446. // generated positions relative to the start of the section, so we
  17447. // need to offset them to be relative to the start of the concatenated
  17448. // generated file.
  17449. var adjustedMapping = {
  17450. source: source,
  17451. generatedLine: mapping.generatedLine +
  17452. (section.generatedOffset.generatedLine - 1),
  17453. generatedColumn: mapping.generatedColumn +
  17454. (section.generatedOffset.generatedLine === mapping.generatedLine
  17455. ? section.generatedOffset.generatedColumn - 1
  17456. : 0),
  17457. originalLine: mapping.originalLine,
  17458. originalColumn: mapping.originalColumn,
  17459. name: name
  17460. };
  17461. this.__generatedMappings.push(adjustedMapping);
  17462. if (typeof adjustedMapping.originalLine === 'number') {
  17463. this.__originalMappings.push(adjustedMapping);
  17464. }
  17465. }
  17466. }
  17467. quickSort$2(this.__generatedMappings, util$8.compareByGeneratedPositionsDeflated);
  17468. quickSort$2(this.__originalMappings, util$8.compareByOriginalPositions);
  17469. };
  17470. sourceMapConsumer$1.IndexedSourceMapConsumer = IndexedSourceMapConsumer$1;
  17471. var sourceNode$1 = {};
  17472. /* -*- Mode: js; js-indent-level: 2; -*- */
  17473. /*
  17474. * Copyright 2011 Mozilla Foundation and contributors
  17475. * Licensed under the New BSD license. See LICENSE or:
  17476. * http://opensource.org/licenses/BSD-3-Clause
  17477. */
  17478. var SourceMapGenerator$7 = sourceMapGenerator$1.SourceMapGenerator;
  17479. var util$7 = util$c;
  17480. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  17481. // operating systems these days (capturing the result).
  17482. var REGEX_NEWLINE$1 = /(\r?\n)/;
  17483. // Newline character code for charCodeAt() comparisons
  17484. var NEWLINE_CODE$1 = 10;
  17485. // Private symbol for identifying `SourceNode`s when multiple versions of
  17486. // the source-map library are loaded. This MUST NOT CHANGE across
  17487. // versions!
  17488. var isSourceNode$1 = "$$$isSourceNode$$$";
  17489. /**
  17490. * SourceNodes provide a way to abstract over interpolating/concatenating
  17491. * snippets of generated JavaScript source code while maintaining the line and
  17492. * column information associated with the original source code.
  17493. *
  17494. * @param aLine The original line number.
  17495. * @param aColumn The original column number.
  17496. * @param aSource The original source's filename.
  17497. * @param aChunks Optional. An array of strings which are snippets of
  17498. * generated JS, or other SourceNodes.
  17499. * @param aName The original identifier.
  17500. */
  17501. function SourceNode$1(aLine, aColumn, aSource, aChunks, aName) {
  17502. this.children = [];
  17503. this.sourceContents = {};
  17504. this.line = aLine == null ? null : aLine;
  17505. this.column = aColumn == null ? null : aColumn;
  17506. this.source = aSource == null ? null : aSource;
  17507. this.name = aName == null ? null : aName;
  17508. this[isSourceNode$1] = true;
  17509. if (aChunks != null) this.add(aChunks);
  17510. }
  17511. /**
  17512. * Creates a SourceNode from generated code and a SourceMapConsumer.
  17513. *
  17514. * @param aGeneratedCode The generated code
  17515. * @param aSourceMapConsumer The SourceMap for the generated code
  17516. * @param aRelativePath Optional. The path that relative sources in the
  17517. * SourceMapConsumer should be relative to.
  17518. */
  17519. SourceNode$1.fromStringWithSourceMap =
  17520. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  17521. // The SourceNode we want to fill with the generated code
  17522. // and the SourceMap
  17523. var node = new SourceNode$1();
  17524. // All even indices of this array are one line of the generated code,
  17525. // while all odd indices are the newlines between two adjacent lines
  17526. // (since `REGEX_NEWLINE` captures its match).
  17527. // Processed fragments are accessed by calling `shiftNextLine`.
  17528. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE$1);
  17529. var remainingLinesIndex = 0;
  17530. var shiftNextLine = function() {
  17531. var lineContents = getNextLine();
  17532. // The last line of a file might not have a newline.
  17533. var newLine = getNextLine() || "";
  17534. return lineContents + newLine;
  17535. function getNextLine() {
  17536. return remainingLinesIndex < remainingLines.length ?
  17537. remainingLines[remainingLinesIndex++] : undefined;
  17538. }
  17539. };
  17540. // We need to remember the position of "remainingLines"
  17541. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  17542. // The generate SourceNodes we need a code range.
  17543. // To extract it current and last mapping is used.
  17544. // Here we store the last mapping.
  17545. var lastMapping = null;
  17546. aSourceMapConsumer.eachMapping(function (mapping) {
  17547. if (lastMapping !== null) {
  17548. // We add the code from "lastMapping" to "mapping":
  17549. // First check if there is a new line in between.
  17550. if (lastGeneratedLine < mapping.generatedLine) {
  17551. // Associate first line with "lastMapping"
  17552. addMappingWithCode(lastMapping, shiftNextLine());
  17553. lastGeneratedLine++;
  17554. lastGeneratedColumn = 0;
  17555. // The remaining code is added without mapping
  17556. } else {
  17557. // There is no new line in between.
  17558. // Associate the code between "lastGeneratedColumn" and
  17559. // "mapping.generatedColumn" with "lastMapping"
  17560. var nextLine = remainingLines[remainingLinesIndex] || '';
  17561. var code = nextLine.substr(0, mapping.generatedColumn -
  17562. lastGeneratedColumn);
  17563. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  17564. lastGeneratedColumn);
  17565. lastGeneratedColumn = mapping.generatedColumn;
  17566. addMappingWithCode(lastMapping, code);
  17567. // No more remaining code, continue
  17568. lastMapping = mapping;
  17569. return;
  17570. }
  17571. }
  17572. // We add the generated code until the first mapping
  17573. // to the SourceNode without any mapping.
  17574. // Each line is added as separate string.
  17575. while (lastGeneratedLine < mapping.generatedLine) {
  17576. node.add(shiftNextLine());
  17577. lastGeneratedLine++;
  17578. }
  17579. if (lastGeneratedColumn < mapping.generatedColumn) {
  17580. var nextLine = remainingLines[remainingLinesIndex] || '';
  17581. node.add(nextLine.substr(0, mapping.generatedColumn));
  17582. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  17583. lastGeneratedColumn = mapping.generatedColumn;
  17584. }
  17585. lastMapping = mapping;
  17586. }, this);
  17587. // We have processed all mappings.
  17588. if (remainingLinesIndex < remainingLines.length) {
  17589. if (lastMapping) {
  17590. // Associate the remaining code in the current line with "lastMapping"
  17591. addMappingWithCode(lastMapping, shiftNextLine());
  17592. }
  17593. // and add the remaining lines without any mapping
  17594. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  17595. }
  17596. // Copy sourcesContent into SourceNode
  17597. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  17598. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  17599. if (content != null) {
  17600. if (aRelativePath != null) {
  17601. sourceFile = util$7.join(aRelativePath, sourceFile);
  17602. }
  17603. node.setSourceContent(sourceFile, content);
  17604. }
  17605. });
  17606. return node;
  17607. function addMappingWithCode(mapping, code) {
  17608. if (mapping === null || mapping.source === undefined) {
  17609. node.add(code);
  17610. } else {
  17611. var source = aRelativePath
  17612. ? util$7.join(aRelativePath, mapping.source)
  17613. : mapping.source;
  17614. node.add(new SourceNode$1(mapping.originalLine,
  17615. mapping.originalColumn,
  17616. source,
  17617. code,
  17618. mapping.name));
  17619. }
  17620. }
  17621. };
  17622. /**
  17623. * Add a chunk of generated JS to this source node.
  17624. *
  17625. * @param aChunk A string snippet of generated JS code, another instance of
  17626. * SourceNode, or an array where each member is one of those things.
  17627. */
  17628. SourceNode$1.prototype.add = function SourceNode_add(aChunk) {
  17629. if (Array.isArray(aChunk)) {
  17630. aChunk.forEach(function (chunk) {
  17631. this.add(chunk);
  17632. }, this);
  17633. }
  17634. else if (aChunk[isSourceNode$1] || typeof aChunk === "string") {
  17635. if (aChunk) {
  17636. this.children.push(aChunk);
  17637. }
  17638. }
  17639. else {
  17640. throw new TypeError(
  17641. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  17642. );
  17643. }
  17644. return this;
  17645. };
  17646. /**
  17647. * Add a chunk of generated JS to the beginning of this source node.
  17648. *
  17649. * @param aChunk A string snippet of generated JS code, another instance of
  17650. * SourceNode, or an array where each member is one of those things.
  17651. */
  17652. SourceNode$1.prototype.prepend = function SourceNode_prepend(aChunk) {
  17653. if (Array.isArray(aChunk)) {
  17654. for (var i = aChunk.length-1; i >= 0; i--) {
  17655. this.prepend(aChunk[i]);
  17656. }
  17657. }
  17658. else if (aChunk[isSourceNode$1] || typeof aChunk === "string") {
  17659. this.children.unshift(aChunk);
  17660. }
  17661. else {
  17662. throw new TypeError(
  17663. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  17664. );
  17665. }
  17666. return this;
  17667. };
  17668. /**
  17669. * Walk over the tree of JS snippets in this node and its children. The
  17670. * walking function is called once for each snippet of JS and is passed that
  17671. * snippet and the its original associated source's line/column location.
  17672. *
  17673. * @param aFn The traversal function.
  17674. */
  17675. SourceNode$1.prototype.walk = function SourceNode_walk(aFn) {
  17676. var chunk;
  17677. for (var i = 0, len = this.children.length; i < len; i++) {
  17678. chunk = this.children[i];
  17679. if (chunk[isSourceNode$1]) {
  17680. chunk.walk(aFn);
  17681. }
  17682. else {
  17683. if (chunk !== '') {
  17684. aFn(chunk, { source: this.source,
  17685. line: this.line,
  17686. column: this.column,
  17687. name: this.name });
  17688. }
  17689. }
  17690. }
  17691. };
  17692. /**
  17693. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  17694. * each of `this.children`.
  17695. *
  17696. * @param aSep The separator.
  17697. */
  17698. SourceNode$1.prototype.join = function SourceNode_join(aSep) {
  17699. var newChildren;
  17700. var i;
  17701. var len = this.children.length;
  17702. if (len > 0) {
  17703. newChildren = [];
  17704. for (i = 0; i < len-1; i++) {
  17705. newChildren.push(this.children[i]);
  17706. newChildren.push(aSep);
  17707. }
  17708. newChildren.push(this.children[i]);
  17709. this.children = newChildren;
  17710. }
  17711. return this;
  17712. };
  17713. /**
  17714. * Call String.prototype.replace on the very right-most source snippet. Useful
  17715. * for trimming whitespace from the end of a source node, etc.
  17716. *
  17717. * @param aPattern The pattern to replace.
  17718. * @param aReplacement The thing to replace the pattern with.
  17719. */
  17720. SourceNode$1.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  17721. var lastChild = this.children[this.children.length - 1];
  17722. if (lastChild[isSourceNode$1]) {
  17723. lastChild.replaceRight(aPattern, aReplacement);
  17724. }
  17725. else if (typeof lastChild === 'string') {
  17726. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  17727. }
  17728. else {
  17729. this.children.push(''.replace(aPattern, aReplacement));
  17730. }
  17731. return this;
  17732. };
  17733. /**
  17734. * Set the source content for a source file. This will be added to the SourceMapGenerator
  17735. * in the sourcesContent field.
  17736. *
  17737. * @param aSourceFile The filename of the source file
  17738. * @param aSourceContent The content of the source file
  17739. */
  17740. SourceNode$1.prototype.setSourceContent =
  17741. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  17742. this.sourceContents[util$7.toSetString(aSourceFile)] = aSourceContent;
  17743. };
  17744. /**
  17745. * Walk over the tree of SourceNodes. The walking function is called for each
  17746. * source file content and is passed the filename and source content.
  17747. *
  17748. * @param aFn The traversal function.
  17749. */
  17750. SourceNode$1.prototype.walkSourceContents =
  17751. function SourceNode_walkSourceContents(aFn) {
  17752. for (var i = 0, len = this.children.length; i < len; i++) {
  17753. if (this.children[i][isSourceNode$1]) {
  17754. this.children[i].walkSourceContents(aFn);
  17755. }
  17756. }
  17757. var sources = Object.keys(this.sourceContents);
  17758. for (var i = 0, len = sources.length; i < len; i++) {
  17759. aFn(util$7.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  17760. }
  17761. };
  17762. /**
  17763. * Return the string representation of this source node. Walks over the tree
  17764. * and concatenates all the various snippets together to one string.
  17765. */
  17766. SourceNode$1.prototype.toString = function SourceNode_toString() {
  17767. var str = "";
  17768. this.walk(function (chunk) {
  17769. str += chunk;
  17770. });
  17771. return str;
  17772. };
  17773. /**
  17774. * Returns the string representation of this source node along with a source
  17775. * map.
  17776. */
  17777. SourceNode$1.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  17778. var generated = {
  17779. code: "",
  17780. line: 1,
  17781. column: 0
  17782. };
  17783. var map = new SourceMapGenerator$7(aArgs);
  17784. var sourceMappingActive = false;
  17785. var lastOriginalSource = null;
  17786. var lastOriginalLine = null;
  17787. var lastOriginalColumn = null;
  17788. var lastOriginalName = null;
  17789. this.walk(function (chunk, original) {
  17790. generated.code += chunk;
  17791. if (original.source !== null
  17792. && original.line !== null
  17793. && original.column !== null) {
  17794. if(lastOriginalSource !== original.source
  17795. || lastOriginalLine !== original.line
  17796. || lastOriginalColumn !== original.column
  17797. || lastOriginalName !== original.name) {
  17798. map.addMapping({
  17799. source: original.source,
  17800. original: {
  17801. line: original.line,
  17802. column: original.column
  17803. },
  17804. generated: {
  17805. line: generated.line,
  17806. column: generated.column
  17807. },
  17808. name: original.name
  17809. });
  17810. }
  17811. lastOriginalSource = original.source;
  17812. lastOriginalLine = original.line;
  17813. lastOriginalColumn = original.column;
  17814. lastOriginalName = original.name;
  17815. sourceMappingActive = true;
  17816. } else if (sourceMappingActive) {
  17817. map.addMapping({
  17818. generated: {
  17819. line: generated.line,
  17820. column: generated.column
  17821. }
  17822. });
  17823. lastOriginalSource = null;
  17824. sourceMappingActive = false;
  17825. }
  17826. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  17827. if (chunk.charCodeAt(idx) === NEWLINE_CODE$1) {
  17828. generated.line++;
  17829. generated.column = 0;
  17830. // Mappings end at eol
  17831. if (idx + 1 === length) {
  17832. lastOriginalSource = null;
  17833. sourceMappingActive = false;
  17834. } else if (sourceMappingActive) {
  17835. map.addMapping({
  17836. source: original.source,
  17837. original: {
  17838. line: original.line,
  17839. column: original.column
  17840. },
  17841. generated: {
  17842. line: generated.line,
  17843. column: generated.column
  17844. },
  17845. name: original.name
  17846. });
  17847. }
  17848. } else {
  17849. generated.column++;
  17850. }
  17851. }
  17852. });
  17853. this.walkSourceContents(function (sourceFile, sourceContent) {
  17854. map.setSourceContent(sourceFile, sourceContent);
  17855. });
  17856. return { code: generated.code, map: map };
  17857. };
  17858. sourceNode$1.SourceNode = SourceNode$1;
  17859. /*
  17860. * Copyright 2009-2011 Mozilla Foundation and contributors
  17861. * Licensed under the New BSD license. See LICENSE.txt or:
  17862. * http://opensource.org/licenses/BSD-3-Clause
  17863. */
  17864. var SourceMapGenerator$6 = sourceMap$2.SourceMapGenerator = sourceMapGenerator$1.SourceMapGenerator;
  17865. var SourceMapConsumer$5 = sourceMap$2.SourceMapConsumer = sourceMapConsumer$1.SourceMapConsumer;
  17866. sourceMap$2.SourceNode = sourceNode$1.SourceNode;
  17867. const PURE_ANNOTATION = `/*#__PURE__*/`;
  17868. const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
  17869. function createCodegenContext(ast, { mode = 'function', prefixIdentifiers = mode === 'module', sourceMap = false, filename = `template.vue.html`, scopeId = null, optimizeImports = false, runtimeGlobalName = `Vue`, runtimeModuleName = `vue`, ssrRuntimeModuleName = 'vue/server-renderer', ssr = false, isTS = false, inSSR = false }) {
  17870. const context = {
  17871. mode,
  17872. prefixIdentifiers,
  17873. sourceMap,
  17874. filename,
  17875. scopeId,
  17876. optimizeImports,
  17877. runtimeGlobalName,
  17878. runtimeModuleName,
  17879. ssrRuntimeModuleName,
  17880. ssr,
  17881. isTS,
  17882. inSSR,
  17883. source: ast.loc.source,
  17884. code: ``,
  17885. column: 1,
  17886. line: 1,
  17887. offset: 0,
  17888. indentLevel: 0,
  17889. pure: false,
  17890. map: undefined,
  17891. helper(key) {
  17892. return `_${helperNameMap[key]}`;
  17893. },
  17894. push(code, node) {
  17895. context.code += code;
  17896. if (context.map) {
  17897. if (node) {
  17898. let name;
  17899. if (node.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && !node.isStatic) {
  17900. const content = node.content.replace(/^_ctx\./, '');
  17901. if (content !== node.content && isSimpleIdentifier(content)) {
  17902. name = content;
  17903. }
  17904. }
  17905. addMapping(node.loc.start, name);
  17906. }
  17907. advancePositionWithMutation(context, code);
  17908. if (node && node.loc !== locStub) {
  17909. addMapping(node.loc.end);
  17910. }
  17911. }
  17912. },
  17913. indent() {
  17914. newline(++context.indentLevel);
  17915. },
  17916. deindent(withoutNewLine = false) {
  17917. if (withoutNewLine) {
  17918. --context.indentLevel;
  17919. }
  17920. else {
  17921. newline(--context.indentLevel);
  17922. }
  17923. },
  17924. newline() {
  17925. newline(context.indentLevel);
  17926. }
  17927. };
  17928. function newline(n) {
  17929. context.push('\n' + ` `.repeat(n));
  17930. }
  17931. function addMapping(loc, name) {
  17932. context.map.addMapping({
  17933. name,
  17934. source: context.filename,
  17935. original: {
  17936. line: loc.line,
  17937. column: loc.column - 1 // source-map column is 0 based
  17938. },
  17939. generated: {
  17940. line: context.line,
  17941. column: context.column - 1
  17942. }
  17943. });
  17944. }
  17945. if (sourceMap) {
  17946. // lazy require source-map implementation, only in non-browser builds
  17947. context.map = new SourceMapGenerator$6();
  17948. context.map.setSourceContent(filename, context.source);
  17949. }
  17950. return context;
  17951. }
  17952. function generate(ast, options = {}) {
  17953. const context = createCodegenContext(ast, options);
  17954. if (options.onContextCreated)
  17955. options.onContextCreated(context);
  17956. const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
  17957. const helpers = Array.from(ast.helpers);
  17958. const hasHelpers = helpers.length > 0;
  17959. const useWithBlock = !prefixIdentifiers && mode !== 'module';
  17960. const genScopeId = scopeId != null && mode === 'module';
  17961. const isSetupInlined = !!options.inline;
  17962. // preambles
  17963. // in setup() inline mode, the preamble is generated in a sub context
  17964. // and returned separately.
  17965. const preambleContext = isSetupInlined
  17966. ? createCodegenContext(ast, options)
  17967. : context;
  17968. if (mode === 'module') {
  17969. genModulePreamble(ast, preambleContext, genScopeId, isSetupInlined);
  17970. }
  17971. else {
  17972. genFunctionPreamble(ast, preambleContext);
  17973. }
  17974. // enter render function
  17975. const functionName = ssr ? `ssrRender` : `render`;
  17976. const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
  17977. if (options.bindingMetadata && !options.inline) {
  17978. // binding optimization args
  17979. args.push('$props', '$setup', '$data', '$options');
  17980. }
  17981. const signature = options.isTS
  17982. ? args.map(arg => `${arg}: any`).join(',')
  17983. : args.join(', ');
  17984. if (isSetupInlined) {
  17985. push(`(${signature}) => {`);
  17986. }
  17987. else {
  17988. push(`function ${functionName}(${signature}) {`);
  17989. }
  17990. indent();
  17991. if (useWithBlock) {
  17992. push(`with (_ctx) {`);
  17993. indent();
  17994. // function mode const declarations should be inside with block
  17995. // also they should be renamed to avoid collision with user properties
  17996. if (hasHelpers) {
  17997. push(`const { ${helpers.map(aliasHelper).join(', ')} } = _Vue`);
  17998. push(`\n`);
  17999. newline();
  18000. }
  18001. }
  18002. // generate asset resolution statements
  18003. if (ast.components.length) {
  18004. genAssets(ast.components, 'component', context);
  18005. if (ast.directives.length || ast.temps > 0) {
  18006. newline();
  18007. }
  18008. }
  18009. if (ast.directives.length) {
  18010. genAssets(ast.directives, 'directive', context);
  18011. if (ast.temps > 0) {
  18012. newline();
  18013. }
  18014. }
  18015. if (ast.temps > 0) {
  18016. push(`let `);
  18017. for (let i = 0; i < ast.temps; i++) {
  18018. push(`${i > 0 ? `, ` : ``}_temp${i}`);
  18019. }
  18020. }
  18021. if (ast.components.length || ast.directives.length || ast.temps) {
  18022. push(`\n`);
  18023. newline();
  18024. }
  18025. // generate the VNode tree expression
  18026. if (!ssr) {
  18027. push(`return `);
  18028. }
  18029. if (ast.codegenNode) {
  18030. genNode(ast.codegenNode, context);
  18031. }
  18032. else {
  18033. push(`null`);
  18034. }
  18035. if (useWithBlock) {
  18036. deindent();
  18037. push(`}`);
  18038. }
  18039. deindent();
  18040. push(`}`);
  18041. return {
  18042. ast,
  18043. code: context.code,
  18044. preamble: isSetupInlined ? preambleContext.code : ``,
  18045. // SourceMapGenerator does have toJSON() method but it's not in the types
  18046. map: context.map ? context.map.toJSON() : undefined
  18047. };
  18048. }
  18049. function genFunctionPreamble(ast, context) {
  18050. const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName, ssrRuntimeModuleName } = context;
  18051. const VueBinding = ssr
  18052. ? `require(${JSON.stringify(runtimeModuleName)})`
  18053. : runtimeGlobalName;
  18054. // Generate const declaration for helpers
  18055. // In prefix mode, we place the const declaration at top so it's done
  18056. // only once; But if we not prefixing, we place the declaration inside the
  18057. // with block so it doesn't incur the `in` check cost for every helper access.
  18058. const helpers = Array.from(ast.helpers);
  18059. if (helpers.length > 0) {
  18060. if (prefixIdentifiers) {
  18061. push(`const { ${helpers.map(aliasHelper).join(', ')} } = ${VueBinding}\n`);
  18062. }
  18063. else {
  18064. // "with" mode.
  18065. // save Vue in a separate variable to avoid collision
  18066. push(`const _Vue = ${VueBinding}\n`);
  18067. // in "with" mode, helpers are declared inside the with block to avoid
  18068. // has check cost, but hoists are lifted out of the function - we need
  18069. // to provide the helper here.
  18070. if (ast.hoists.length) {
  18071. const staticHelpers = [
  18072. CREATE_VNODE,
  18073. CREATE_ELEMENT_VNODE,
  18074. CREATE_COMMENT,
  18075. CREATE_TEXT,
  18076. CREATE_STATIC
  18077. ]
  18078. .filter(helper => helpers.includes(helper))
  18079. .map(aliasHelper)
  18080. .join(', ');
  18081. push(`const { ${staticHelpers} } = _Vue\n`);
  18082. }
  18083. }
  18084. }
  18085. // generate variables for ssr helpers
  18086. if (ast.ssrHelpers && ast.ssrHelpers.length) {
  18087. // ssr guarantees prefixIdentifier: true
  18088. push(`const { ${ast.ssrHelpers
  18089. .map(aliasHelper)
  18090. .join(', ')} } = require("${ssrRuntimeModuleName}")\n`);
  18091. }
  18092. genHoists(ast.hoists, context);
  18093. newline();
  18094. push(`return `);
  18095. }
  18096. function genModulePreamble(ast, context, genScopeId, inline) {
  18097. const { push, newline, optimizeImports, runtimeModuleName, ssrRuntimeModuleName } = context;
  18098. if (genScopeId && ast.hoists.length) {
  18099. ast.helpers.add(PUSH_SCOPE_ID);
  18100. ast.helpers.add(POP_SCOPE_ID);
  18101. }
  18102. // generate import statements for helpers
  18103. if (ast.helpers.size) {
  18104. const helpers = Array.from(ast.helpers);
  18105. if (optimizeImports) {
  18106. // when bundled with webpack with code-split, calling an import binding
  18107. // as a function leads to it being wrapped with `Object(a.b)` or `(0,a.b)`,
  18108. // incurring both payload size increase and potential perf overhead.
  18109. // therefore we assign the imports to variables (which is a constant ~50b
  18110. // cost per-component instead of scaling with template size)
  18111. push(`import { ${helpers
  18112. .map(s => helperNameMap[s])
  18113. .join(', ')} } from ${JSON.stringify(runtimeModuleName)}\n`);
  18114. push(`\n// Binding optimization for webpack code-split\nconst ${helpers
  18115. .map(s => `_${helperNameMap[s]} = ${helperNameMap[s]}`)
  18116. .join(', ')}\n`);
  18117. }
  18118. else {
  18119. push(`import { ${helpers
  18120. .map(s => `${helperNameMap[s]} as _${helperNameMap[s]}`)
  18121. .join(', ')} } from ${JSON.stringify(runtimeModuleName)}\n`);
  18122. }
  18123. }
  18124. if (ast.ssrHelpers && ast.ssrHelpers.length) {
  18125. push(`import { ${ast.ssrHelpers
  18126. .map(s => `${helperNameMap[s]} as _${helperNameMap[s]}`)
  18127. .join(', ')} } from "${ssrRuntimeModuleName}"\n`);
  18128. }
  18129. if (ast.imports.length) {
  18130. genImports(ast.imports, context);
  18131. newline();
  18132. }
  18133. genHoists(ast.hoists, context);
  18134. newline();
  18135. if (!inline) {
  18136. push(`export `);
  18137. }
  18138. }
  18139. function genAssets(assets, type, { helper, push, newline, isTS }) {
  18140. const resolver = helper(type === 'component'
  18141. ? RESOLVE_COMPONENT
  18142. : RESOLVE_DIRECTIVE);
  18143. for (let i = 0; i < assets.length; i++) {
  18144. let id = assets[i];
  18145. // potential component implicit self-reference inferred from SFC filename
  18146. const maybeSelfReference = id.endsWith('__self');
  18147. if (maybeSelfReference) {
  18148. id = id.slice(0, -6);
  18149. }
  18150. push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}`);
  18151. if (i < assets.length - 1) {
  18152. newline();
  18153. }
  18154. }
  18155. }
  18156. function genHoists(hoists, context) {
  18157. if (!hoists.length) {
  18158. return;
  18159. }
  18160. context.pure = true;
  18161. const { push, newline, helper, scopeId, mode } = context;
  18162. const genScopeId = scopeId != null && mode !== 'function';
  18163. newline();
  18164. // generate inlined withScopeId helper
  18165. if (genScopeId) {
  18166. push(`const _withScopeId = n => (${helper(PUSH_SCOPE_ID)}("${scopeId}"),n=n(),${helper(POP_SCOPE_ID)}(),n)`);
  18167. newline();
  18168. }
  18169. for (let i = 0; i < hoists.length; i++) {
  18170. const exp = hoists[i];
  18171. if (exp) {
  18172. const needScopeIdWrapper = genScopeId && exp.type === 13 /* NodeTypes.VNODE_CALL */;
  18173. push(`const _hoisted_${i + 1} = ${needScopeIdWrapper ? `${PURE_ANNOTATION} _withScopeId(() => ` : ``}`);
  18174. genNode(exp, context);
  18175. if (needScopeIdWrapper) {
  18176. push(`)`);
  18177. }
  18178. newline();
  18179. }
  18180. }
  18181. context.pure = false;
  18182. }
  18183. function genImports(importsOptions, context) {
  18184. if (!importsOptions.length) {
  18185. return;
  18186. }
  18187. importsOptions.forEach(imports => {
  18188. context.push(`import `);
  18189. genNode(imports.exp, context);
  18190. context.push(` from '${imports.path}'`);
  18191. context.newline();
  18192. });
  18193. }
  18194. function isText(n) {
  18195. return (isString$2(n) ||
  18196. n.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
  18197. n.type === 2 /* NodeTypes.TEXT */ ||
  18198. n.type === 5 /* NodeTypes.INTERPOLATION */ ||
  18199. n.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */);
  18200. }
  18201. function genNodeListAsArray(nodes, context) {
  18202. const multilines = nodes.length > 3 ||
  18203. (nodes.some(n => isArray$3(n) || !isText(n)));
  18204. context.push(`[`);
  18205. multilines && context.indent();
  18206. genNodeList(nodes, context, multilines);
  18207. multilines && context.deindent();
  18208. context.push(`]`);
  18209. }
  18210. function genNodeList(nodes, context, multilines = false, comma = true) {
  18211. const { push, newline } = context;
  18212. for (let i = 0; i < nodes.length; i++) {
  18213. const node = nodes[i];
  18214. if (isString$2(node)) {
  18215. push(node);
  18216. }
  18217. else if (isArray$3(node)) {
  18218. genNodeListAsArray(node, context);
  18219. }
  18220. else {
  18221. genNode(node, context);
  18222. }
  18223. if (i < nodes.length - 1) {
  18224. if (multilines) {
  18225. comma && push(',');
  18226. newline();
  18227. }
  18228. else {
  18229. comma && push(', ');
  18230. }
  18231. }
  18232. }
  18233. }
  18234. function genNode(node, context) {
  18235. if (isString$2(node)) {
  18236. context.push(node);
  18237. return;
  18238. }
  18239. if (isSymbol$1(node)) {
  18240. context.push(context.helper(node));
  18241. return;
  18242. }
  18243. switch (node.type) {
  18244. case 1 /* NodeTypes.ELEMENT */:
  18245. case 9 /* NodeTypes.IF */:
  18246. case 11 /* NodeTypes.FOR */:
  18247. assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
  18248. `Apply appropriate transforms first.`);
  18249. genNode(node.codegenNode, context);
  18250. break;
  18251. case 2 /* NodeTypes.TEXT */:
  18252. genText(node, context);
  18253. break;
  18254. case 4 /* NodeTypes.SIMPLE_EXPRESSION */:
  18255. genExpression(node, context);
  18256. break;
  18257. case 5 /* NodeTypes.INTERPOLATION */:
  18258. genInterpolation(node, context);
  18259. break;
  18260. case 12 /* NodeTypes.TEXT_CALL */:
  18261. genNode(node.codegenNode, context);
  18262. break;
  18263. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  18264. genCompoundExpression(node, context);
  18265. break;
  18266. case 3 /* NodeTypes.COMMENT */:
  18267. genComment(node, context);
  18268. break;
  18269. case 13 /* NodeTypes.VNODE_CALL */:
  18270. genVNodeCall(node, context);
  18271. break;
  18272. case 14 /* NodeTypes.JS_CALL_EXPRESSION */:
  18273. genCallExpression(node, context);
  18274. break;
  18275. case 15 /* NodeTypes.JS_OBJECT_EXPRESSION */:
  18276. genObjectExpression(node, context);
  18277. break;
  18278. case 17 /* NodeTypes.JS_ARRAY_EXPRESSION */:
  18279. genArrayExpression(node, context);
  18280. break;
  18281. case 18 /* NodeTypes.JS_FUNCTION_EXPRESSION */:
  18282. genFunctionExpression(node, context);
  18283. break;
  18284. case 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */:
  18285. genConditionalExpression(node, context);
  18286. break;
  18287. case 20 /* NodeTypes.JS_CACHE_EXPRESSION */:
  18288. genCacheExpression(node, context);
  18289. break;
  18290. case 21 /* NodeTypes.JS_BLOCK_STATEMENT */:
  18291. genNodeList(node.body, context, true, false);
  18292. break;
  18293. // SSR only types
  18294. case 22 /* NodeTypes.JS_TEMPLATE_LITERAL */:
  18295. genTemplateLiteral(node, context);
  18296. break;
  18297. case 23 /* NodeTypes.JS_IF_STATEMENT */:
  18298. genIfStatement(node, context);
  18299. break;
  18300. case 24 /* NodeTypes.JS_ASSIGNMENT_EXPRESSION */:
  18301. genAssignmentExpression(node, context);
  18302. break;
  18303. case 25 /* NodeTypes.JS_SEQUENCE_EXPRESSION */:
  18304. genSequenceExpression(node, context);
  18305. break;
  18306. case 26 /* NodeTypes.JS_RETURN_STATEMENT */:
  18307. genReturnStatement(node, context);
  18308. break;
  18309. /* istanbul ignore next */
  18310. case 10 /* NodeTypes.IF_BRANCH */:
  18311. // noop
  18312. break;
  18313. default:
  18314. {
  18315. assert(false, `unhandled codegen node type: ${node.type}`);
  18316. // make sure we exhaust all possible types
  18317. const exhaustiveCheck = node;
  18318. return exhaustiveCheck;
  18319. }
  18320. }
  18321. }
  18322. function genText(node, context) {
  18323. context.push(JSON.stringify(node.content), node);
  18324. }
  18325. function genExpression(node, context) {
  18326. const { content, isStatic } = node;
  18327. context.push(isStatic ? JSON.stringify(content) : content, node);
  18328. }
  18329. function genInterpolation(node, context) {
  18330. const { push, helper, pure } = context;
  18331. if (pure)
  18332. push(PURE_ANNOTATION);
  18333. push(`${helper(TO_DISPLAY_STRING)}(`);
  18334. genNode(node.content, context);
  18335. push(`)`);
  18336. }
  18337. function genCompoundExpression(node, context) {
  18338. for (let i = 0; i < node.children.length; i++) {
  18339. const child = node.children[i];
  18340. if (isString$2(child)) {
  18341. context.push(child);
  18342. }
  18343. else {
  18344. genNode(child, context);
  18345. }
  18346. }
  18347. }
  18348. function genExpressionAsPropertyKey(node, context) {
  18349. const { push } = context;
  18350. if (node.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) {
  18351. push(`[`);
  18352. genCompoundExpression(node, context);
  18353. push(`]`);
  18354. }
  18355. else if (node.isStatic) {
  18356. // only quote keys if necessary
  18357. const text = isSimpleIdentifier(node.content)
  18358. ? node.content
  18359. : JSON.stringify(node.content);
  18360. push(text, node);
  18361. }
  18362. else {
  18363. push(`[${node.content}]`, node);
  18364. }
  18365. }
  18366. function genComment(node, context) {
  18367. const { push, helper, pure } = context;
  18368. if (pure) {
  18369. push(PURE_ANNOTATION);
  18370. }
  18371. push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
  18372. }
  18373. function genVNodeCall(node, context) {
  18374. const { push, helper, pure } = context;
  18375. const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking, isComponent } = node;
  18376. if (directives) {
  18377. push(helper(WITH_DIRECTIVES) + `(`);
  18378. }
  18379. if (isBlock) {
  18380. push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
  18381. }
  18382. if (pure) {
  18383. push(PURE_ANNOTATION);
  18384. }
  18385. const callHelper = isBlock
  18386. ? getVNodeBlockHelper(context.inSSR, isComponent)
  18387. : getVNodeHelper(context.inSSR, isComponent);
  18388. push(helper(callHelper) + `(`, node);
  18389. genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
  18390. push(`)`);
  18391. if (isBlock) {
  18392. push(`)`);
  18393. }
  18394. if (directives) {
  18395. push(`, `);
  18396. genNode(directives, context);
  18397. push(`)`);
  18398. }
  18399. }
  18400. function genNullableArgs(args) {
  18401. let i = args.length;
  18402. while (i--) {
  18403. if (args[i] != null)
  18404. break;
  18405. }
  18406. return args.slice(0, i + 1).map(arg => arg || `null`);
  18407. }
  18408. // JavaScript
  18409. function genCallExpression(node, context) {
  18410. const { push, helper, pure } = context;
  18411. const callee = isString$2(node.callee) ? node.callee : helper(node.callee);
  18412. if (pure) {
  18413. push(PURE_ANNOTATION);
  18414. }
  18415. push(callee + `(`, node);
  18416. genNodeList(node.arguments, context);
  18417. push(`)`);
  18418. }
  18419. function genObjectExpression(node, context) {
  18420. const { push, indent, deindent, newline } = context;
  18421. const { properties } = node;
  18422. if (!properties.length) {
  18423. push(`{}`, node);
  18424. return;
  18425. }
  18426. const multilines = properties.length > 1 ||
  18427. (properties.some(p => p.value.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */));
  18428. push(multilines ? `{` : `{ `);
  18429. multilines && indent();
  18430. for (let i = 0; i < properties.length; i++) {
  18431. const { key, value } = properties[i];
  18432. // key
  18433. genExpressionAsPropertyKey(key, context);
  18434. push(`: `);
  18435. // value
  18436. genNode(value, context);
  18437. if (i < properties.length - 1) {
  18438. // will only reach this if it's multilines
  18439. push(`,`);
  18440. newline();
  18441. }
  18442. }
  18443. multilines && deindent();
  18444. push(multilines ? `}` : ` }`);
  18445. }
  18446. function genArrayExpression(node, context) {
  18447. genNodeListAsArray(node.elements, context);
  18448. }
  18449. function genFunctionExpression(node, context) {
  18450. const { push, indent, deindent } = context;
  18451. const { params, returns, body, newline, isSlot } = node;
  18452. if (isSlot) {
  18453. // wrap slot functions with owner context
  18454. push(`_${helperNameMap[WITH_CTX]}(`);
  18455. }
  18456. push(`(`, node);
  18457. if (isArray$3(params)) {
  18458. genNodeList(params, context);
  18459. }
  18460. else if (params) {
  18461. genNode(params, context);
  18462. }
  18463. push(`) => `);
  18464. if (newline || body) {
  18465. push(`{`);
  18466. indent();
  18467. }
  18468. if (returns) {
  18469. if (newline) {
  18470. push(`return `);
  18471. }
  18472. if (isArray$3(returns)) {
  18473. genNodeListAsArray(returns, context);
  18474. }
  18475. else {
  18476. genNode(returns, context);
  18477. }
  18478. }
  18479. else if (body) {
  18480. genNode(body, context);
  18481. }
  18482. if (newline || body) {
  18483. deindent();
  18484. push(`}`);
  18485. }
  18486. if (isSlot) {
  18487. push(`)`);
  18488. }
  18489. }
  18490. function genConditionalExpression(node, context) {
  18491. const { test, consequent, alternate, newline: needNewline } = node;
  18492. const { push, indent, deindent, newline } = context;
  18493. if (test.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  18494. const needsParens = !isSimpleIdentifier(test.content);
  18495. needsParens && push(`(`);
  18496. genExpression(test, context);
  18497. needsParens && push(`)`);
  18498. }
  18499. else {
  18500. push(`(`);
  18501. genNode(test, context);
  18502. push(`)`);
  18503. }
  18504. needNewline && indent();
  18505. context.indentLevel++;
  18506. needNewline || push(` `);
  18507. push(`? `);
  18508. genNode(consequent, context);
  18509. context.indentLevel--;
  18510. needNewline && newline();
  18511. needNewline || push(` `);
  18512. push(`: `);
  18513. const isNested = alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */;
  18514. if (!isNested) {
  18515. context.indentLevel++;
  18516. }
  18517. genNode(alternate, context);
  18518. if (!isNested) {
  18519. context.indentLevel--;
  18520. }
  18521. needNewline && deindent(true /* without newline */);
  18522. }
  18523. function genCacheExpression(node, context) {
  18524. const { push, helper, indent, deindent, newline } = context;
  18525. push(`_cache[${node.index}] || (`);
  18526. if (node.isVNode) {
  18527. indent();
  18528. push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
  18529. newline();
  18530. }
  18531. push(`_cache[${node.index}] = `);
  18532. genNode(node.value, context);
  18533. if (node.isVNode) {
  18534. push(`,`);
  18535. newline();
  18536. push(`${helper(SET_BLOCK_TRACKING)}(1),`);
  18537. newline();
  18538. push(`_cache[${node.index}]`);
  18539. deindent();
  18540. }
  18541. push(`)`);
  18542. }
  18543. function genTemplateLiteral(node, context) {
  18544. const { push, indent, deindent } = context;
  18545. push('`');
  18546. const l = node.elements.length;
  18547. const multilines = l > 3;
  18548. for (let i = 0; i < l; i++) {
  18549. const e = node.elements[i];
  18550. if (isString$2(e)) {
  18551. push(e.replace(/(`|\$|\\)/g, '\\$1'));
  18552. }
  18553. else {
  18554. push('${');
  18555. if (multilines)
  18556. indent();
  18557. genNode(e, context);
  18558. if (multilines)
  18559. deindent();
  18560. push('}');
  18561. }
  18562. }
  18563. push('`');
  18564. }
  18565. function genIfStatement(node, context) {
  18566. const { push, indent, deindent } = context;
  18567. const { test, consequent, alternate } = node;
  18568. push(`if (`);
  18569. genNode(test, context);
  18570. push(`) {`);
  18571. indent();
  18572. genNode(consequent, context);
  18573. deindent();
  18574. push(`}`);
  18575. if (alternate) {
  18576. push(` else `);
  18577. if (alternate.type === 23 /* NodeTypes.JS_IF_STATEMENT */) {
  18578. genIfStatement(alternate, context);
  18579. }
  18580. else {
  18581. push(`{`);
  18582. indent();
  18583. genNode(alternate, context);
  18584. deindent();
  18585. push(`}`);
  18586. }
  18587. }
  18588. }
  18589. function genAssignmentExpression(node, context) {
  18590. genNode(node.left, context);
  18591. context.push(` = `);
  18592. genNode(node.right, context);
  18593. }
  18594. function genSequenceExpression(node, context) {
  18595. context.push(`(`);
  18596. genNodeList(node.expressions, context);
  18597. context.push(`)`);
  18598. }
  18599. function genReturnStatement({ returns }, context) {
  18600. context.push(`return `);
  18601. if (isArray$3(returns)) {
  18602. genNodeListAsArray(returns, context);
  18603. }
  18604. else {
  18605. genNode(returns, context);
  18606. }
  18607. }
  18608. // @ts-check
  18609. /** @typedef { import('estree').BaseNode} BaseNode */
  18610. /** @typedef {{
  18611. skip: () => void;
  18612. remove: () => void;
  18613. replace: (node: BaseNode) => void;
  18614. }} WalkerContext */
  18615. class WalkerBase {
  18616. constructor() {
  18617. /** @type {boolean} */
  18618. this.should_skip = false;
  18619. /** @type {boolean} */
  18620. this.should_remove = false;
  18621. /** @type {BaseNode | null} */
  18622. this.replacement = null;
  18623. /** @type {WalkerContext} */
  18624. this.context = {
  18625. skip: () => (this.should_skip = true),
  18626. remove: () => (this.should_remove = true),
  18627. replace: (node) => (this.replacement = node)
  18628. };
  18629. }
  18630. /**
  18631. *
  18632. * @param {any} parent
  18633. * @param {string} prop
  18634. * @param {number} index
  18635. * @param {BaseNode} node
  18636. */
  18637. replace(parent, prop, index, node) {
  18638. if (parent) {
  18639. if (index !== null) {
  18640. parent[prop][index] = node;
  18641. } else {
  18642. parent[prop] = node;
  18643. }
  18644. }
  18645. }
  18646. /**
  18647. *
  18648. * @param {any} parent
  18649. * @param {string} prop
  18650. * @param {number} index
  18651. */
  18652. remove(parent, prop, index) {
  18653. if (parent) {
  18654. if (index !== null) {
  18655. parent[prop].splice(index, 1);
  18656. } else {
  18657. delete parent[prop];
  18658. }
  18659. }
  18660. }
  18661. }
  18662. // @ts-check
  18663. /** @typedef { import('estree').BaseNode} BaseNode */
  18664. /** @typedef { import('./walker.js').WalkerContext} WalkerContext */
  18665. /** @typedef {(
  18666. * this: WalkerContext,
  18667. * node: BaseNode,
  18668. * parent: BaseNode,
  18669. * key: string,
  18670. * index: number
  18671. * ) => void} SyncHandler */
  18672. class SyncWalker extends WalkerBase {
  18673. /**
  18674. *
  18675. * @param {SyncHandler} enter
  18676. * @param {SyncHandler} leave
  18677. */
  18678. constructor(enter, leave) {
  18679. super();
  18680. /** @type {SyncHandler} */
  18681. this.enter = enter;
  18682. /** @type {SyncHandler} */
  18683. this.leave = leave;
  18684. }
  18685. /**
  18686. *
  18687. * @param {BaseNode} node
  18688. * @param {BaseNode} parent
  18689. * @param {string} [prop]
  18690. * @param {number} [index]
  18691. * @returns {BaseNode}
  18692. */
  18693. visit(node, parent, prop, index) {
  18694. if (node) {
  18695. if (this.enter) {
  18696. const _should_skip = this.should_skip;
  18697. const _should_remove = this.should_remove;
  18698. const _replacement = this.replacement;
  18699. this.should_skip = false;
  18700. this.should_remove = false;
  18701. this.replacement = null;
  18702. this.enter.call(this.context, node, parent, prop, index);
  18703. if (this.replacement) {
  18704. node = this.replacement;
  18705. this.replace(parent, prop, index, node);
  18706. }
  18707. if (this.should_remove) {
  18708. this.remove(parent, prop, index);
  18709. }
  18710. const skipped = this.should_skip;
  18711. const removed = this.should_remove;
  18712. this.should_skip = _should_skip;
  18713. this.should_remove = _should_remove;
  18714. this.replacement = _replacement;
  18715. if (skipped) return node;
  18716. if (removed) return null;
  18717. }
  18718. for (const key in node) {
  18719. const value = node[key];
  18720. if (typeof value !== "object") {
  18721. continue;
  18722. } else if (Array.isArray(value)) {
  18723. for (let i = 0; i < value.length; i += 1) {
  18724. if (value[i] !== null && typeof value[i].type === 'string') {
  18725. if (!this.visit(value[i], node, key, i)) {
  18726. // removed
  18727. i--;
  18728. }
  18729. }
  18730. }
  18731. } else if (value !== null && typeof value.type === "string") {
  18732. this.visit(value, node, key, null);
  18733. }
  18734. }
  18735. if (this.leave) {
  18736. const _replacement = this.replacement;
  18737. const _should_remove = this.should_remove;
  18738. this.replacement = null;
  18739. this.should_remove = false;
  18740. this.leave.call(this.context, node, parent, prop, index);
  18741. if (this.replacement) {
  18742. node = this.replacement;
  18743. this.replace(parent, prop, index, node);
  18744. }
  18745. if (this.should_remove) {
  18746. this.remove(parent, prop, index);
  18747. }
  18748. const removed = this.should_remove;
  18749. this.replacement = _replacement;
  18750. this.should_remove = _should_remove;
  18751. if (removed) return null;
  18752. }
  18753. }
  18754. return node;
  18755. }
  18756. }
  18757. // @ts-check
  18758. /** @typedef { import('estree').BaseNode} BaseNode */
  18759. /** @typedef { import('./sync.js').SyncHandler} SyncHandler */
  18760. /** @typedef { import('./async.js').AsyncHandler} AsyncHandler */
  18761. /**
  18762. *
  18763. * @param {BaseNode} ast
  18764. * @param {{
  18765. * enter?: SyncHandler
  18766. * leave?: SyncHandler
  18767. * }} walker
  18768. * @returns {BaseNode}
  18769. */
  18770. function walk$1(ast, { enter, leave }) {
  18771. const instance = new SyncWalker(enter, leave);
  18772. return instance.visit(ast, null);
  18773. }
  18774. function walkIdentifiers(root, onIdentifier, includeAll = false, parentStack = [], knownIds = Object.create(null)) {
  18775. const rootExp = root.type === 'Program' &&
  18776. root.body[0].type === 'ExpressionStatement' &&
  18777. root.body[0].expression;
  18778. walk$1(root, {
  18779. enter(node, parent) {
  18780. parent && parentStack.push(parent);
  18781. if (parent &&
  18782. parent.type.startsWith('TS') &&
  18783. parent.type !== 'TSAsExpression' &&
  18784. parent.type !== 'TSNonNullExpression' &&
  18785. parent.type !== 'TSTypeAssertion') {
  18786. return this.skip();
  18787. }
  18788. if (node.type === 'Identifier') {
  18789. const isLocal = !!knownIds[node.name];
  18790. const isRefed = isReferencedIdentifier(node, parent, parentStack);
  18791. if (includeAll || (isRefed && !isLocal)) {
  18792. onIdentifier(node, parent, parentStack, isRefed, isLocal);
  18793. }
  18794. }
  18795. else if (node.type === 'ObjectProperty' &&
  18796. parent.type === 'ObjectPattern') {
  18797. node.inPattern = true;
  18798. }
  18799. else if (isFunctionType(node)) {
  18800. // walk function expressions and add its arguments to known identifiers
  18801. // so that we don't prefix them
  18802. walkFunctionParams(node, id => markScopeIdentifier(node, id, knownIds));
  18803. }
  18804. else if (node.type === 'BlockStatement') {
  18805. // #3445 record block-level local variables
  18806. walkBlockDeclarations(node, id => markScopeIdentifier(node, id, knownIds));
  18807. }
  18808. },
  18809. leave(node, parent) {
  18810. parent && parentStack.pop();
  18811. if (node !== rootExp && node.scopeIds) {
  18812. for (const id of node.scopeIds) {
  18813. knownIds[id]--;
  18814. if (knownIds[id] === 0) {
  18815. delete knownIds[id];
  18816. }
  18817. }
  18818. }
  18819. }
  18820. });
  18821. }
  18822. function isReferencedIdentifier(id, parent, parentStack) {
  18823. if (!parent) {
  18824. return true;
  18825. }
  18826. // is a special keyword but parsed as identifier
  18827. if (id.name === 'arguments') {
  18828. return false;
  18829. }
  18830. if (isReferenced(id, parent)) {
  18831. return true;
  18832. }
  18833. // babel's isReferenced check returns false for ids being assigned to, so we
  18834. // need to cover those cases here
  18835. switch (parent.type) {
  18836. case 'AssignmentExpression':
  18837. case 'AssignmentPattern':
  18838. return true;
  18839. case 'ObjectPattern':
  18840. case 'ArrayPattern':
  18841. return isInDestructureAssignment(parent, parentStack);
  18842. }
  18843. return false;
  18844. }
  18845. function isInDestructureAssignment(parent, parentStack) {
  18846. if (parent &&
  18847. (parent.type === 'ObjectProperty' || parent.type === 'ArrayPattern')) {
  18848. let i = parentStack.length;
  18849. while (i--) {
  18850. const p = parentStack[i];
  18851. if (p.type === 'AssignmentExpression') {
  18852. return true;
  18853. }
  18854. else if (p.type !== 'ObjectProperty' && !p.type.endsWith('Pattern')) {
  18855. break;
  18856. }
  18857. }
  18858. }
  18859. return false;
  18860. }
  18861. function walkFunctionParams(node, onIdent) {
  18862. for (const p of node.params) {
  18863. for (const id of extractIdentifiers(p)) {
  18864. onIdent(id);
  18865. }
  18866. }
  18867. }
  18868. function walkBlockDeclarations(block, onIdent) {
  18869. for (const stmt of block.body) {
  18870. if (stmt.type === 'VariableDeclaration') {
  18871. if (stmt.declare)
  18872. continue;
  18873. for (const decl of stmt.declarations) {
  18874. for (const id of extractIdentifiers(decl.id)) {
  18875. onIdent(id);
  18876. }
  18877. }
  18878. }
  18879. else if (stmt.type === 'FunctionDeclaration' ||
  18880. stmt.type === 'ClassDeclaration') {
  18881. if (stmt.declare || !stmt.id)
  18882. continue;
  18883. onIdent(stmt.id);
  18884. }
  18885. }
  18886. }
  18887. function extractIdentifiers(param, nodes = []) {
  18888. switch (param.type) {
  18889. case 'Identifier':
  18890. nodes.push(param);
  18891. break;
  18892. case 'MemberExpression':
  18893. let object = param;
  18894. while (object.type === 'MemberExpression') {
  18895. object = object.object;
  18896. }
  18897. nodes.push(object);
  18898. break;
  18899. case 'ObjectPattern':
  18900. for (const prop of param.properties) {
  18901. if (prop.type === 'RestElement') {
  18902. extractIdentifiers(prop.argument, nodes);
  18903. }
  18904. else {
  18905. extractIdentifiers(prop.value, nodes);
  18906. }
  18907. }
  18908. break;
  18909. case 'ArrayPattern':
  18910. param.elements.forEach(element => {
  18911. if (element)
  18912. extractIdentifiers(element, nodes);
  18913. });
  18914. break;
  18915. case 'RestElement':
  18916. extractIdentifiers(param.argument, nodes);
  18917. break;
  18918. case 'AssignmentPattern':
  18919. extractIdentifiers(param.left, nodes);
  18920. break;
  18921. }
  18922. return nodes;
  18923. }
  18924. function markScopeIdentifier(node, child, knownIds) {
  18925. const { name } = child;
  18926. if (node.scopeIds && node.scopeIds.has(name)) {
  18927. return;
  18928. }
  18929. if (name in knownIds) {
  18930. knownIds[name]++;
  18931. }
  18932. else {
  18933. knownIds[name] = 1;
  18934. }
  18935. (node.scopeIds || (node.scopeIds = new Set())).add(name);
  18936. }
  18937. const isFunctionType = (node) => {
  18938. return /Function(?:Expression|Declaration)$|Method$/.test(node.type);
  18939. };
  18940. const isStaticProperty = (node) => node &&
  18941. (node.type === 'ObjectProperty' || node.type === 'ObjectMethod') &&
  18942. !node.computed;
  18943. const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node;
  18944. /**
  18945. * Copied from https://github.com/babel/babel/blob/main/packages/babel-types/src/validators/isReferenced.ts
  18946. * To avoid runtime dependency on @babel/types (which includes process references)
  18947. * This file should not change very often in babel but we may need to keep it
  18948. * up-to-date from time to time.
  18949. *
  18950. * https://github.com/babel/babel/blob/main/LICENSE
  18951. *
  18952. */
  18953. function isReferenced(node, parent, grandparent) {
  18954. switch (parent.type) {
  18955. // yes: PARENT[NODE]
  18956. // yes: NODE.child
  18957. // no: parent.NODE
  18958. case 'MemberExpression':
  18959. case 'OptionalMemberExpression':
  18960. if (parent.property === node) {
  18961. return !!parent.computed;
  18962. }
  18963. return parent.object === node;
  18964. case 'JSXMemberExpression':
  18965. return parent.object === node;
  18966. // no: let NODE = init;
  18967. // yes: let id = NODE;
  18968. case 'VariableDeclarator':
  18969. return parent.init === node;
  18970. // yes: () => NODE
  18971. // no: (NODE) => {}
  18972. case 'ArrowFunctionExpression':
  18973. return parent.body === node;
  18974. // no: class { #NODE; }
  18975. // no: class { get #NODE() {} }
  18976. // no: class { #NODE() {} }
  18977. // no: class { fn() { return this.#NODE; } }
  18978. case 'PrivateName':
  18979. return false;
  18980. // no: class { NODE() {} }
  18981. // yes: class { [NODE]() {} }
  18982. // no: class { foo(NODE) {} }
  18983. case 'ClassMethod':
  18984. case 'ClassPrivateMethod':
  18985. case 'ObjectMethod':
  18986. if (parent.key === node) {
  18987. return !!parent.computed;
  18988. }
  18989. return false;
  18990. // yes: { [NODE]: "" }
  18991. // no: { NODE: "" }
  18992. // depends: { NODE }
  18993. // depends: { key: NODE }
  18994. case 'ObjectProperty':
  18995. if (parent.key === node) {
  18996. return !!parent.computed;
  18997. }
  18998. // parent.value === node
  18999. return !grandparent || grandparent.type !== 'ObjectPattern';
  19000. // no: class { NODE = value; }
  19001. // yes: class { [NODE] = value; }
  19002. // yes: class { key = NODE; }
  19003. case 'ClassProperty':
  19004. if (parent.key === node) {
  19005. return !!parent.computed;
  19006. }
  19007. return true;
  19008. case 'ClassPrivateProperty':
  19009. return parent.key !== node;
  19010. // no: class NODE {}
  19011. // yes: class Foo extends NODE {}
  19012. case 'ClassDeclaration':
  19013. case 'ClassExpression':
  19014. return parent.superClass === node;
  19015. // yes: left = NODE;
  19016. // no: NODE = right;
  19017. case 'AssignmentExpression':
  19018. return parent.right === node;
  19019. // no: [NODE = foo] = [];
  19020. // yes: [foo = NODE] = [];
  19021. case 'AssignmentPattern':
  19022. return parent.right === node;
  19023. // no: NODE: for (;;) {}
  19024. case 'LabeledStatement':
  19025. return false;
  19026. // no: try {} catch (NODE) {}
  19027. case 'CatchClause':
  19028. return false;
  19029. // no: function foo(...NODE) {}
  19030. case 'RestElement':
  19031. return false;
  19032. case 'BreakStatement':
  19033. case 'ContinueStatement':
  19034. return false;
  19035. // no: function NODE() {}
  19036. // no: function foo(NODE) {}
  19037. case 'FunctionDeclaration':
  19038. case 'FunctionExpression':
  19039. return false;
  19040. // no: export NODE from "foo";
  19041. // no: export * as NODE from "foo";
  19042. case 'ExportNamespaceSpecifier':
  19043. case 'ExportDefaultSpecifier':
  19044. return false;
  19045. // no: export { foo as NODE };
  19046. // yes: export { NODE as foo };
  19047. // no: export { NODE as foo } from "foo";
  19048. case 'ExportSpecifier':
  19049. // @ts-expect-error
  19050. if (grandparent === null || grandparent === void 0 ? void 0 : grandparent.source) {
  19051. return false;
  19052. }
  19053. return parent.local === node;
  19054. // no: import NODE from "foo";
  19055. // no: import * as NODE from "foo";
  19056. // no: import { NODE as foo } from "foo";
  19057. // no: import { foo as NODE } from "foo";
  19058. // no: import NODE from "bar";
  19059. case 'ImportDefaultSpecifier':
  19060. case 'ImportNamespaceSpecifier':
  19061. case 'ImportSpecifier':
  19062. return false;
  19063. // no: import "foo" assert { NODE: "json" }
  19064. case 'ImportAttribute':
  19065. return false;
  19066. // no: <div NODE="foo" />
  19067. case 'JSXAttribute':
  19068. return false;
  19069. // no: [NODE] = [];
  19070. // no: ({ NODE }) = [];
  19071. case 'ObjectPattern':
  19072. case 'ArrayPattern':
  19073. return false;
  19074. // no: new.NODE
  19075. // no: NODE.target
  19076. case 'MetaProperty':
  19077. return false;
  19078. // yes: type X = { someProperty: NODE }
  19079. // no: type X = { NODE: OtherType }
  19080. case 'ObjectTypeProperty':
  19081. return parent.key !== node;
  19082. // yes: enum X { Foo = NODE }
  19083. // no: enum X { NODE }
  19084. case 'TSEnumMember':
  19085. return parent.id !== node;
  19086. // yes: { [NODE]: value }
  19087. // no: { NODE: value }
  19088. case 'TSPropertySignature':
  19089. if (parent.key === node) {
  19090. return !!parent.computed;
  19091. }
  19092. return true;
  19093. }
  19094. return true;
  19095. }
  19096. const isLiteralWhitelisted = /*#__PURE__*/ makeMap('true,false,null,this');
  19097. const transformExpression = (node, context) => {
  19098. if (node.type === 5 /* NodeTypes.INTERPOLATION */) {
  19099. node.content = processExpression(node.content, context);
  19100. }
  19101. else if (node.type === 1 /* NodeTypes.ELEMENT */) {
  19102. // handle directives on element
  19103. for (let i = 0; i < node.props.length; i++) {
  19104. const dir = node.props[i];
  19105. // do not process for v-on & v-for since they are special handled
  19106. if (dir.type === 7 /* NodeTypes.DIRECTIVE */ && dir.name !== 'for') {
  19107. const exp = dir.exp;
  19108. const arg = dir.arg;
  19109. // do not process exp if this is v-on:arg - we need special handling
  19110. // for wrapping inline statements.
  19111. if (exp &&
  19112. exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  19113. !(dir.name === 'on' && arg)) {
  19114. dir.exp = processExpression(exp, context,
  19115. // slot args must be processed as function params
  19116. dir.name === 'slot');
  19117. }
  19118. if (arg && arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && !arg.isStatic) {
  19119. dir.arg = processExpression(arg, context);
  19120. }
  19121. }
  19122. }
  19123. }
  19124. };
  19125. // Important: since this function uses Node.js only dependencies, it should
  19126. // always be used with a leading !false check so that it can be
  19127. // tree-shaken from the browser build.
  19128. function processExpression(node, context,
  19129. // some expressions like v-slot props & v-for aliases should be parsed as
  19130. // function params
  19131. asParams = false,
  19132. // v-on handler values may contain multiple statements
  19133. asRawStatements = false, localVars = Object.create(context.identifiers)) {
  19134. if (!context.prefixIdentifiers || !node.content.trim()) {
  19135. return node;
  19136. }
  19137. const { inline, bindingMetadata } = context;
  19138. const rewriteIdentifier = (raw, parent, id) => {
  19139. const type = hasOwn(bindingMetadata, raw) && bindingMetadata[raw];
  19140. if (inline) {
  19141. // x = y
  19142. const isAssignmentLVal = parent && parent.type === 'AssignmentExpression' && parent.left === id;
  19143. // x++
  19144. const isUpdateArg = parent && parent.type === 'UpdateExpression' && parent.argument === id;
  19145. // ({ x } = y)
  19146. const isDestructureAssignment = parent && isInDestructureAssignment(parent, parentStack);
  19147. if (type === "setup-const" /* BindingTypes.SETUP_CONST */ ||
  19148. type === "setup-reactive-const" /* BindingTypes.SETUP_REACTIVE_CONST */ ||
  19149. localVars[raw]) {
  19150. return raw;
  19151. }
  19152. else if (type === "setup-ref" /* BindingTypes.SETUP_REF */) {
  19153. return `${raw}.value`;
  19154. }
  19155. else if (type === "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */) {
  19156. // const binding that may or may not be ref
  19157. // if it's not a ref, then assignments don't make sense -
  19158. // so we ignore the non-ref assignment case and generate code
  19159. // that assumes the value to be a ref for more efficiency
  19160. return isAssignmentLVal || isUpdateArg || isDestructureAssignment
  19161. ? `${raw}.value`
  19162. : `${context.helperString(UNREF)}(${raw})`;
  19163. }
  19164. else if (type === "setup-let" /* BindingTypes.SETUP_LET */) {
  19165. if (isAssignmentLVal) {
  19166. // let binding.
  19167. // this is a bit more tricky as we need to cover the case where
  19168. // let is a local non-ref value, and we need to replicate the
  19169. // right hand side value.
  19170. // x = y --> isRef(x) ? x.value = y : x = y
  19171. const { right: rVal, operator } = parent;
  19172. const rExp = rawExp.slice(rVal.start - 1, rVal.end - 1);
  19173. const rExpString = stringifyExpression(processExpression(createSimpleExpression(rExp, false), context, false, false, knownIds));
  19174. return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore\n` : ``} ? ${raw}.value ${operator} ${rExpString} : ${raw}`;
  19175. }
  19176. else if (isUpdateArg) {
  19177. // make id replace parent in the code range so the raw update operator
  19178. // is removed
  19179. id.start = parent.start;
  19180. id.end = parent.end;
  19181. const { prefix: isPrefix, operator } = parent;
  19182. const prefix = isPrefix ? operator : ``;
  19183. const postfix = isPrefix ? `` : operator;
  19184. // let binding.
  19185. // x++ --> isRef(a) ? a.value++ : a++
  19186. return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore\n` : ``} ? ${prefix}${raw}.value${postfix} : ${prefix}${raw}${postfix}`;
  19187. }
  19188. else if (isDestructureAssignment) {
  19189. // TODO
  19190. // let binding in a destructure assignment - it's very tricky to
  19191. // handle both possible cases here without altering the original
  19192. // structure of the code, so we just assume it's not a ref here
  19193. // for now
  19194. return raw;
  19195. }
  19196. else {
  19197. return `${context.helperString(UNREF)}(${raw})`;
  19198. }
  19199. }
  19200. else if (type === "props" /* BindingTypes.PROPS */) {
  19201. // use __props which is generated by compileScript so in ts mode
  19202. // it gets correct type
  19203. return genPropsAccessExp(raw);
  19204. }
  19205. else if (type === "props-aliased" /* BindingTypes.PROPS_ALIASED */) {
  19206. // prop with a different local alias (from defineProps() destructure)
  19207. return genPropsAccessExp(bindingMetadata.__propsAliases[raw]);
  19208. }
  19209. }
  19210. else {
  19211. if (type && type.startsWith('setup')) {
  19212. // setup bindings in non-inline mode
  19213. return `$setup.${raw}`;
  19214. }
  19215. else if (type === "props-aliased" /* BindingTypes.PROPS_ALIASED */) {
  19216. return `$props['${bindingMetadata.__propsAliases[raw]}']`;
  19217. }
  19218. else if (type) {
  19219. return `$${type}.${raw}`;
  19220. }
  19221. }
  19222. // fallback to ctx
  19223. return `_ctx.${raw}`;
  19224. };
  19225. // fast path if expression is a simple identifier.
  19226. const rawExp = node.content;
  19227. // bail constant on parens (function invocation) and dot (member access)
  19228. const bailConstant = rawExp.indexOf(`(`) > -1 || rawExp.indexOf('.') > 0;
  19229. if (isSimpleIdentifier(rawExp)) {
  19230. const isScopeVarReference = context.identifiers[rawExp];
  19231. const isAllowedGlobal = isGloballyWhitelisted(rawExp);
  19232. const isLiteral = isLiteralWhitelisted(rawExp);
  19233. if (!asParams && !isScopeVarReference && !isAllowedGlobal && !isLiteral) {
  19234. // const bindings exposed from setup can be skipped for patching but
  19235. // cannot be hoisted to module scope
  19236. if (bindingMetadata[node.content] === "setup-const" /* BindingTypes.SETUP_CONST */) {
  19237. node.constType = 1 /* ConstantTypes.CAN_SKIP_PATCH */;
  19238. }
  19239. node.content = rewriteIdentifier(rawExp);
  19240. }
  19241. else if (!isScopeVarReference) {
  19242. if (isLiteral) {
  19243. node.constType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  19244. }
  19245. else {
  19246. node.constType = 2 /* ConstantTypes.CAN_HOIST */;
  19247. }
  19248. }
  19249. return node;
  19250. }
  19251. let ast;
  19252. // exp needs to be parsed differently:
  19253. // 1. Multiple inline statements (v-on, with presence of `;`): parse as raw
  19254. // exp, but make sure to pad with spaces for consistent ranges
  19255. // 2. Expressions: wrap with parens (for e.g. object expressions)
  19256. // 3. Function arguments (v-for, v-slot): place in a function argument position
  19257. const source = asRawStatements
  19258. ? ` ${rawExp} `
  19259. : `(${rawExp})${asParams ? `=>{}` : ``}`;
  19260. try {
  19261. ast = parse_1$1(source, {
  19262. plugins: context.expressionPlugins
  19263. }).program;
  19264. }
  19265. catch (e) {
  19266. context.onError(createCompilerError(45 /* ErrorCodes.X_INVALID_EXPRESSION */, node.loc, undefined, e.message));
  19267. return node;
  19268. }
  19269. const ids = [];
  19270. const parentStack = [];
  19271. const knownIds = Object.create(context.identifiers);
  19272. walkIdentifiers(ast, (node, parent, _, isReferenced, isLocal) => {
  19273. if (isStaticPropertyKey(node, parent)) {
  19274. return;
  19275. }
  19276. const needPrefix = isReferenced && canPrefix(node);
  19277. if (needPrefix && !isLocal) {
  19278. if (isStaticProperty(parent) && parent.shorthand) {
  19279. node.prefix = `${node.name}: `;
  19280. }
  19281. node.name = rewriteIdentifier(node.name, parent, node);
  19282. ids.push(node);
  19283. }
  19284. else {
  19285. // The identifier is considered constant unless it's pointing to a
  19286. // local scope variable (a v-for alias, or a v-slot prop)
  19287. if (!(needPrefix && isLocal) && !bailConstant) {
  19288. node.isConstant = true;
  19289. }
  19290. // also generate sub-expressions for other identifiers for better
  19291. // source map support. (except for property keys which are static)
  19292. ids.push(node);
  19293. }
  19294. }, true, // invoke on ALL identifiers
  19295. parentStack, knownIds);
  19296. // We break up the compound expression into an array of strings and sub
  19297. // expressions (for identifiers that have been prefixed). In codegen, if
  19298. // an ExpressionNode has the `.children` property, it will be used instead of
  19299. // `.content`.
  19300. const children = [];
  19301. ids.sort((a, b) => a.start - b.start);
  19302. ids.forEach((id, i) => {
  19303. // range is offset by -1 due to the wrapping parens when parsed
  19304. const start = id.start - 1;
  19305. const end = id.end - 1;
  19306. const last = ids[i - 1];
  19307. const leadingText = rawExp.slice(last ? last.end - 1 : 0, start);
  19308. if (leadingText.length || id.prefix) {
  19309. children.push(leadingText + (id.prefix || ``));
  19310. }
  19311. const source = rawExp.slice(start, end);
  19312. children.push(createSimpleExpression(id.name, false, {
  19313. source,
  19314. start: advancePositionWithClone(node.loc.start, source, start),
  19315. end: advancePositionWithClone(node.loc.start, source, end)
  19316. }, id.isConstant ? 3 /* ConstantTypes.CAN_STRINGIFY */ : 0 /* ConstantTypes.NOT_CONSTANT */));
  19317. if (i === ids.length - 1 && end < rawExp.length) {
  19318. children.push(rawExp.slice(end));
  19319. }
  19320. });
  19321. let ret;
  19322. if (children.length) {
  19323. ret = createCompoundExpression(children, node.loc);
  19324. }
  19325. else {
  19326. ret = node;
  19327. ret.constType = bailConstant
  19328. ? 0 /* ConstantTypes.NOT_CONSTANT */
  19329. : 3 /* ConstantTypes.CAN_STRINGIFY */;
  19330. }
  19331. ret.identifiers = Object.keys(knownIds);
  19332. return ret;
  19333. }
  19334. function canPrefix(id) {
  19335. // skip whitelisted globals
  19336. if (isGloballyWhitelisted(id.name)) {
  19337. return false;
  19338. }
  19339. // special case for webpack compilation
  19340. if (id.name === 'require') {
  19341. return false;
  19342. }
  19343. return true;
  19344. }
  19345. function stringifyExpression(exp) {
  19346. if (isString$2(exp)) {
  19347. return exp;
  19348. }
  19349. else if (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  19350. return exp.content;
  19351. }
  19352. else {
  19353. return exp.children
  19354. .map(stringifyExpression)
  19355. .join('');
  19356. }
  19357. }
  19358. const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
  19359. return processIf(node, dir, context, (ifNode, branch, isRoot) => {
  19360. // #1587: We need to dynamically increment the key based on the current
  19361. // node's sibling nodes, since chained v-if/else branches are
  19362. // rendered at the same depth
  19363. const siblings = context.parent.children;
  19364. let i = siblings.indexOf(ifNode);
  19365. let key = 0;
  19366. while (i-- >= 0) {
  19367. const sibling = siblings[i];
  19368. if (sibling && sibling.type === 9 /* NodeTypes.IF */) {
  19369. key += sibling.branches.length;
  19370. }
  19371. }
  19372. // Exit callback. Complete the codegenNode when all children have been
  19373. // transformed.
  19374. return () => {
  19375. if (isRoot) {
  19376. ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
  19377. }
  19378. else {
  19379. // attach this branch's codegen node to the v-if root.
  19380. const parentCondition = getParentCondition(ifNode.codegenNode);
  19381. parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
  19382. }
  19383. };
  19384. });
  19385. });
  19386. // target-agnostic transform used for both Client and SSR
  19387. function processIf(node, dir, context, processCodegen) {
  19388. if (dir.name !== 'else' &&
  19389. (!dir.exp || !dir.exp.content.trim())) {
  19390. const loc = dir.exp ? dir.exp.loc : node.loc;
  19391. context.onError(createCompilerError(28 /* ErrorCodes.X_V_IF_NO_EXPRESSION */, dir.loc));
  19392. dir.exp = createSimpleExpression(`true`, false, loc);
  19393. }
  19394. if (context.prefixIdentifiers && dir.exp) {
  19395. // dir.exp can only be simple expression because vIf transform is applied
  19396. // before expression transform.
  19397. dir.exp = processExpression(dir.exp, context);
  19398. }
  19399. if (dir.name === 'if') {
  19400. const branch = createIfBranch(node, dir);
  19401. const ifNode = {
  19402. type: 9 /* NodeTypes.IF */,
  19403. loc: node.loc,
  19404. branches: [branch]
  19405. };
  19406. context.replaceNode(ifNode);
  19407. if (processCodegen) {
  19408. return processCodegen(ifNode, branch, true);
  19409. }
  19410. }
  19411. else {
  19412. // locate the adjacent v-if
  19413. const siblings = context.parent.children;
  19414. const comments = [];
  19415. let i = siblings.indexOf(node);
  19416. while (i-- >= -1) {
  19417. const sibling = siblings[i];
  19418. if (sibling && sibling.type === 3 /* NodeTypes.COMMENT */) {
  19419. context.removeNode(sibling);
  19420. comments.unshift(sibling);
  19421. continue;
  19422. }
  19423. if (sibling &&
  19424. sibling.type === 2 /* NodeTypes.TEXT */ &&
  19425. !sibling.content.trim().length) {
  19426. context.removeNode(sibling);
  19427. continue;
  19428. }
  19429. if (sibling && sibling.type === 9 /* NodeTypes.IF */) {
  19430. // Check if v-else was followed by v-else-if
  19431. if (dir.name === 'else-if' &&
  19432. sibling.branches[sibling.branches.length - 1].condition === undefined) {
  19433. context.onError(createCompilerError(30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  19434. }
  19435. // move the node to the if node's branches
  19436. context.removeNode();
  19437. const branch = createIfBranch(node, dir);
  19438. if (comments.length &&
  19439. // #3619 ignore comments if the v-if is direct child of <transition>
  19440. !(context.parent &&
  19441. context.parent.type === 1 /* NodeTypes.ELEMENT */ &&
  19442. isBuiltInType(context.parent.tag, 'transition'))) {
  19443. branch.children = [...comments, ...branch.children];
  19444. }
  19445. // check if user is forcing same key on different branches
  19446. {
  19447. const key = branch.userKey;
  19448. if (key) {
  19449. sibling.branches.forEach(({ userKey }) => {
  19450. if (isSameKey(userKey, key)) {
  19451. context.onError(createCompilerError(29 /* ErrorCodes.X_V_IF_SAME_KEY */, branch.userKey.loc));
  19452. }
  19453. });
  19454. }
  19455. }
  19456. sibling.branches.push(branch);
  19457. const onExit = processCodegen && processCodegen(sibling, branch, false);
  19458. // since the branch was removed, it will not be traversed.
  19459. // make sure to traverse here.
  19460. traverseNode(branch, context);
  19461. // call on exit
  19462. if (onExit)
  19463. onExit();
  19464. // make sure to reset currentNode after traversal to indicate this
  19465. // node has been removed.
  19466. context.currentNode = null;
  19467. }
  19468. else {
  19469. context.onError(createCompilerError(30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  19470. }
  19471. break;
  19472. }
  19473. }
  19474. }
  19475. function createIfBranch(node, dir) {
  19476. const isTemplateIf = node.tagType === 3 /* ElementTypes.TEMPLATE */;
  19477. return {
  19478. type: 10 /* NodeTypes.IF_BRANCH */,
  19479. loc: node.loc,
  19480. condition: dir.name === 'else' ? undefined : dir.exp,
  19481. children: isTemplateIf && !findDir(node, 'for') ? node.children : [node],
  19482. userKey: findProp(node, `key`),
  19483. isTemplateIf
  19484. };
  19485. }
  19486. function createCodegenNodeForBranch(branch, keyIndex, context) {
  19487. if (branch.condition) {
  19488. return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
  19489. // make sure to pass in asBlock: true so that the comment node call
  19490. // closes the current block.
  19491. createCallExpression(context.helper(CREATE_COMMENT), [
  19492. '"v-if"' ,
  19493. 'true'
  19494. ]));
  19495. }
  19496. else {
  19497. return createChildrenCodegenNode(branch, keyIndex, context);
  19498. }
  19499. }
  19500. function createChildrenCodegenNode(branch, keyIndex, context) {
  19501. const { helper } = context;
  19502. const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* ConstantTypes.CAN_HOIST */));
  19503. const { children } = branch;
  19504. const firstChild = children[0];
  19505. const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* NodeTypes.ELEMENT */;
  19506. if (needFragmentWrapper) {
  19507. if (children.length === 1 && firstChild.type === 11 /* NodeTypes.FOR */) {
  19508. // optimize away nested fragments when child is a ForNode
  19509. const vnodeCall = firstChild.codegenNode;
  19510. injectProp(vnodeCall, keyProperty, context);
  19511. return vnodeCall;
  19512. }
  19513. else {
  19514. let patchFlag = 64 /* PatchFlags.STABLE_FRAGMENT */;
  19515. let patchFlagText = PatchFlagNames[64 /* PatchFlags.STABLE_FRAGMENT */];
  19516. // check if the fragment actually contains a single valid child with
  19517. // the rest being comments
  19518. if (!branch.isTemplateIf &&
  19519. children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */).length === 1) {
  19520. patchFlag |= 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */;
  19521. patchFlagText += `, ${PatchFlagNames[2048 /* PatchFlags.DEV_ROOT_FRAGMENT */]}`;
  19522. }
  19523. return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, false, false /* isComponent */, branch.loc);
  19524. }
  19525. }
  19526. else {
  19527. const ret = firstChild.codegenNode;
  19528. const vnodeCall = getMemoedVNodeCall(ret);
  19529. // Change createVNode to createBlock.
  19530. if (vnodeCall.type === 13 /* NodeTypes.VNODE_CALL */) {
  19531. makeBlock(vnodeCall, context);
  19532. }
  19533. // inject branch key
  19534. injectProp(vnodeCall, keyProperty, context);
  19535. return ret;
  19536. }
  19537. }
  19538. function isSameKey(a, b) {
  19539. if (!a || a.type !== b.type) {
  19540. return false;
  19541. }
  19542. if (a.type === 6 /* NodeTypes.ATTRIBUTE */) {
  19543. if (a.value.content !== b.value.content) {
  19544. return false;
  19545. }
  19546. }
  19547. else {
  19548. // directive
  19549. const exp = a.exp;
  19550. const branchExp = b.exp;
  19551. if (exp.type !== branchExp.type) {
  19552. return false;
  19553. }
  19554. if (exp.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
  19555. exp.isStatic !== branchExp.isStatic ||
  19556. exp.content !== branchExp.content) {
  19557. return false;
  19558. }
  19559. }
  19560. return true;
  19561. }
  19562. function getParentCondition(node) {
  19563. while (true) {
  19564. if (node.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */) {
  19565. if (node.alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */) {
  19566. node = node.alternate;
  19567. }
  19568. else {
  19569. return node;
  19570. }
  19571. }
  19572. else if (node.type === 20 /* NodeTypes.JS_CACHE_EXPRESSION */) {
  19573. node = node.value;
  19574. }
  19575. }
  19576. }
  19577. const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
  19578. const { helper, removeHelper } = context;
  19579. return processFor(node, dir, context, forNode => {
  19580. // create the loop render function expression now, and add the
  19581. // iterator on exit after all children have been traversed
  19582. const renderExp = createCallExpression(helper(RENDER_LIST), [
  19583. forNode.source
  19584. ]);
  19585. const isTemplate = isTemplateNode(node);
  19586. const memo = findDir(node, 'memo');
  19587. const keyProp = findProp(node, `key`);
  19588. const keyExp = keyProp &&
  19589. (keyProp.type === 6 /* NodeTypes.ATTRIBUTE */
  19590. ? createSimpleExpression(keyProp.value.content, true)
  19591. : keyProp.exp);
  19592. const keyProperty = keyProp ? createObjectProperty(`key`, keyExp) : null;
  19593. if (isTemplate) {
  19594. // #2085 / #5288 process :key and v-memo expressions need to be
  19595. // processed on `<template v-for>`. In this case the node is discarded
  19596. // and never traversed so its binding expressions won't be processed
  19597. // by the normal transforms.
  19598. if (memo) {
  19599. memo.exp = processExpression(memo.exp, context);
  19600. }
  19601. if (keyProperty && keyProp.type !== 6 /* NodeTypes.ATTRIBUTE */) {
  19602. keyProperty.value = processExpression(keyProperty.value, context);
  19603. }
  19604. }
  19605. const isStableFragment = forNode.source.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  19606. forNode.source.constType > 0 /* ConstantTypes.NOT_CONSTANT */;
  19607. const fragmentFlag = isStableFragment
  19608. ? 64 /* PatchFlags.STABLE_FRAGMENT */
  19609. : keyProp
  19610. ? 128 /* PatchFlags.KEYED_FRAGMENT */
  19611. : 256 /* PatchFlags.UNKEYED_FRAGMENT */;
  19612. forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
  19613. (` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, false /* isComponent */, node.loc);
  19614. return () => {
  19615. // finish the codegen now that all children have been traversed
  19616. let childBlock;
  19617. const { children } = forNode;
  19618. // check <template v-for> key placement
  19619. if (isTemplate) {
  19620. node.children.some(c => {
  19621. if (c.type === 1 /* NodeTypes.ELEMENT */) {
  19622. const key = findProp(c, 'key');
  19623. if (key) {
  19624. context.onError(createCompilerError(33 /* ErrorCodes.X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
  19625. return true;
  19626. }
  19627. }
  19628. });
  19629. }
  19630. const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* NodeTypes.ELEMENT */;
  19631. const slotOutlet = isSlotOutlet(node)
  19632. ? node
  19633. : isTemplate &&
  19634. node.children.length === 1 &&
  19635. isSlotOutlet(node.children[0])
  19636. ? node.children[0] // api-extractor somehow fails to infer this
  19637. : null;
  19638. if (slotOutlet) {
  19639. // <slot v-for="..."> or <template v-for="..."><slot/></template>
  19640. childBlock = slotOutlet.codegenNode;
  19641. if (isTemplate && keyProperty) {
  19642. // <template v-for="..." :key="..."><slot/></template>
  19643. // we need to inject the key to the renderSlot() call.
  19644. // the props for renderSlot is passed as the 3rd argument.
  19645. injectProp(childBlock, keyProperty, context);
  19646. }
  19647. }
  19648. else if (needFragmentWrapper) {
  19649. // <template v-for="..."> with text or multi-elements
  19650. // should generate a fragment block for each loop
  19651. childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* PatchFlags.STABLE_FRAGMENT */ +
  19652. (` /* ${PatchFlagNames[64 /* PatchFlags.STABLE_FRAGMENT */]} */`
  19653. ), undefined, undefined, true, undefined, false /* isComponent */);
  19654. }
  19655. else {
  19656. // Normal element v-for. Directly use the child's codegenNode
  19657. // but mark it as a block.
  19658. childBlock = children[0]
  19659. .codegenNode;
  19660. if (isTemplate && keyProperty) {
  19661. injectProp(childBlock, keyProperty, context);
  19662. }
  19663. if (childBlock.isBlock !== !isStableFragment) {
  19664. if (childBlock.isBlock) {
  19665. // switch from block to vnode
  19666. removeHelper(OPEN_BLOCK);
  19667. removeHelper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
  19668. }
  19669. else {
  19670. // switch from vnode to block
  19671. removeHelper(getVNodeHelper(context.inSSR, childBlock.isComponent));
  19672. }
  19673. }
  19674. childBlock.isBlock = !isStableFragment;
  19675. if (childBlock.isBlock) {
  19676. helper(OPEN_BLOCK);
  19677. helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
  19678. }
  19679. else {
  19680. helper(getVNodeHelper(context.inSSR, childBlock.isComponent));
  19681. }
  19682. }
  19683. if (memo) {
  19684. const loop = createFunctionExpression(createForLoopParams(forNode.parseResult, [
  19685. createSimpleExpression(`_cached`)
  19686. ]));
  19687. loop.body = createBlockStatement([
  19688. createCompoundExpression([`const _memo = (`, memo.exp, `)`]),
  19689. createCompoundExpression([
  19690. `if (_cached`,
  19691. ...(keyExp ? [` && _cached.key === `, keyExp] : []),
  19692. ` && ${context.helperString(IS_MEMO_SAME)}(_cached, _memo)) return _cached`
  19693. ]),
  19694. createCompoundExpression([`const _item = `, childBlock]),
  19695. createSimpleExpression(`_item.memo = _memo`),
  19696. createSimpleExpression(`return _item`)
  19697. ]);
  19698. renderExp.arguments.push(loop, createSimpleExpression(`_cache`), createSimpleExpression(String(context.cached++)));
  19699. }
  19700. else {
  19701. renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
  19702. }
  19703. };
  19704. });
  19705. });
  19706. // target-agnostic transform used for both Client and SSR
  19707. function processFor(node, dir, context, processCodegen) {
  19708. if (!dir.exp) {
  19709. context.onError(createCompilerError(31 /* ErrorCodes.X_V_FOR_NO_EXPRESSION */, dir.loc));
  19710. return;
  19711. }
  19712. const parseResult = parseForExpression(
  19713. // can only be simple expression because vFor transform is applied
  19714. // before expression transform.
  19715. dir.exp, context);
  19716. if (!parseResult) {
  19717. context.onError(createCompilerError(32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
  19718. return;
  19719. }
  19720. const { addIdentifiers, removeIdentifiers, scopes } = context;
  19721. const { source, value, key, index } = parseResult;
  19722. const forNode = {
  19723. type: 11 /* NodeTypes.FOR */,
  19724. loc: dir.loc,
  19725. source,
  19726. valueAlias: value,
  19727. keyAlias: key,
  19728. objectIndexAlias: index,
  19729. parseResult,
  19730. children: isTemplateNode(node) ? node.children : [node]
  19731. };
  19732. context.replaceNode(forNode);
  19733. // bookkeeping
  19734. scopes.vFor++;
  19735. if (context.prefixIdentifiers) {
  19736. // scope management
  19737. // inject identifiers to context
  19738. value && addIdentifiers(value);
  19739. key && addIdentifiers(key);
  19740. index && addIdentifiers(index);
  19741. }
  19742. const onExit = processCodegen && processCodegen(forNode);
  19743. return () => {
  19744. scopes.vFor--;
  19745. if (context.prefixIdentifiers) {
  19746. value && removeIdentifiers(value);
  19747. key && removeIdentifiers(key);
  19748. index && removeIdentifiers(index);
  19749. }
  19750. if (onExit)
  19751. onExit();
  19752. };
  19753. }
  19754. const forAliasRE$1 = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
  19755. // This regex doesn't cover the case if key or index aliases have destructuring,
  19756. // but those do not make sense in the first place, so this works in practice.
  19757. const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
  19758. const stripParensRE = /^\(|\)$/g;
  19759. function parseForExpression(input, context) {
  19760. const loc = input.loc;
  19761. const exp = input.content;
  19762. const inMatch = exp.match(forAliasRE$1);
  19763. if (!inMatch)
  19764. return;
  19765. const [, LHS, RHS] = inMatch;
  19766. const result = {
  19767. source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
  19768. value: undefined,
  19769. key: undefined,
  19770. index: undefined
  19771. };
  19772. if (context.prefixIdentifiers) {
  19773. result.source = processExpression(result.source, context);
  19774. }
  19775. let valueContent = LHS.trim().replace(stripParensRE, '').trim();
  19776. const trimmedOffset = LHS.indexOf(valueContent);
  19777. const iteratorMatch = valueContent.match(forIteratorRE);
  19778. if (iteratorMatch) {
  19779. valueContent = valueContent.replace(forIteratorRE, '').trim();
  19780. const keyContent = iteratorMatch[1].trim();
  19781. let keyOffset;
  19782. if (keyContent) {
  19783. keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
  19784. result.key = createAliasExpression(loc, keyContent, keyOffset);
  19785. if (context.prefixIdentifiers) {
  19786. result.key = processExpression(result.key, context, true);
  19787. }
  19788. }
  19789. if (iteratorMatch[2]) {
  19790. const indexContent = iteratorMatch[2].trim();
  19791. if (indexContent) {
  19792. result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
  19793. ? keyOffset + keyContent.length
  19794. : trimmedOffset + valueContent.length));
  19795. if (context.prefixIdentifiers) {
  19796. result.index = processExpression(result.index, context, true);
  19797. }
  19798. }
  19799. }
  19800. }
  19801. if (valueContent) {
  19802. result.value = createAliasExpression(loc, valueContent, trimmedOffset);
  19803. if (context.prefixIdentifiers) {
  19804. result.value = processExpression(result.value, context, true);
  19805. }
  19806. }
  19807. return result;
  19808. }
  19809. function createAliasExpression(range, content, offset) {
  19810. return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
  19811. }
  19812. function createForLoopParams({ value, key, index }, memoArgs = []) {
  19813. return createParamsList([value, key, index, ...memoArgs]);
  19814. }
  19815. function createParamsList(args) {
  19816. let i = args.length;
  19817. while (i--) {
  19818. if (args[i])
  19819. break;
  19820. }
  19821. return args
  19822. .slice(0, i + 1)
  19823. .map((arg, i) => arg || createSimpleExpression(`_`.repeat(i + 1), false));
  19824. }
  19825. const defaultFallback = createSimpleExpression(`undefined`, false);
  19826. // A NodeTransform that:
  19827. // 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
  19828. // by transformExpression. This is only applied in non-browser builds with
  19829. // { prefixIdentifiers: true }.
  19830. // 2. Track v-slot depths so that we know a slot is inside another slot.
  19831. // Note the exit callback is executed before buildSlots() on the same node,
  19832. // so only nested slots see positive numbers.
  19833. const trackSlotScopes = (node, context) => {
  19834. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  19835. (node.tagType === 1 /* ElementTypes.COMPONENT */ ||
  19836. node.tagType === 3 /* ElementTypes.TEMPLATE */)) {
  19837. // We are only checking non-empty v-slot here
  19838. // since we only care about slots that introduce scope variables.
  19839. const vSlot = findDir(node, 'slot');
  19840. if (vSlot) {
  19841. const slotProps = vSlot.exp;
  19842. if (context.prefixIdentifiers) {
  19843. slotProps && context.addIdentifiers(slotProps);
  19844. }
  19845. context.scopes.vSlot++;
  19846. return () => {
  19847. if (context.prefixIdentifiers) {
  19848. slotProps && context.removeIdentifiers(slotProps);
  19849. }
  19850. context.scopes.vSlot--;
  19851. };
  19852. }
  19853. }
  19854. };
  19855. // A NodeTransform that tracks scope identifiers for scoped slots with v-for.
  19856. // This transform is only applied in non-browser builds with { prefixIdentifiers: true }
  19857. const trackVForSlotScopes = (node, context) => {
  19858. let vFor;
  19859. if (isTemplateNode(node) &&
  19860. node.props.some(isVSlot) &&
  19861. (vFor = findDir(node, 'for'))) {
  19862. const result = (vFor.parseResult = parseForExpression(vFor.exp, context));
  19863. if (result) {
  19864. const { value, key, index } = result;
  19865. const { addIdentifiers, removeIdentifiers } = context;
  19866. value && addIdentifiers(value);
  19867. key && addIdentifiers(key);
  19868. index && addIdentifiers(index);
  19869. return () => {
  19870. value && removeIdentifiers(value);
  19871. key && removeIdentifiers(key);
  19872. index && removeIdentifiers(index);
  19873. };
  19874. }
  19875. }
  19876. };
  19877. const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
  19878. // Instead of being a DirectiveTransform, v-slot processing is called during
  19879. // transformElement to build the slots object for a component.
  19880. function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
  19881. context.helper(WITH_CTX);
  19882. const { children, loc } = node;
  19883. const slotsProperties = [];
  19884. const dynamicSlots = [];
  19885. // If the slot is inside a v-for or another v-slot, force it to be dynamic
  19886. // since it likely uses a scope variable.
  19887. let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
  19888. // with `prefixIdentifiers: true`, this can be further optimized to make
  19889. // it dynamic only when the slot actually uses the scope variables.
  19890. if (!context.ssr && context.prefixIdentifiers) {
  19891. hasDynamicSlots = hasScopeRef(node, context.identifiers);
  19892. }
  19893. // 1. Check for slot with slotProps on component itself.
  19894. // <Comp v-slot="{ prop }"/>
  19895. const onComponentSlot = findDir(node, 'slot', true);
  19896. if (onComponentSlot) {
  19897. const { arg, exp } = onComponentSlot;
  19898. if (arg && !isStaticExp(arg)) {
  19899. hasDynamicSlots = true;
  19900. }
  19901. slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
  19902. }
  19903. // 2. Iterate through children and check for template slots
  19904. // <template v-slot:foo="{ prop }">
  19905. let hasTemplateSlots = false;
  19906. let hasNamedDefaultSlot = false;
  19907. const implicitDefaultChildren = [];
  19908. const seenSlotNames = new Set();
  19909. let conditionalBranchIndex = 0;
  19910. for (let i = 0; i < children.length; i++) {
  19911. const slotElement = children[i];
  19912. let slotDir;
  19913. if (!isTemplateNode(slotElement) ||
  19914. !(slotDir = findDir(slotElement, 'slot', true))) {
  19915. // not a <template v-slot>, skip.
  19916. if (slotElement.type !== 3 /* NodeTypes.COMMENT */) {
  19917. implicitDefaultChildren.push(slotElement);
  19918. }
  19919. continue;
  19920. }
  19921. if (onComponentSlot) {
  19922. // already has on-component slot - this is incorrect usage.
  19923. context.onError(createCompilerError(37 /* ErrorCodes.X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
  19924. break;
  19925. }
  19926. hasTemplateSlots = true;
  19927. const { children: slotChildren, loc: slotLoc } = slotElement;
  19928. const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
  19929. // check if name is dynamic.
  19930. let staticSlotName;
  19931. if (isStaticExp(slotName)) {
  19932. staticSlotName = slotName ? slotName.content : `default`;
  19933. }
  19934. else {
  19935. hasDynamicSlots = true;
  19936. }
  19937. const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
  19938. // check if this slot is conditional (v-if/v-for)
  19939. let vIf;
  19940. let vElse;
  19941. let vFor;
  19942. if ((vIf = findDir(slotElement, 'if'))) {
  19943. hasDynamicSlots = true;
  19944. dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++), defaultFallback));
  19945. }
  19946. else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
  19947. // find adjacent v-if
  19948. let j = i;
  19949. let prev;
  19950. while (j--) {
  19951. prev = children[j];
  19952. if (prev.type !== 3 /* NodeTypes.COMMENT */) {
  19953. break;
  19954. }
  19955. }
  19956. if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
  19957. // remove node
  19958. children.splice(i, 1);
  19959. i--;
  19960. // attach this slot to previous conditional
  19961. let conditional = dynamicSlots[dynamicSlots.length - 1];
  19962. while (conditional.alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */) {
  19963. conditional = conditional.alternate;
  19964. }
  19965. conditional.alternate = vElse.exp
  19966. ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++), defaultFallback)
  19967. : buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++);
  19968. }
  19969. else {
  19970. context.onError(createCompilerError(30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
  19971. }
  19972. }
  19973. else if ((vFor = findDir(slotElement, 'for'))) {
  19974. hasDynamicSlots = true;
  19975. const parseResult = vFor.parseResult ||
  19976. parseForExpression(vFor.exp, context);
  19977. if (parseResult) {
  19978. // Render the dynamic slots as an array and add it to the createSlot()
  19979. // args. The runtime knows how to handle it appropriately.
  19980. dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
  19981. parseResult.source,
  19982. createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
  19983. ]));
  19984. }
  19985. else {
  19986. context.onError(createCompilerError(32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
  19987. }
  19988. }
  19989. else {
  19990. // check duplicate static names
  19991. if (staticSlotName) {
  19992. if (seenSlotNames.has(staticSlotName)) {
  19993. context.onError(createCompilerError(38 /* ErrorCodes.X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
  19994. continue;
  19995. }
  19996. seenSlotNames.add(staticSlotName);
  19997. if (staticSlotName === 'default') {
  19998. hasNamedDefaultSlot = true;
  19999. }
  20000. }
  20001. slotsProperties.push(createObjectProperty(slotName, slotFunction));
  20002. }
  20003. }
  20004. if (!onComponentSlot) {
  20005. const buildDefaultSlotProperty = (props, children) => {
  20006. const fn = buildSlotFn(props, children, loc);
  20007. return createObjectProperty(`default`, fn);
  20008. };
  20009. if (!hasTemplateSlots) {
  20010. // implicit default slot (on component)
  20011. slotsProperties.push(buildDefaultSlotProperty(undefined, children));
  20012. }
  20013. else if (implicitDefaultChildren.length &&
  20014. // #3766
  20015. // with whitespace: 'preserve', whitespaces between slots will end up in
  20016. // implicitDefaultChildren. Ignore if all implicit children are whitespaces.
  20017. implicitDefaultChildren.some(node => isNonWhitespaceContent(node))) {
  20018. // implicit default slot (mixed with named slots)
  20019. if (hasNamedDefaultSlot) {
  20020. context.onError(createCompilerError(39 /* ErrorCodes.X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
  20021. }
  20022. else {
  20023. slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
  20024. }
  20025. }
  20026. }
  20027. const slotFlag = hasDynamicSlots
  20028. ? 2 /* SlotFlags.DYNAMIC */
  20029. : hasForwardedSlots(node.children)
  20030. ? 3 /* SlotFlags.FORWARDED */
  20031. : 1 /* SlotFlags.STABLE */;
  20032. let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
  20033. // 2 = compiled but dynamic = can skip normalization, but must run diff
  20034. // 1 = compiled and static = can skip normalization AND diff as optimized
  20035. createSimpleExpression(slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
  20036. if (dynamicSlots.length) {
  20037. slots = createCallExpression(context.helper(CREATE_SLOTS), [
  20038. slots,
  20039. createArrayExpression(dynamicSlots)
  20040. ]);
  20041. }
  20042. return {
  20043. slots,
  20044. hasDynamicSlots
  20045. };
  20046. }
  20047. function buildDynamicSlot(name, fn, index) {
  20048. const props = [
  20049. createObjectProperty(`name`, name),
  20050. createObjectProperty(`fn`, fn)
  20051. ];
  20052. if (index != null) {
  20053. props.push(createObjectProperty(`key`, createSimpleExpression(String(index), true)));
  20054. }
  20055. return createObjectExpression(props);
  20056. }
  20057. function hasForwardedSlots(children) {
  20058. for (let i = 0; i < children.length; i++) {
  20059. const child = children[i];
  20060. switch (child.type) {
  20061. case 1 /* NodeTypes.ELEMENT */:
  20062. if (child.tagType === 2 /* ElementTypes.SLOT */ ||
  20063. hasForwardedSlots(child.children)) {
  20064. return true;
  20065. }
  20066. break;
  20067. case 9 /* NodeTypes.IF */:
  20068. if (hasForwardedSlots(child.branches))
  20069. return true;
  20070. break;
  20071. case 10 /* NodeTypes.IF_BRANCH */:
  20072. case 11 /* NodeTypes.FOR */:
  20073. if (hasForwardedSlots(child.children))
  20074. return true;
  20075. break;
  20076. }
  20077. }
  20078. return false;
  20079. }
  20080. function isNonWhitespaceContent(node) {
  20081. if (node.type !== 2 /* NodeTypes.TEXT */ && node.type !== 12 /* NodeTypes.TEXT_CALL */)
  20082. return true;
  20083. return node.type === 2 /* NodeTypes.TEXT */
  20084. ? !!node.content.trim()
  20085. : isNonWhitespaceContent(node.content);
  20086. }
  20087. // some directive transforms (e.g. v-model) may return a symbol for runtime
  20088. // import, which should be used instead of a resolveDirective call.
  20089. const directiveImportMap = new WeakMap();
  20090. // generate a JavaScript AST for this element's codegen
  20091. const transformElement = (node, context) => {
  20092. // perform the work on exit, after all child expressions have been
  20093. // processed and merged.
  20094. return function postTransformElement() {
  20095. node = context.currentNode;
  20096. if (!(node.type === 1 /* NodeTypes.ELEMENT */ &&
  20097. (node.tagType === 0 /* ElementTypes.ELEMENT */ ||
  20098. node.tagType === 1 /* ElementTypes.COMPONENT */))) {
  20099. return;
  20100. }
  20101. const { tag, props } = node;
  20102. const isComponent = node.tagType === 1 /* ElementTypes.COMPONENT */;
  20103. // The goal of the transform is to create a codegenNode implementing the
  20104. // VNodeCall interface.
  20105. let vnodeTag = isComponent
  20106. ? resolveComponentType(node, context)
  20107. : `"${tag}"`;
  20108. const isDynamicComponent = isObject$2(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
  20109. let vnodeProps;
  20110. let vnodeChildren;
  20111. let vnodePatchFlag;
  20112. let patchFlag = 0;
  20113. let vnodeDynamicProps;
  20114. let dynamicPropNames;
  20115. let vnodeDirectives;
  20116. let shouldUseBlock =
  20117. // dynamic component may resolve to plain elements
  20118. isDynamicComponent ||
  20119. vnodeTag === TELEPORT ||
  20120. vnodeTag === SUSPENSE ||
  20121. (!isComponent &&
  20122. // <svg> and <foreignObject> must be forced into blocks so that block
  20123. // updates inside get proper isSVG flag at runtime. (#639, #643)
  20124. // This is technically web-specific, but splitting the logic out of core
  20125. // leads to too much unnecessary complexity.
  20126. (tag === 'svg' || tag === 'foreignObject'));
  20127. // props
  20128. if (props.length > 0) {
  20129. const propsBuildResult = buildProps(node, context, undefined, isComponent, isDynamicComponent);
  20130. vnodeProps = propsBuildResult.props;
  20131. patchFlag = propsBuildResult.patchFlag;
  20132. dynamicPropNames = propsBuildResult.dynamicPropNames;
  20133. const directives = propsBuildResult.directives;
  20134. vnodeDirectives =
  20135. directives && directives.length
  20136. ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
  20137. : undefined;
  20138. if (propsBuildResult.shouldUseBlock) {
  20139. shouldUseBlock = true;
  20140. }
  20141. }
  20142. // children
  20143. if (node.children.length > 0) {
  20144. if (vnodeTag === KEEP_ALIVE) {
  20145. // Although a built-in component, we compile KeepAlive with raw children
  20146. // instead of slot functions so that it can be used inside Transition
  20147. // or other Transition-wrapping HOCs.
  20148. // To ensure correct updates with block optimizations, we need to:
  20149. // 1. Force keep-alive into a block. This avoids its children being
  20150. // collected by a parent block.
  20151. shouldUseBlock = true;
  20152. // 2. Force keep-alive to always be updated, since it uses raw children.
  20153. patchFlag |= 1024 /* PatchFlags.DYNAMIC_SLOTS */;
  20154. if (node.children.length > 1) {
  20155. context.onError(createCompilerError(46 /* ErrorCodes.X_KEEP_ALIVE_INVALID_CHILDREN */, {
  20156. start: node.children[0].loc.start,
  20157. end: node.children[node.children.length - 1].loc.end,
  20158. source: ''
  20159. }));
  20160. }
  20161. }
  20162. const shouldBuildAsSlots = isComponent &&
  20163. // Teleport is not a real component and has dedicated runtime handling
  20164. vnodeTag !== TELEPORT &&
  20165. // explained above.
  20166. vnodeTag !== KEEP_ALIVE;
  20167. if (shouldBuildAsSlots) {
  20168. const { slots, hasDynamicSlots } = buildSlots(node, context);
  20169. vnodeChildren = slots;
  20170. if (hasDynamicSlots) {
  20171. patchFlag |= 1024 /* PatchFlags.DYNAMIC_SLOTS */;
  20172. }
  20173. }
  20174. else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
  20175. const child = node.children[0];
  20176. const type = child.type;
  20177. // check for dynamic text children
  20178. const hasDynamicTextChild = type === 5 /* NodeTypes.INTERPOLATION */ ||
  20179. type === 8 /* NodeTypes.COMPOUND_EXPRESSION */;
  20180. if (hasDynamicTextChild &&
  20181. getConstantType(child, context) === 0 /* ConstantTypes.NOT_CONSTANT */) {
  20182. patchFlag |= 1 /* PatchFlags.TEXT */;
  20183. }
  20184. // pass directly if the only child is a text node
  20185. // (plain / interpolation / expression)
  20186. if (hasDynamicTextChild || type === 2 /* NodeTypes.TEXT */) {
  20187. vnodeChildren = child;
  20188. }
  20189. else {
  20190. vnodeChildren = node.children;
  20191. }
  20192. }
  20193. else {
  20194. vnodeChildren = node.children;
  20195. }
  20196. }
  20197. // patchFlag & dynamicPropNames
  20198. if (patchFlag !== 0) {
  20199. {
  20200. if (patchFlag < 0) {
  20201. // special flags (negative and mutually exclusive)
  20202. vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
  20203. }
  20204. else {
  20205. // bitwise flags
  20206. const flagNames = Object.keys(PatchFlagNames)
  20207. .map(Number)
  20208. .filter(n => n > 0 && patchFlag & n)
  20209. .map(n => PatchFlagNames[n])
  20210. .join(`, `);
  20211. vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
  20212. }
  20213. }
  20214. if (dynamicPropNames && dynamicPropNames.length) {
  20215. vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
  20216. }
  20217. }
  20218. node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, isComponent, node.loc);
  20219. };
  20220. };
  20221. function resolveComponentType(node, context, ssr = false) {
  20222. let { tag } = node;
  20223. // 1. dynamic component
  20224. const isExplicitDynamic = isComponentTag(tag);
  20225. const isProp = findProp(node, 'is');
  20226. if (isProp) {
  20227. if (isExplicitDynamic ||
  20228. (false )) {
  20229. const exp = isProp.type === 6 /* NodeTypes.ATTRIBUTE */
  20230. ? isProp.value && createSimpleExpression(isProp.value.content, true)
  20231. : isProp.exp;
  20232. if (exp) {
  20233. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  20234. exp
  20235. ]);
  20236. }
  20237. }
  20238. else if (isProp.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  20239. isProp.value.content.startsWith('vue:')) {
  20240. // <button is="vue:xxx">
  20241. // if not <component>, only is value that starts with "vue:" will be
  20242. // treated as component by the parse phase and reach here, unless it's
  20243. // compat mode where all is values are considered components
  20244. tag = isProp.value.content.slice(4);
  20245. }
  20246. }
  20247. // 1.5 v-is (TODO: Deprecate)
  20248. const isDir = !isExplicitDynamic && findDir(node, 'is');
  20249. if (isDir && isDir.exp) {
  20250. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  20251. isDir.exp
  20252. ]);
  20253. }
  20254. // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
  20255. const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
  20256. if (builtIn) {
  20257. // built-ins are simply fallthroughs / have special handling during ssr
  20258. // so we don't need to import their runtime equivalents
  20259. if (!ssr)
  20260. context.helper(builtIn);
  20261. return builtIn;
  20262. }
  20263. // 3. user component (from setup bindings)
  20264. // this is skipped in browser build since browser builds do not perform
  20265. // binding analysis.
  20266. {
  20267. const fromSetup = resolveSetupReference(tag, context);
  20268. if (fromSetup) {
  20269. return fromSetup;
  20270. }
  20271. const dotIndex = tag.indexOf('.');
  20272. if (dotIndex > 0) {
  20273. const ns = resolveSetupReference(tag.slice(0, dotIndex), context);
  20274. if (ns) {
  20275. return ns + tag.slice(dotIndex);
  20276. }
  20277. }
  20278. }
  20279. // 4. Self referencing component (inferred from filename)
  20280. if (context.selfName &&
  20281. capitalize$1(camelize(tag)) === context.selfName) {
  20282. context.helper(RESOLVE_COMPONENT);
  20283. // codegen.ts has special check for __self postfix when generating
  20284. // component imports, which will pass additional `maybeSelfReference` flag
  20285. // to `resolveComponent`.
  20286. context.components.add(tag + `__self`);
  20287. return toValidAssetId(tag, `component`);
  20288. }
  20289. // 5. user component (resolve)
  20290. context.helper(RESOLVE_COMPONENT);
  20291. context.components.add(tag);
  20292. return toValidAssetId(tag, `component`);
  20293. }
  20294. function resolveSetupReference(name, context) {
  20295. const bindings = context.bindingMetadata;
  20296. if (!bindings || bindings.__isScriptSetup === false) {
  20297. return;
  20298. }
  20299. const camelName = camelize(name);
  20300. const PascalName = capitalize$1(camelName);
  20301. const checkType = (type) => {
  20302. if (bindings[name] === type) {
  20303. return name;
  20304. }
  20305. if (bindings[camelName] === type) {
  20306. return camelName;
  20307. }
  20308. if (bindings[PascalName] === type) {
  20309. return PascalName;
  20310. }
  20311. };
  20312. const fromConst = checkType("setup-const" /* BindingTypes.SETUP_CONST */) ||
  20313. checkType("setup-reactive-const" /* BindingTypes.SETUP_REACTIVE_CONST */);
  20314. if (fromConst) {
  20315. return context.inline
  20316. ? // in inline mode, const setup bindings (e.g. imports) can be used as-is
  20317. fromConst
  20318. : `$setup[${JSON.stringify(fromConst)}]`;
  20319. }
  20320. const fromMaybeRef = checkType("setup-let" /* BindingTypes.SETUP_LET */) ||
  20321. checkType("setup-ref" /* BindingTypes.SETUP_REF */) ||
  20322. checkType("setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */);
  20323. if (fromMaybeRef) {
  20324. return context.inline
  20325. ? // setup scope bindings that may be refs need to be unrefed
  20326. `${context.helperString(UNREF)}(${fromMaybeRef})`
  20327. : `$setup[${JSON.stringify(fromMaybeRef)}]`;
  20328. }
  20329. }
  20330. function buildProps(node, context, props = node.props, isComponent, isDynamicComponent, ssr = false) {
  20331. const { tag, loc: elementLoc, children } = node;
  20332. let properties = [];
  20333. const mergeArgs = [];
  20334. const runtimeDirectives = [];
  20335. const hasChildren = children.length > 0;
  20336. let shouldUseBlock = false;
  20337. // patchFlag analysis
  20338. let patchFlag = 0;
  20339. let hasRef = false;
  20340. let hasClassBinding = false;
  20341. let hasStyleBinding = false;
  20342. let hasHydrationEventBinding = false;
  20343. let hasDynamicKeys = false;
  20344. let hasVnodeHook = false;
  20345. const dynamicPropNames = [];
  20346. const pushMergeArg = (arg) => {
  20347. if (properties.length) {
  20348. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  20349. properties = [];
  20350. }
  20351. if (arg)
  20352. mergeArgs.push(arg);
  20353. };
  20354. const analyzePatchFlag = ({ key, value }) => {
  20355. if (isStaticExp(key)) {
  20356. const name = key.content;
  20357. const isEventHandler = isOn(name);
  20358. if (isEventHandler &&
  20359. (!isComponent || isDynamicComponent) &&
  20360. // omit the flag for click handlers because hydration gives click
  20361. // dedicated fast path.
  20362. name.toLowerCase() !== 'onclick' &&
  20363. // omit v-model handlers
  20364. name !== 'onUpdate:modelValue' &&
  20365. // omit onVnodeXXX hooks
  20366. !isReservedProp(name)) {
  20367. hasHydrationEventBinding = true;
  20368. }
  20369. if (isEventHandler && isReservedProp(name)) {
  20370. hasVnodeHook = true;
  20371. }
  20372. if (value.type === 20 /* NodeTypes.JS_CACHE_EXPRESSION */ ||
  20373. ((value.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
  20374. value.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) &&
  20375. getConstantType(value, context) > 0)) {
  20376. // skip if the prop is a cached handler or has constant value
  20377. return;
  20378. }
  20379. if (name === 'ref') {
  20380. hasRef = true;
  20381. }
  20382. else if (name === 'class') {
  20383. hasClassBinding = true;
  20384. }
  20385. else if (name === 'style') {
  20386. hasStyleBinding = true;
  20387. }
  20388. else if (name !== 'key' && !dynamicPropNames.includes(name)) {
  20389. dynamicPropNames.push(name);
  20390. }
  20391. // treat the dynamic class and style binding of the component as dynamic props
  20392. if (isComponent &&
  20393. (name === 'class' || name === 'style') &&
  20394. !dynamicPropNames.includes(name)) {
  20395. dynamicPropNames.push(name);
  20396. }
  20397. }
  20398. else {
  20399. hasDynamicKeys = true;
  20400. }
  20401. };
  20402. for (let i = 0; i < props.length; i++) {
  20403. // static attribute
  20404. const prop = props[i];
  20405. if (prop.type === 6 /* NodeTypes.ATTRIBUTE */) {
  20406. const { loc, name, value } = prop;
  20407. let isStatic = true;
  20408. if (name === 'ref') {
  20409. hasRef = true;
  20410. if (context.scopes.vFor > 0) {
  20411. properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
  20412. }
  20413. // in inline mode there is no setupState object, so we can't use string
  20414. // keys to set the ref. Instead, we need to transform it to pass the
  20415. // actual ref instead.
  20416. if (value && context.inline) {
  20417. const binding = context.bindingMetadata[value.content];
  20418. if (binding === "setup-let" /* BindingTypes.SETUP_LET */ ||
  20419. binding === "setup-ref" /* BindingTypes.SETUP_REF */ ||
  20420. binding === "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */) {
  20421. isStatic = false;
  20422. properties.push(createObjectProperty(createSimpleExpression('ref_key', true), createSimpleExpression(value.content, true, value.loc)));
  20423. }
  20424. }
  20425. }
  20426. // skip is on <component>, or is="vue:xxx"
  20427. if (name === 'is' &&
  20428. (isComponentTag(tag) ||
  20429. (value && value.content.startsWith('vue:')) ||
  20430. (false ))) {
  20431. continue;
  20432. }
  20433. properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', isStatic, value ? value.loc : loc)));
  20434. }
  20435. else {
  20436. // directives
  20437. const { name, arg, exp, loc } = prop;
  20438. const isVBind = name === 'bind';
  20439. const isVOn = name === 'on';
  20440. // skip v-slot - it is handled by its dedicated transform.
  20441. if (name === 'slot') {
  20442. if (!isComponent) {
  20443. context.onError(createCompilerError(40 /* ErrorCodes.X_V_SLOT_MISPLACED */, loc));
  20444. }
  20445. continue;
  20446. }
  20447. // skip v-once/v-memo - they are handled by dedicated transforms.
  20448. if (name === 'once' || name === 'memo') {
  20449. continue;
  20450. }
  20451. // skip v-is and :is on <component>
  20452. if (name === 'is' ||
  20453. (isVBind &&
  20454. isStaticArgOf(arg, 'is') &&
  20455. (isComponentTag(tag) ||
  20456. (false )))) {
  20457. continue;
  20458. }
  20459. // skip v-on in SSR compilation
  20460. if (isVOn && ssr) {
  20461. continue;
  20462. }
  20463. if (
  20464. // #938: elements with dynamic keys should be forced into blocks
  20465. (isVBind && isStaticArgOf(arg, 'key')) ||
  20466. // inline before-update hooks need to force block so that it is invoked
  20467. // before children
  20468. (isVOn && hasChildren && isStaticArgOf(arg, 'vue:before-update'))) {
  20469. shouldUseBlock = true;
  20470. }
  20471. if (isVBind && isStaticArgOf(arg, 'ref') && context.scopes.vFor > 0) {
  20472. properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
  20473. }
  20474. // special case for v-bind and v-on with no argument
  20475. if (!arg && (isVBind || isVOn)) {
  20476. hasDynamicKeys = true;
  20477. if (exp) {
  20478. if (isVBind) {
  20479. // have to merge early for compat build check
  20480. pushMergeArg();
  20481. mergeArgs.push(exp);
  20482. }
  20483. else {
  20484. // v-on="obj" -> toHandlers(obj)
  20485. pushMergeArg({
  20486. type: 14 /* NodeTypes.JS_CALL_EXPRESSION */,
  20487. loc,
  20488. callee: context.helper(TO_HANDLERS),
  20489. arguments: isComponent ? [exp] : [exp, `true`]
  20490. });
  20491. }
  20492. }
  20493. else {
  20494. context.onError(createCompilerError(isVBind
  20495. ? 34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */
  20496. : 35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */, loc));
  20497. }
  20498. continue;
  20499. }
  20500. const directiveTransform = context.directiveTransforms[name];
  20501. if (directiveTransform) {
  20502. // has built-in directive transform.
  20503. const { props, needRuntime } = directiveTransform(prop, node, context);
  20504. !ssr && props.forEach(analyzePatchFlag);
  20505. if (isVOn && arg && !isStaticExp(arg)) {
  20506. pushMergeArg(createObjectExpression(props, elementLoc));
  20507. }
  20508. else {
  20509. properties.push(...props);
  20510. }
  20511. if (needRuntime) {
  20512. runtimeDirectives.push(prop);
  20513. if (isSymbol$1(needRuntime)) {
  20514. directiveImportMap.set(prop, needRuntime);
  20515. }
  20516. }
  20517. }
  20518. else if (!isBuiltInDirective(name)) {
  20519. // no built-in transform, this is a user custom directive.
  20520. runtimeDirectives.push(prop);
  20521. // custom dirs may use beforeUpdate so they need to force blocks
  20522. // to ensure before-update gets called before children update
  20523. if (hasChildren) {
  20524. shouldUseBlock = true;
  20525. }
  20526. }
  20527. }
  20528. }
  20529. let propsExpression = undefined;
  20530. // has v-bind="object" or v-on="object", wrap with mergeProps
  20531. if (mergeArgs.length) {
  20532. // close up any not-yet-merged props
  20533. pushMergeArg();
  20534. if (mergeArgs.length > 1) {
  20535. propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
  20536. }
  20537. else {
  20538. // single v-bind with nothing else - no need for a mergeProps call
  20539. propsExpression = mergeArgs[0];
  20540. }
  20541. }
  20542. else if (properties.length) {
  20543. propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
  20544. }
  20545. // patchFlag analysis
  20546. if (hasDynamicKeys) {
  20547. patchFlag |= 16 /* PatchFlags.FULL_PROPS */;
  20548. }
  20549. else {
  20550. if (hasClassBinding && !isComponent) {
  20551. patchFlag |= 2 /* PatchFlags.CLASS */;
  20552. }
  20553. if (hasStyleBinding && !isComponent) {
  20554. patchFlag |= 4 /* PatchFlags.STYLE */;
  20555. }
  20556. if (dynamicPropNames.length) {
  20557. patchFlag |= 8 /* PatchFlags.PROPS */;
  20558. }
  20559. if (hasHydrationEventBinding) {
  20560. patchFlag |= 32 /* PatchFlags.HYDRATE_EVENTS */;
  20561. }
  20562. }
  20563. if (!shouldUseBlock &&
  20564. (patchFlag === 0 || patchFlag === 32 /* PatchFlags.HYDRATE_EVENTS */) &&
  20565. (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
  20566. patchFlag |= 512 /* PatchFlags.NEED_PATCH */;
  20567. }
  20568. // pre-normalize props, SSR is skipped for now
  20569. if (!context.inSSR && propsExpression) {
  20570. switch (propsExpression.type) {
  20571. case 15 /* NodeTypes.JS_OBJECT_EXPRESSION */:
  20572. // means that there is no v-bind,
  20573. // but still need to deal with dynamic key binding
  20574. let classKeyIndex = -1;
  20575. let styleKeyIndex = -1;
  20576. let hasDynamicKey = false;
  20577. for (let i = 0; i < propsExpression.properties.length; i++) {
  20578. const key = propsExpression.properties[i].key;
  20579. if (isStaticExp(key)) {
  20580. if (key.content === 'class') {
  20581. classKeyIndex = i;
  20582. }
  20583. else if (key.content === 'style') {
  20584. styleKeyIndex = i;
  20585. }
  20586. }
  20587. else if (!key.isHandlerKey) {
  20588. hasDynamicKey = true;
  20589. }
  20590. }
  20591. const classProp = propsExpression.properties[classKeyIndex];
  20592. const styleProp = propsExpression.properties[styleKeyIndex];
  20593. // no dynamic key
  20594. if (!hasDynamicKey) {
  20595. if (classProp && !isStaticExp(classProp.value)) {
  20596. classProp.value = createCallExpression(context.helper(NORMALIZE_CLASS), [classProp.value]);
  20597. }
  20598. if (styleProp &&
  20599. // the static style is compiled into an object,
  20600. // so use `hasStyleBinding` to ensure that it is a dynamic style binding
  20601. (hasStyleBinding ||
  20602. (styleProp.value.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  20603. styleProp.value.content.trim()[0] === `[`) ||
  20604. // v-bind:style and style both exist,
  20605. // v-bind:style with static literal object
  20606. styleProp.value.type === 17 /* NodeTypes.JS_ARRAY_EXPRESSION */)) {
  20607. styleProp.value = createCallExpression(context.helper(NORMALIZE_STYLE), [styleProp.value]);
  20608. }
  20609. }
  20610. else {
  20611. // dynamic key binding, wrap with `normalizeProps`
  20612. propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [propsExpression]);
  20613. }
  20614. break;
  20615. case 14 /* NodeTypes.JS_CALL_EXPRESSION */:
  20616. // mergeProps call, do nothing
  20617. break;
  20618. default:
  20619. // single v-bind
  20620. propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [
  20621. createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [
  20622. propsExpression
  20623. ])
  20624. ]);
  20625. break;
  20626. }
  20627. }
  20628. return {
  20629. props: propsExpression,
  20630. directives: runtimeDirectives,
  20631. patchFlag,
  20632. dynamicPropNames,
  20633. shouldUseBlock
  20634. };
  20635. }
  20636. // Dedupe props in an object literal.
  20637. // Literal duplicated attributes would have been warned during the parse phase,
  20638. // however, it's possible to encounter duplicated `onXXX` handlers with different
  20639. // modifiers. We also need to merge static and dynamic class / style attributes.
  20640. // - onXXX handlers / style: merge into array
  20641. // - class: merge into single expression with concatenation
  20642. function dedupeProperties(properties) {
  20643. const knownProps = new Map();
  20644. const deduped = [];
  20645. for (let i = 0; i < properties.length; i++) {
  20646. const prop = properties[i];
  20647. // dynamic keys are always allowed
  20648. if (prop.key.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
  20649. deduped.push(prop);
  20650. continue;
  20651. }
  20652. const name = prop.key.content;
  20653. const existing = knownProps.get(name);
  20654. if (existing) {
  20655. if (name === 'style' || name === 'class' || isOn(name)) {
  20656. mergeAsArray(existing, prop);
  20657. }
  20658. // unexpected duplicate, should have emitted error during parse
  20659. }
  20660. else {
  20661. knownProps.set(name, prop);
  20662. deduped.push(prop);
  20663. }
  20664. }
  20665. return deduped;
  20666. }
  20667. function mergeAsArray(existing, incoming) {
  20668. if (existing.value.type === 17 /* NodeTypes.JS_ARRAY_EXPRESSION */) {
  20669. existing.value.elements.push(incoming.value);
  20670. }
  20671. else {
  20672. existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
  20673. }
  20674. }
  20675. function buildDirectiveArgs(dir, context) {
  20676. const dirArgs = [];
  20677. const runtime = directiveImportMap.get(dir);
  20678. if (runtime) {
  20679. // built-in directive with runtime
  20680. dirArgs.push(context.helperString(runtime));
  20681. }
  20682. else {
  20683. // user directive.
  20684. // see if we have directives exposed via <script setup>
  20685. const fromSetup = resolveSetupReference('v-' + dir.name, context);
  20686. if (fromSetup) {
  20687. dirArgs.push(fromSetup);
  20688. }
  20689. else {
  20690. // inject statement for resolving directive
  20691. context.helper(RESOLVE_DIRECTIVE);
  20692. context.directives.add(dir.name);
  20693. dirArgs.push(toValidAssetId(dir.name, `directive`));
  20694. }
  20695. }
  20696. const { loc } = dir;
  20697. if (dir.exp)
  20698. dirArgs.push(dir.exp);
  20699. if (dir.arg) {
  20700. if (!dir.exp) {
  20701. dirArgs.push(`void 0`);
  20702. }
  20703. dirArgs.push(dir.arg);
  20704. }
  20705. if (Object.keys(dir.modifiers).length) {
  20706. if (!dir.arg) {
  20707. if (!dir.exp) {
  20708. dirArgs.push(`void 0`);
  20709. }
  20710. dirArgs.push(`void 0`);
  20711. }
  20712. const trueExpression = createSimpleExpression(`true`, false, loc);
  20713. dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
  20714. }
  20715. return createArrayExpression(dirArgs, dir.loc);
  20716. }
  20717. function stringifyDynamicPropNames(props) {
  20718. let propsNamesString = `[`;
  20719. for (let i = 0, l = props.length; i < l; i++) {
  20720. propsNamesString += JSON.stringify(props[i]);
  20721. if (i < l - 1)
  20722. propsNamesString += ', ';
  20723. }
  20724. return propsNamesString + `]`;
  20725. }
  20726. function isComponentTag(tag) {
  20727. return tag === 'component' || tag === 'Component';
  20728. }
  20729. const transformSlotOutlet = (node, context) => {
  20730. if (isSlotOutlet(node)) {
  20731. const { children, loc } = node;
  20732. const { slotName, slotProps } = processSlotOutlet(node, context);
  20733. const slotArgs = [
  20734. context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
  20735. slotName,
  20736. '{}',
  20737. 'undefined',
  20738. 'true'
  20739. ];
  20740. let expectedLen = 2;
  20741. if (slotProps) {
  20742. slotArgs[2] = slotProps;
  20743. expectedLen = 3;
  20744. }
  20745. if (children.length) {
  20746. slotArgs[3] = createFunctionExpression([], children, false, false, loc);
  20747. expectedLen = 4;
  20748. }
  20749. if (context.scopeId && !context.slotted) {
  20750. expectedLen = 5;
  20751. }
  20752. slotArgs.splice(expectedLen); // remove unused arguments
  20753. node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
  20754. }
  20755. };
  20756. function processSlotOutlet(node, context) {
  20757. let slotName = `"default"`;
  20758. let slotProps = undefined;
  20759. const nonNameProps = [];
  20760. for (let i = 0; i < node.props.length; i++) {
  20761. const p = node.props[i];
  20762. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  20763. if (p.value) {
  20764. if (p.name === 'name') {
  20765. slotName = JSON.stringify(p.value.content);
  20766. }
  20767. else {
  20768. p.name = camelize(p.name);
  20769. nonNameProps.push(p);
  20770. }
  20771. }
  20772. }
  20773. else {
  20774. if (p.name === 'bind' && isStaticArgOf(p.arg, 'name')) {
  20775. if (p.exp)
  20776. slotName = p.exp;
  20777. }
  20778. else {
  20779. if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
  20780. p.arg.content = camelize(p.arg.content);
  20781. }
  20782. nonNameProps.push(p);
  20783. }
  20784. }
  20785. }
  20786. if (nonNameProps.length > 0) {
  20787. const { props, directives } = buildProps(node, context, nonNameProps, false, false);
  20788. slotProps = props;
  20789. if (directives.length) {
  20790. context.onError(createCompilerError(36 /* ErrorCodes.X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
  20791. }
  20792. }
  20793. return {
  20794. slotName,
  20795. slotProps
  20796. };
  20797. }
  20798. const fnExpRE = /^\s*([\w$_]+|(async\s*)?\([^)]*?\))\s*(:[^=]+)?=>|^\s*(async\s+)?function(?:\s+[\w$]+)?\s*\(/;
  20799. const transformOn$1 = (dir, node, context, augmentor) => {
  20800. const { loc, modifiers, arg } = dir;
  20801. if (!dir.exp && !modifiers.length) {
  20802. context.onError(createCompilerError(35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */, loc));
  20803. }
  20804. let eventName;
  20805. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  20806. if (arg.isStatic) {
  20807. let rawName = arg.content;
  20808. // TODO deprecate @vnodeXXX usage
  20809. if (rawName.startsWith('vue:')) {
  20810. rawName = `vnode-${rawName.slice(4)}`;
  20811. }
  20812. const eventString = node.tagType !== 0 /* ElementTypes.ELEMENT */ ||
  20813. rawName.startsWith('vnode') ||
  20814. !/[A-Z]/.test(rawName)
  20815. ? // for non-element and vnode lifecycle event listeners, auto convert
  20816. // it to camelCase. See issue #2249
  20817. toHandlerKey(camelize(rawName))
  20818. : // preserve case for plain element listeners that have uppercase
  20819. // letters, as these may be custom elements' custom events
  20820. `on:${rawName}`;
  20821. eventName = createSimpleExpression(eventString, true, arg.loc);
  20822. }
  20823. else {
  20824. // #2388
  20825. eventName = createCompoundExpression([
  20826. `${context.helperString(TO_HANDLER_KEY)}(`,
  20827. arg,
  20828. `)`
  20829. ]);
  20830. }
  20831. }
  20832. else {
  20833. // already a compound expression.
  20834. eventName = arg;
  20835. eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
  20836. eventName.children.push(`)`);
  20837. }
  20838. // handler processing
  20839. let exp = dir.exp;
  20840. if (exp && !exp.content.trim()) {
  20841. exp = undefined;
  20842. }
  20843. let shouldCache = context.cacheHandlers && !exp && !context.inVOnce;
  20844. if (exp) {
  20845. const isMemberExp = isMemberExpression(exp.content, context);
  20846. const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
  20847. const hasMultipleStatements = exp.content.includes(`;`);
  20848. // process the expression since it's been skipped
  20849. if (context.prefixIdentifiers) {
  20850. isInlineStatement && context.addIdentifiers(`$event`);
  20851. exp = dir.exp = processExpression(exp, context, false, hasMultipleStatements);
  20852. isInlineStatement && context.removeIdentifiers(`$event`);
  20853. // with scope analysis, the function is hoistable if it has no reference
  20854. // to scope variables.
  20855. shouldCache =
  20856. context.cacheHandlers &&
  20857. // unnecessary to cache inside v-once
  20858. !context.inVOnce &&
  20859. // runtime constants don't need to be cached
  20860. // (this is analyzed by compileScript in SFC <script setup>)
  20861. !(exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && exp.constType > 0) &&
  20862. // #1541 bail if this is a member exp handler passed to a component -
  20863. // we need to use the original function to preserve arity,
  20864. // e.g. <transition> relies on checking cb.length to determine
  20865. // transition end handling. Inline function is ok since its arity
  20866. // is preserved even when cached.
  20867. !(isMemberExp && node.tagType === 1 /* ElementTypes.COMPONENT */) &&
  20868. // bail if the function references closure variables (v-for, v-slot)
  20869. // it must be passed fresh to avoid stale values.
  20870. !hasScopeRef(exp, context.identifiers);
  20871. // If the expression is optimizable and is a member expression pointing
  20872. // to a function, turn it into invocation (and wrap in an arrow function
  20873. // below) so that it always accesses the latest value when called - thus
  20874. // avoiding the need to be patched.
  20875. if (shouldCache && isMemberExp) {
  20876. if (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  20877. exp.content = `${exp.content} && ${exp.content}(...args)`;
  20878. }
  20879. else {
  20880. exp.children = [...exp.children, ` && `, ...exp.children, `(...args)`];
  20881. }
  20882. }
  20883. }
  20884. if (isInlineStatement || (shouldCache && isMemberExp)) {
  20885. // wrap inline statement in a function expression
  20886. exp = createCompoundExpression([
  20887. `${isInlineStatement
  20888. ? context.isTS
  20889. ? `($event: any)`
  20890. : `$event`
  20891. : `${context.isTS ? `\n//@ts-ignore\n` : ``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
  20892. exp,
  20893. hasMultipleStatements ? `}` : `)`
  20894. ]);
  20895. }
  20896. }
  20897. let ret = {
  20898. props: [
  20899. createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
  20900. ]
  20901. };
  20902. // apply extended compiler augmentor
  20903. if (augmentor) {
  20904. ret = augmentor(ret);
  20905. }
  20906. if (shouldCache) {
  20907. // cache handlers so that it's always the same handler being passed down.
  20908. // this avoids unnecessary re-renders when users use inline handlers on
  20909. // components.
  20910. ret.props[0].value = context.cache(ret.props[0].value);
  20911. }
  20912. // mark the key as handler for props normalization check
  20913. ret.props.forEach(p => (p.key.isHandlerKey = true));
  20914. return ret;
  20915. };
  20916. // v-bind without arg is handled directly in ./transformElements.ts due to it affecting
  20917. // codegen for the entire props object. This transform here is only for v-bind
  20918. // *with* args.
  20919. const transformBind = (dir, _node, context) => {
  20920. const { exp, modifiers, loc } = dir;
  20921. const arg = dir.arg;
  20922. if (arg.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  20923. arg.children.unshift(`(`);
  20924. arg.children.push(`) || ""`);
  20925. }
  20926. else if (!arg.isStatic) {
  20927. arg.content = `${arg.content} || ""`;
  20928. }
  20929. // .sync is replaced by v-model:arg
  20930. if (modifiers.includes('camel')) {
  20931. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  20932. if (arg.isStatic) {
  20933. arg.content = camelize(arg.content);
  20934. }
  20935. else {
  20936. arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
  20937. }
  20938. }
  20939. else {
  20940. arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
  20941. arg.children.push(`)`);
  20942. }
  20943. }
  20944. if (!context.inSSR) {
  20945. if (modifiers.includes('prop')) {
  20946. injectPrefix(arg, '.');
  20947. }
  20948. if (modifiers.includes('attr')) {
  20949. injectPrefix(arg, '^');
  20950. }
  20951. }
  20952. if (!exp ||
  20953. (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && !exp.content.trim())) {
  20954. context.onError(createCompilerError(34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */, loc));
  20955. return {
  20956. props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
  20957. };
  20958. }
  20959. return {
  20960. props: [createObjectProperty(arg, exp)]
  20961. };
  20962. };
  20963. const injectPrefix = (arg, prefix) => {
  20964. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  20965. if (arg.isStatic) {
  20966. arg.content = prefix + arg.content;
  20967. }
  20968. else {
  20969. arg.content = `\`${prefix}\${${arg.content}}\``;
  20970. }
  20971. }
  20972. else {
  20973. arg.children.unshift(`'${prefix}' + (`);
  20974. arg.children.push(`)`);
  20975. }
  20976. };
  20977. // Merge adjacent text nodes and expressions into a single expression
  20978. // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
  20979. const transformText = (node, context) => {
  20980. if (node.type === 0 /* NodeTypes.ROOT */ ||
  20981. node.type === 1 /* NodeTypes.ELEMENT */ ||
  20982. node.type === 11 /* NodeTypes.FOR */ ||
  20983. node.type === 10 /* NodeTypes.IF_BRANCH */) {
  20984. // perform the transform on node exit so that all expressions have already
  20985. // been processed.
  20986. return () => {
  20987. const children = node.children;
  20988. let currentContainer = undefined;
  20989. let hasText = false;
  20990. for (let i = 0; i < children.length; i++) {
  20991. const child = children[i];
  20992. if (isText$1(child)) {
  20993. hasText = true;
  20994. for (let j = i + 1; j < children.length; j++) {
  20995. const next = children[j];
  20996. if (isText$1(next)) {
  20997. if (!currentContainer) {
  20998. currentContainer = children[i] = createCompoundExpression([child], child.loc);
  20999. }
  21000. // merge adjacent text node into current
  21001. currentContainer.children.push(` + `, next);
  21002. children.splice(j, 1);
  21003. j--;
  21004. }
  21005. else {
  21006. currentContainer = undefined;
  21007. break;
  21008. }
  21009. }
  21010. }
  21011. }
  21012. if (!hasText ||
  21013. // if this is a plain element with a single text child, leave it
  21014. // as-is since the runtime has dedicated fast path for this by directly
  21015. // setting textContent of the element.
  21016. // for component root it's always normalized anyway.
  21017. (children.length === 1 &&
  21018. (node.type === 0 /* NodeTypes.ROOT */ ||
  21019. (node.type === 1 /* NodeTypes.ELEMENT */ &&
  21020. node.tagType === 0 /* ElementTypes.ELEMENT */ &&
  21021. // #3756
  21022. // custom directives can potentially add DOM elements arbitrarily,
  21023. // we need to avoid setting textContent of the element at runtime
  21024. // to avoid accidentally overwriting the DOM elements added
  21025. // by the user through custom directives.
  21026. !node.props.find(p => p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  21027. !context.directiveTransforms[p.name]) &&
  21028. // in compat mode, <template> tags with no special directives
  21029. // will be rendered as a fragment so its children must be
  21030. // converted into vnodes.
  21031. !(false ))))) {
  21032. return;
  21033. }
  21034. // pre-convert text nodes into createTextVNode(text) calls to avoid
  21035. // runtime normalization.
  21036. for (let i = 0; i < children.length; i++) {
  21037. const child = children[i];
  21038. if (isText$1(child) || child.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) {
  21039. const callArgs = [];
  21040. // createTextVNode defaults to single whitespace, so if it is a
  21041. // single space the code could be an empty call to save bytes.
  21042. if (child.type !== 2 /* NodeTypes.TEXT */ || child.content !== ' ') {
  21043. callArgs.push(child);
  21044. }
  21045. // mark dynamic text with flag so it gets patched inside a block
  21046. if (!context.ssr &&
  21047. getConstantType(child, context) === 0 /* ConstantTypes.NOT_CONSTANT */) {
  21048. callArgs.push(1 /* PatchFlags.TEXT */ +
  21049. (` /* ${PatchFlagNames[1 /* PatchFlags.TEXT */]} */` ));
  21050. }
  21051. children[i] = {
  21052. type: 12 /* NodeTypes.TEXT_CALL */,
  21053. content: child,
  21054. loc: child.loc,
  21055. codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
  21056. };
  21057. }
  21058. }
  21059. };
  21060. }
  21061. };
  21062. const seen$1 = new WeakSet();
  21063. const transformOnce = (node, context) => {
  21064. if (node.type === 1 /* NodeTypes.ELEMENT */ && findDir(node, 'once', true)) {
  21065. if (seen$1.has(node) || context.inVOnce) {
  21066. return;
  21067. }
  21068. seen$1.add(node);
  21069. context.inVOnce = true;
  21070. context.helper(SET_BLOCK_TRACKING);
  21071. return () => {
  21072. context.inVOnce = false;
  21073. const cur = context.currentNode;
  21074. if (cur.codegenNode) {
  21075. cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
  21076. }
  21077. };
  21078. }
  21079. };
  21080. const transformModel$1 = (dir, node, context) => {
  21081. const { exp, arg } = dir;
  21082. if (!exp) {
  21083. context.onError(createCompilerError(41 /* ErrorCodes.X_V_MODEL_NO_EXPRESSION */, dir.loc));
  21084. return createTransformProps();
  21085. }
  21086. const rawExp = exp.loc.source;
  21087. const expString = exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ? exp.content : rawExp;
  21088. // im SFC <script setup> inline mode, the exp may have been transformed into
  21089. // _unref(exp)
  21090. const bindingType = context.bindingMetadata[rawExp];
  21091. // check props
  21092. if (bindingType === "props" /* BindingTypes.PROPS */ ||
  21093. bindingType === "props-aliased" /* BindingTypes.PROPS_ALIASED */) {
  21094. context.onError(createCompilerError(44 /* ErrorCodes.X_V_MODEL_ON_PROPS */, exp.loc));
  21095. return createTransformProps();
  21096. }
  21097. const maybeRef = context.inline &&
  21098. (bindingType === "setup-let" /* BindingTypes.SETUP_LET */ ||
  21099. bindingType === "setup-ref" /* BindingTypes.SETUP_REF */ ||
  21100. bindingType === "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */);
  21101. if (!expString.trim() ||
  21102. (!isMemberExpression(expString, context) && !maybeRef)) {
  21103. context.onError(createCompilerError(42 /* ErrorCodes.X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
  21104. return createTransformProps();
  21105. }
  21106. if (context.prefixIdentifiers &&
  21107. isSimpleIdentifier(expString) &&
  21108. context.identifiers[expString]) {
  21109. context.onError(createCompilerError(43 /* ErrorCodes.X_V_MODEL_ON_SCOPE_VARIABLE */, exp.loc));
  21110. return createTransformProps();
  21111. }
  21112. const propName = arg ? arg : createSimpleExpression('modelValue', true);
  21113. const eventName = arg
  21114. ? isStaticExp(arg)
  21115. ? `onUpdate:${camelize(arg.content)}`
  21116. : createCompoundExpression(['"onUpdate:" + ', arg])
  21117. : `onUpdate:modelValue`;
  21118. let assignmentExp;
  21119. const eventArg = context.isTS ? `($event: any)` : `$event`;
  21120. if (maybeRef) {
  21121. if (bindingType === "setup-ref" /* BindingTypes.SETUP_REF */) {
  21122. // v-model used on known ref.
  21123. assignmentExp = createCompoundExpression([
  21124. `${eventArg} => ((`,
  21125. createSimpleExpression(rawExp, false, exp.loc),
  21126. `).value = $event)`
  21127. ]);
  21128. }
  21129. else {
  21130. // v-model used on a potentially ref binding in <script setup> inline mode.
  21131. // the assignment needs to check whether the binding is actually a ref.
  21132. const altAssignment = bindingType === "setup-let" /* BindingTypes.SETUP_LET */ ? `${rawExp} = $event` : `null`;
  21133. assignmentExp = createCompoundExpression([
  21134. `${eventArg} => (${context.helperString(IS_REF)}(${rawExp}) ? (`,
  21135. createSimpleExpression(rawExp, false, exp.loc),
  21136. `).value = $event : ${altAssignment})`
  21137. ]);
  21138. }
  21139. }
  21140. else {
  21141. assignmentExp = createCompoundExpression([
  21142. `${eventArg} => ((`,
  21143. exp,
  21144. `) = $event)`
  21145. ]);
  21146. }
  21147. const props = [
  21148. // modelValue: foo
  21149. createObjectProperty(propName, dir.exp),
  21150. // "onUpdate:modelValue": $event => (foo = $event)
  21151. createObjectProperty(eventName, assignmentExp)
  21152. ];
  21153. // cache v-model handler if applicable (when it doesn't refer any scope vars)
  21154. if (context.prefixIdentifiers &&
  21155. !context.inVOnce &&
  21156. context.cacheHandlers &&
  21157. !hasScopeRef(exp, context.identifiers)) {
  21158. props[1].value = context.cache(props[1].value);
  21159. }
  21160. // modelModifiers: { foo: true, "bar-baz": true }
  21161. if (dir.modifiers.length && node.tagType === 1 /* ElementTypes.COMPONENT */) {
  21162. const modifiers = dir.modifiers
  21163. .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
  21164. .join(`, `);
  21165. const modifiersKey = arg
  21166. ? isStaticExp(arg)
  21167. ? `${arg.content}Modifiers`
  21168. : createCompoundExpression([arg, ' + "Modifiers"'])
  21169. : `modelModifiers`;
  21170. props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* ConstantTypes.CAN_HOIST */)));
  21171. }
  21172. return createTransformProps(props);
  21173. };
  21174. function createTransformProps(props = []) {
  21175. return { props };
  21176. }
  21177. const seen = new WeakSet();
  21178. const transformMemo = (node, context) => {
  21179. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  21180. const dir = findDir(node, 'memo');
  21181. if (!dir || seen.has(node)) {
  21182. return;
  21183. }
  21184. seen.add(node);
  21185. return () => {
  21186. const codegenNode = node.codegenNode ||
  21187. context.currentNode.codegenNode;
  21188. if (codegenNode && codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  21189. // non-component sub tree should be turned into a block
  21190. if (node.tagType !== 1 /* ElementTypes.COMPONENT */) {
  21191. makeBlock(codegenNode, context);
  21192. }
  21193. node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [
  21194. dir.exp,
  21195. createFunctionExpression(undefined, codegenNode),
  21196. `_cache`,
  21197. String(context.cached++)
  21198. ]);
  21199. }
  21200. };
  21201. }
  21202. };
  21203. function getBaseTransformPreset(prefixIdentifiers) {
  21204. return [
  21205. [
  21206. transformOnce,
  21207. transformIf,
  21208. transformMemo,
  21209. transformFor,
  21210. ...([]),
  21211. ...(prefixIdentifiers
  21212. ? [
  21213. // order is important
  21214. trackVForSlotScopes,
  21215. transformExpression
  21216. ]
  21217. : []),
  21218. transformSlotOutlet,
  21219. transformElement,
  21220. trackSlotScopes,
  21221. transformText
  21222. ],
  21223. {
  21224. on: transformOn$1,
  21225. bind: transformBind,
  21226. model: transformModel$1
  21227. }
  21228. ];
  21229. }
  21230. // we name it `baseCompile` so that higher order compilers like
  21231. // @vue/compiler-dom can export `compile` while re-exporting everything else.
  21232. function baseCompile(template, options = {}) {
  21233. const onError = options.onError || defaultOnError;
  21234. const isModuleMode = options.mode === 'module';
  21235. const prefixIdentifiers = (options.prefixIdentifiers === true || isModuleMode);
  21236. if (!prefixIdentifiers && options.cacheHandlers) {
  21237. onError(createCompilerError(49 /* ErrorCodes.X_CACHE_HANDLER_NOT_SUPPORTED */));
  21238. }
  21239. if (options.scopeId && !isModuleMode) {
  21240. onError(createCompilerError(50 /* ErrorCodes.X_SCOPE_ID_NOT_SUPPORTED */));
  21241. }
  21242. const ast = isString$2(template) ? baseParse(template, options) : template;
  21243. const [nodeTransforms, directiveTransforms] = getBaseTransformPreset(prefixIdentifiers);
  21244. if (options.isTS) {
  21245. const { expressionPlugins } = options;
  21246. if (!expressionPlugins || !expressionPlugins.includes('typescript')) {
  21247. options.expressionPlugins = [...(expressionPlugins || []), 'typescript'];
  21248. }
  21249. }
  21250. transform$1(ast, extend({}, options, {
  21251. prefixIdentifiers,
  21252. nodeTransforms: [
  21253. ...nodeTransforms,
  21254. ...(options.nodeTransforms || []) // user transforms
  21255. ],
  21256. directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
  21257. )
  21258. }));
  21259. return generate(ast, extend({}, options, {
  21260. prefixIdentifiers
  21261. }));
  21262. }
  21263. const noopDirectiveTransform = () => ({ props: [] });
  21264. const V_MODEL_RADIO = Symbol(`vModelRadio` );
  21265. const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` );
  21266. const V_MODEL_TEXT = Symbol(`vModelText` );
  21267. const V_MODEL_SELECT = Symbol(`vModelSelect` );
  21268. const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` );
  21269. const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` );
  21270. const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` );
  21271. const V_SHOW = Symbol(`vShow` );
  21272. const TRANSITION = Symbol(`Transition` );
  21273. const TRANSITION_GROUP = Symbol(`TransitionGroup` );
  21274. registerRuntimeHelpers({
  21275. [V_MODEL_RADIO]: `vModelRadio`,
  21276. [V_MODEL_CHECKBOX]: `vModelCheckbox`,
  21277. [V_MODEL_TEXT]: `vModelText`,
  21278. [V_MODEL_SELECT]: `vModelSelect`,
  21279. [V_MODEL_DYNAMIC]: `vModelDynamic`,
  21280. [V_ON_WITH_MODIFIERS]: `withModifiers`,
  21281. [V_ON_WITH_KEYS]: `withKeys`,
  21282. [V_SHOW]: `vShow`,
  21283. [TRANSITION]: `Transition`,
  21284. [TRANSITION_GROUP]: `TransitionGroup`
  21285. });
  21286. var namedCharacterReferences = {
  21287. GT: ">",
  21288. gt: ">",
  21289. LT: "<",
  21290. lt: "<",
  21291. "ac;": "∾",
  21292. "af;": "⁡",
  21293. AMP: "&",
  21294. amp: "&",
  21295. "ap;": "≈",
  21296. "DD;": "ⅅ",
  21297. "dd;": "ⅆ",
  21298. deg: "°",
  21299. "ee;": "ⅇ",
  21300. "eg;": "⪚",
  21301. "el;": "⪙",
  21302. ETH: "Ð",
  21303. eth: "ð",
  21304. "gE;": "≧",
  21305. "ge;": "≥",
  21306. "Gg;": "⋙",
  21307. "gg;": "≫",
  21308. "gl;": "≷",
  21309. "GT;": ">",
  21310. "Gt;": "≫",
  21311. "gt;": ">",
  21312. "ic;": "⁣",
  21313. "ii;": "ⅈ",
  21314. "Im;": "ℑ",
  21315. "in;": "∈",
  21316. "it;": "⁢",
  21317. "lE;": "≦",
  21318. "le;": "≤",
  21319. "lg;": "≶",
  21320. "Ll;": "⋘",
  21321. "ll;": "≪",
  21322. "LT;": "<",
  21323. "Lt;": "≪",
  21324. "lt;": "<",
  21325. "mp;": "∓",
  21326. "Mu;": "Μ",
  21327. "mu;": "μ",
  21328. "ne;": "≠",
  21329. "ni;": "∋",
  21330. not: "¬",
  21331. "Nu;": "Ν",
  21332. "nu;": "ν",
  21333. "Or;": "⩔",
  21334. "or;": "∨",
  21335. "oS;": "Ⓢ",
  21336. "Pi;": "Π",
  21337. "pi;": "π",
  21338. "pm;": "±",
  21339. "Pr;": "⪻",
  21340. "pr;": "≺",
  21341. "Re;": "ℜ",
  21342. REG: "®",
  21343. reg: "®",
  21344. "rx;": "℞",
  21345. "Sc;": "⪼",
  21346. "sc;": "≻",
  21347. shy: "­",
  21348. uml: "¨",
  21349. "wp;": "℘",
  21350. "wr;": "≀",
  21351. "Xi;": "Ξ",
  21352. "xi;": "ξ",
  21353. yen: "¥",
  21354. "acd;": "∿",
  21355. "acE;": "∾̳",
  21356. "Acy;": "А",
  21357. "acy;": "а",
  21358. "Afr;": "𝔄",
  21359. "afr;": "𝔞",
  21360. "AMP;": "&",
  21361. "amp;": "&",
  21362. "And;": "⩓",
  21363. "and;": "∧",
  21364. "ang;": "∠",
  21365. "apE;": "⩰",
  21366. "ape;": "≊",
  21367. "ast;": "*",
  21368. Auml: "Ä",
  21369. auml: "ä",
  21370. "Bcy;": "Б",
  21371. "bcy;": "б",
  21372. "Bfr;": "𝔅",
  21373. "bfr;": "𝔟",
  21374. "bne;": "=⃥",
  21375. "bot;": "⊥",
  21376. "Cap;": "⋒",
  21377. "cap;": "∩",
  21378. cent: "¢",
  21379. "Cfr;": "ℭ",
  21380. "cfr;": "𝔠",
  21381. "Chi;": "Χ",
  21382. "chi;": "χ",
  21383. "cir;": "○",
  21384. COPY: "©",
  21385. copy: "©",
  21386. "Cup;": "⋓",
  21387. "cup;": "∪",
  21388. "Dcy;": "Д",
  21389. "dcy;": "д",
  21390. "deg;": "°",
  21391. "Del;": "∇",
  21392. "Dfr;": "𝔇",
  21393. "dfr;": "𝔡",
  21394. "die;": "¨",
  21395. "div;": "÷",
  21396. "Dot;": "¨",
  21397. "dot;": "˙",
  21398. "Ecy;": "Э",
  21399. "ecy;": "э",
  21400. "Efr;": "𝔈",
  21401. "efr;": "𝔢",
  21402. "egs;": "⪖",
  21403. "ell;": "ℓ",
  21404. "els;": "⪕",
  21405. "ENG;": "Ŋ",
  21406. "eng;": "ŋ",
  21407. "Eta;": "Η",
  21408. "eta;": "η",
  21409. "ETH;": "Ð",
  21410. "eth;": "ð",
  21411. Euml: "Ë",
  21412. euml: "ë",
  21413. "Fcy;": "Ф",
  21414. "fcy;": "ф",
  21415. "Ffr;": "𝔉",
  21416. "ffr;": "𝔣",
  21417. "gap;": "⪆",
  21418. "Gcy;": "Г",
  21419. "gcy;": "г",
  21420. "gEl;": "⪌",
  21421. "gel;": "⋛",
  21422. "geq;": "≥",
  21423. "ges;": "⩾",
  21424. "Gfr;": "𝔊",
  21425. "gfr;": "𝔤",
  21426. "ggg;": "⋙",
  21427. "gla;": "⪥",
  21428. "glE;": "⪒",
  21429. "glj;": "⪤",
  21430. "gnE;": "≩",
  21431. "gne;": "⪈",
  21432. "Hat;": "^",
  21433. "Hfr;": "ℌ",
  21434. "hfr;": "𝔥",
  21435. "Icy;": "И",
  21436. "icy;": "и",
  21437. "iff;": "⇔",
  21438. "Ifr;": "ℑ",
  21439. "ifr;": "𝔦",
  21440. "Int;": "∬",
  21441. "int;": "∫",
  21442. Iuml: "Ï",
  21443. iuml: "ï",
  21444. "Jcy;": "Й",
  21445. "jcy;": "й",
  21446. "Jfr;": "𝔍",
  21447. "jfr;": "𝔧",
  21448. "Kcy;": "К",
  21449. "kcy;": "к",
  21450. "Kfr;": "𝔎",
  21451. "kfr;": "𝔨",
  21452. "lap;": "⪅",
  21453. "lat;": "⪫",
  21454. "Lcy;": "Л",
  21455. "lcy;": "л",
  21456. "lEg;": "⪋",
  21457. "leg;": "⋚",
  21458. "leq;": "≤",
  21459. "les;": "⩽",
  21460. "Lfr;": "𝔏",
  21461. "lfr;": "𝔩",
  21462. "lgE;": "⪑",
  21463. "lnE;": "≨",
  21464. "lne;": "⪇",
  21465. "loz;": "◊",
  21466. "lrm;": "‎",
  21467. "Lsh;": "↰",
  21468. "lsh;": "↰",
  21469. macr: "¯",
  21470. "Map;": "⤅",
  21471. "map;": "↦",
  21472. "Mcy;": "М",
  21473. "mcy;": "м",
  21474. "Mfr;": "𝔐",
  21475. "mfr;": "𝔪",
  21476. "mho;": "℧",
  21477. "mid;": "∣",
  21478. "nap;": "≉",
  21479. nbsp: " ",
  21480. "Ncy;": "Н",
  21481. "ncy;": "н",
  21482. "Nfr;": "𝔑",
  21483. "nfr;": "𝔫",
  21484. "ngE;": "≧̸",
  21485. "nge;": "≱",
  21486. "nGg;": "⋙̸",
  21487. "nGt;": "≫⃒",
  21488. "ngt;": "≯",
  21489. "nis;": "⋼",
  21490. "niv;": "∋",
  21491. "nlE;": "≦̸",
  21492. "nle;": "≰",
  21493. "nLl;": "⋘̸",
  21494. "nLt;": "≪⃒",
  21495. "nlt;": "≮",
  21496. "Not;": "⫬",
  21497. "not;": "¬",
  21498. "npr;": "⊀",
  21499. "nsc;": "⊁",
  21500. "num;": "#",
  21501. "Ocy;": "О",
  21502. "ocy;": "о",
  21503. "Ofr;": "𝔒",
  21504. "ofr;": "𝔬",
  21505. "ogt;": "⧁",
  21506. "ohm;": "Ω",
  21507. "olt;": "⧀",
  21508. "ord;": "⩝",
  21509. ordf: "ª",
  21510. ordm: "º",
  21511. "orv;": "⩛",
  21512. Ouml: "Ö",
  21513. ouml: "ö",
  21514. "par;": "∥",
  21515. para: "¶",
  21516. "Pcy;": "П",
  21517. "pcy;": "п",
  21518. "Pfr;": "𝔓",
  21519. "pfr;": "𝔭",
  21520. "Phi;": "Φ",
  21521. "phi;": "φ",
  21522. "piv;": "ϖ",
  21523. "prE;": "⪳",
  21524. "pre;": "⪯",
  21525. "Psi;": "Ψ",
  21526. "psi;": "ψ",
  21527. "Qfr;": "𝔔",
  21528. "qfr;": "𝔮",
  21529. QUOT: "\"",
  21530. quot: "\"",
  21531. "Rcy;": "Р",
  21532. "rcy;": "р",
  21533. "REG;": "®",
  21534. "reg;": "®",
  21535. "Rfr;": "ℜ",
  21536. "rfr;": "𝔯",
  21537. "Rho;": "Ρ",
  21538. "rho;": "ρ",
  21539. "rlm;": "‏",
  21540. "Rsh;": "↱",
  21541. "rsh;": "↱",
  21542. "scE;": "⪴",
  21543. "sce;": "⪰",
  21544. "Scy;": "С",
  21545. "scy;": "с",
  21546. sect: "§",
  21547. "Sfr;": "𝔖",
  21548. "sfr;": "𝔰",
  21549. "shy;": "­",
  21550. "sim;": "∼",
  21551. "smt;": "⪪",
  21552. "sol;": "/",
  21553. "squ;": "□",
  21554. "Sub;": "⋐",
  21555. "sub;": "⊂",
  21556. "Sum;": "∑",
  21557. "sum;": "∑",
  21558. "Sup;": "⋑",
  21559. "sup;": "⊃",
  21560. sup1: "¹",
  21561. sup2: "²",
  21562. sup3: "³",
  21563. "Tab;": "\t",
  21564. "Tau;": "Τ",
  21565. "tau;": "τ",
  21566. "Tcy;": "Т",
  21567. "tcy;": "т",
  21568. "Tfr;": "𝔗",
  21569. "tfr;": "𝔱",
  21570. "top;": "⊤",
  21571. "Ucy;": "У",
  21572. "ucy;": "у",
  21573. "Ufr;": "𝔘",
  21574. "ufr;": "𝔲",
  21575. "uml;": "¨",
  21576. Uuml: "Ü",
  21577. uuml: "ü",
  21578. "Vcy;": "В",
  21579. "vcy;": "в",
  21580. "Vee;": "⋁",
  21581. "vee;": "∨",
  21582. "Vfr;": "𝔙",
  21583. "vfr;": "𝔳",
  21584. "Wfr;": "𝔚",
  21585. "wfr;": "𝔴",
  21586. "Xfr;": "𝔛",
  21587. "xfr;": "𝔵",
  21588. "Ycy;": "Ы",
  21589. "ycy;": "ы",
  21590. "yen;": "¥",
  21591. "Yfr;": "𝔜",
  21592. "yfr;": "𝔶",
  21593. yuml: "ÿ",
  21594. "Zcy;": "З",
  21595. "zcy;": "з",
  21596. "Zfr;": "ℨ",
  21597. "zfr;": "𝔷",
  21598. "zwj;": "‍",
  21599. Acirc: "Â",
  21600. acirc: "â",
  21601. acute: "´",
  21602. AElig: "Æ",
  21603. aelig: "æ",
  21604. "andd;": "⩜",
  21605. "andv;": "⩚",
  21606. "ange;": "⦤",
  21607. "Aopf;": "𝔸",
  21608. "aopf;": "𝕒",
  21609. "apid;": "≋",
  21610. "apos;": "'",
  21611. Aring: "Å",
  21612. aring: "å",
  21613. "Ascr;": "𝒜",
  21614. "ascr;": "𝒶",
  21615. "Auml;": "Ä",
  21616. "auml;": "ä",
  21617. "Barv;": "⫧",
  21618. "bbrk;": "⎵",
  21619. "Beta;": "Β",
  21620. "beta;": "β",
  21621. "beth;": "ℶ",
  21622. "bNot;": "⫭",
  21623. "bnot;": "⌐",
  21624. "Bopf;": "𝔹",
  21625. "bopf;": "𝕓",
  21626. "boxH;": "═",
  21627. "boxh;": "─",
  21628. "boxV;": "║",
  21629. "boxv;": "│",
  21630. "Bscr;": "ℬ",
  21631. "bscr;": "𝒷",
  21632. "bsim;": "∽",
  21633. "bsol;": "\\",
  21634. "bull;": "•",
  21635. "bump;": "≎",
  21636. "caps;": "∩︀",
  21637. "Cdot;": "Ċ",
  21638. "cdot;": "ċ",
  21639. cedil: "¸",
  21640. "cent;": "¢",
  21641. "CHcy;": "Ч",
  21642. "chcy;": "ч",
  21643. "circ;": "ˆ",
  21644. "cirE;": "⧃",
  21645. "cire;": "≗",
  21646. "comp;": "∁",
  21647. "cong;": "≅",
  21648. "Copf;": "ℂ",
  21649. "copf;": "𝕔",
  21650. "COPY;": "©",
  21651. "copy;": "©",
  21652. "Cscr;": "𝒞",
  21653. "cscr;": "𝒸",
  21654. "csub;": "⫏",
  21655. "csup;": "⫐",
  21656. "cups;": "∪︀",
  21657. "Darr;": "↡",
  21658. "dArr;": "⇓",
  21659. "darr;": "↓",
  21660. "dash;": "‐",
  21661. "dHar;": "⥥",
  21662. "diam;": "⋄",
  21663. "DJcy;": "Ђ",
  21664. "djcy;": "ђ",
  21665. "Dopf;": "𝔻",
  21666. "dopf;": "𝕕",
  21667. "Dscr;": "𝒟",
  21668. "dscr;": "𝒹",
  21669. "DScy;": "Ѕ",
  21670. "dscy;": "ѕ",
  21671. "dsol;": "⧶",
  21672. "dtri;": "▿",
  21673. "DZcy;": "Џ",
  21674. "dzcy;": "џ",
  21675. "ecir;": "≖",
  21676. Ecirc: "Ê",
  21677. ecirc: "ê",
  21678. "Edot;": "Ė",
  21679. "eDot;": "≑",
  21680. "edot;": "ė",
  21681. "emsp;": " ",
  21682. "ensp;": " ",
  21683. "Eopf;": "𝔼",
  21684. "eopf;": "𝕖",
  21685. "epar;": "⋕",
  21686. "epsi;": "ε",
  21687. "Escr;": "ℰ",
  21688. "escr;": "ℯ",
  21689. "Esim;": "⩳",
  21690. "esim;": "≂",
  21691. "Euml;": "Ë",
  21692. "euml;": "ë",
  21693. "euro;": "€",
  21694. "excl;": "!",
  21695. "flat;": "♭",
  21696. "fnof;": "ƒ",
  21697. "Fopf;": "𝔽",
  21698. "fopf;": "𝕗",
  21699. "fork;": "⋔",
  21700. "Fscr;": "ℱ",
  21701. "fscr;": "𝒻",
  21702. "Gdot;": "Ġ",
  21703. "gdot;": "ġ",
  21704. "geqq;": "≧",
  21705. "gesl;": "⋛︀",
  21706. "GJcy;": "Ѓ",
  21707. "gjcy;": "ѓ",
  21708. "gnap;": "⪊",
  21709. "gneq;": "⪈",
  21710. "Gopf;": "𝔾",
  21711. "gopf;": "𝕘",
  21712. "Gscr;": "𝒢",
  21713. "gscr;": "ℊ",
  21714. "gsim;": "≳",
  21715. "gtcc;": "⪧",
  21716. "gvnE;": "≩︀",
  21717. "half;": "½",
  21718. "hArr;": "⇔",
  21719. "harr;": "↔",
  21720. "hbar;": "ℏ",
  21721. "Hopf;": "ℍ",
  21722. "hopf;": "𝕙",
  21723. "Hscr;": "ℋ",
  21724. "hscr;": "𝒽",
  21725. Icirc: "Î",
  21726. icirc: "î",
  21727. "Idot;": "İ",
  21728. "IEcy;": "Е",
  21729. "iecy;": "е",
  21730. iexcl: "¡",
  21731. "imof;": "⊷",
  21732. "IOcy;": "Ё",
  21733. "iocy;": "ё",
  21734. "Iopf;": "𝕀",
  21735. "iopf;": "𝕚",
  21736. "Iota;": "Ι",
  21737. "iota;": "ι",
  21738. "Iscr;": "ℐ",
  21739. "iscr;": "𝒾",
  21740. "isin;": "∈",
  21741. "Iuml;": "Ï",
  21742. "iuml;": "ï",
  21743. "Jopf;": "𝕁",
  21744. "jopf;": "𝕛",
  21745. "Jscr;": "𝒥",
  21746. "jscr;": "𝒿",
  21747. "KHcy;": "Х",
  21748. "khcy;": "х",
  21749. "KJcy;": "Ќ",
  21750. "kjcy;": "ќ",
  21751. "Kopf;": "𝕂",
  21752. "kopf;": "𝕜",
  21753. "Kscr;": "𝒦",
  21754. "kscr;": "𝓀",
  21755. "Lang;": "⟪",
  21756. "lang;": "⟨",
  21757. laquo: "«",
  21758. "Larr;": "↞",
  21759. "lArr;": "⇐",
  21760. "larr;": "←",
  21761. "late;": "⪭",
  21762. "lcub;": "{",
  21763. "ldca;": "⤶",
  21764. "ldsh;": "↲",
  21765. "leqq;": "≦",
  21766. "lesg;": "⋚︀",
  21767. "lHar;": "⥢",
  21768. "LJcy;": "Љ",
  21769. "ljcy;": "љ",
  21770. "lnap;": "⪉",
  21771. "lneq;": "⪇",
  21772. "Lopf;": "𝕃",
  21773. "lopf;": "𝕝",
  21774. "lozf;": "⧫",
  21775. "lpar;": "(",
  21776. "Lscr;": "ℒ",
  21777. "lscr;": "𝓁",
  21778. "lsim;": "≲",
  21779. "lsqb;": "[",
  21780. "ltcc;": "⪦",
  21781. "ltri;": "◃",
  21782. "lvnE;": "≨︀",
  21783. "macr;": "¯",
  21784. "male;": "♂",
  21785. "malt;": "✠",
  21786. micro: "µ",
  21787. "mlcp;": "⫛",
  21788. "mldr;": "…",
  21789. "Mopf;": "𝕄",
  21790. "mopf;": "𝕞",
  21791. "Mscr;": "ℳ",
  21792. "mscr;": "𝓂",
  21793. "nang;": "∠⃒",
  21794. "napE;": "⩰̸",
  21795. "nbsp;": " ",
  21796. "ncap;": "⩃",
  21797. "ncup;": "⩂",
  21798. "ngeq;": "≱",
  21799. "nges;": "⩾̸",
  21800. "ngtr;": "≯",
  21801. "nGtv;": "≫̸",
  21802. "nisd;": "⋺",
  21803. "NJcy;": "Њ",
  21804. "njcy;": "њ",
  21805. "nldr;": "‥",
  21806. "nleq;": "≰",
  21807. "nles;": "⩽̸",
  21808. "nLtv;": "≪̸",
  21809. "nmid;": "∤",
  21810. "Nopf;": "ℕ",
  21811. "nopf;": "𝕟",
  21812. "npar;": "∦",
  21813. "npre;": "⪯̸",
  21814. "nsce;": "⪰̸",
  21815. "Nscr;": "𝒩",
  21816. "nscr;": "𝓃",
  21817. "nsim;": "≁",
  21818. "nsub;": "⊄",
  21819. "nsup;": "⊅",
  21820. "ntgl;": "≹",
  21821. "ntlg;": "≸",
  21822. "nvap;": "≍⃒",
  21823. "nvge;": "≥⃒",
  21824. "nvgt;": ">⃒",
  21825. "nvle;": "≤⃒",
  21826. "nvlt;": "<⃒",
  21827. "oast;": "⊛",
  21828. "ocir;": "⊚",
  21829. Ocirc: "Ô",
  21830. ocirc: "ô",
  21831. "odiv;": "⨸",
  21832. "odot;": "⊙",
  21833. "ogon;": "˛",
  21834. "oint;": "∮",
  21835. "omid;": "⦶",
  21836. "Oopf;": "𝕆",
  21837. "oopf;": "𝕠",
  21838. "opar;": "⦷",
  21839. "ordf;": "ª",
  21840. "ordm;": "º",
  21841. "oror;": "⩖",
  21842. "Oscr;": "𝒪",
  21843. "oscr;": "ℴ",
  21844. "osol;": "⊘",
  21845. "Ouml;": "Ö",
  21846. "ouml;": "ö",
  21847. "para;": "¶",
  21848. "part;": "∂",
  21849. "perp;": "⊥",
  21850. "phiv;": "ϕ",
  21851. "plus;": "+",
  21852. "Popf;": "ℙ",
  21853. "popf;": "𝕡",
  21854. pound: "£",
  21855. "prap;": "⪷",
  21856. "prec;": "≺",
  21857. "prnE;": "⪵",
  21858. "prod;": "∏",
  21859. "prop;": "∝",
  21860. "Pscr;": "𝒫",
  21861. "pscr;": "𝓅",
  21862. "qint;": "⨌",
  21863. "Qopf;": "ℚ",
  21864. "qopf;": "𝕢",
  21865. "Qscr;": "𝒬",
  21866. "qscr;": "𝓆",
  21867. "QUOT;": "\"",
  21868. "quot;": "\"",
  21869. "race;": "∽̱",
  21870. "Rang;": "⟫",
  21871. "rang;": "⟩",
  21872. raquo: "»",
  21873. "Rarr;": "↠",
  21874. "rArr;": "⇒",
  21875. "rarr;": "→",
  21876. "rcub;": "}",
  21877. "rdca;": "⤷",
  21878. "rdsh;": "↳",
  21879. "real;": "ℜ",
  21880. "rect;": "▭",
  21881. "rHar;": "⥤",
  21882. "rhov;": "ϱ",
  21883. "ring;": "˚",
  21884. "Ropf;": "ℝ",
  21885. "ropf;": "𝕣",
  21886. "rpar;": ")",
  21887. "Rscr;": "ℛ",
  21888. "rscr;": "𝓇",
  21889. "rsqb;": "]",
  21890. "rtri;": "▹",
  21891. "scap;": "⪸",
  21892. "scnE;": "⪶",
  21893. "sdot;": "⋅",
  21894. "sect;": "§",
  21895. "semi;": ";",
  21896. "sext;": "✶",
  21897. "SHcy;": "Ш",
  21898. "shcy;": "ш",
  21899. "sime;": "≃",
  21900. "simg;": "⪞",
  21901. "siml;": "⪝",
  21902. "smid;": "∣",
  21903. "smte;": "⪬",
  21904. "solb;": "⧄",
  21905. "Sopf;": "𝕊",
  21906. "sopf;": "𝕤",
  21907. "spar;": "∥",
  21908. "Sqrt;": "√",
  21909. "squf;": "▪",
  21910. "Sscr;": "𝒮",
  21911. "sscr;": "𝓈",
  21912. "Star;": "⋆",
  21913. "star;": "☆",
  21914. "subE;": "⫅",
  21915. "sube;": "⊆",
  21916. "succ;": "≻",
  21917. "sung;": "♪",
  21918. "sup1;": "¹",
  21919. "sup2;": "²",
  21920. "sup3;": "³",
  21921. "supE;": "⫆",
  21922. "supe;": "⊇",
  21923. szlig: "ß",
  21924. "tbrk;": "⎴",
  21925. "tdot;": "⃛",
  21926. THORN: "Þ",
  21927. thorn: "þ",
  21928. times: "×",
  21929. "tint;": "∭",
  21930. "toea;": "⤨",
  21931. "Topf;": "𝕋",
  21932. "topf;": "𝕥",
  21933. "tosa;": "⤩",
  21934. "trie;": "≜",
  21935. "Tscr;": "𝒯",
  21936. "tscr;": "𝓉",
  21937. "TScy;": "Ц",
  21938. "tscy;": "ц",
  21939. "Uarr;": "↟",
  21940. "uArr;": "⇑",
  21941. "uarr;": "↑",
  21942. Ucirc: "Û",
  21943. ucirc: "û",
  21944. "uHar;": "⥣",
  21945. "Uopf;": "𝕌",
  21946. "uopf;": "𝕦",
  21947. "Upsi;": "ϒ",
  21948. "upsi;": "υ",
  21949. "Uscr;": "𝒰",
  21950. "uscr;": "𝓊",
  21951. "utri;": "▵",
  21952. "Uuml;": "Ü",
  21953. "uuml;": "ü",
  21954. "vArr;": "⇕",
  21955. "varr;": "↕",
  21956. "Vbar;": "⫫",
  21957. "vBar;": "⫨",
  21958. "Vert;": "‖",
  21959. "vert;": "|",
  21960. "Vopf;": "𝕍",
  21961. "vopf;": "𝕧",
  21962. "Vscr;": "𝒱",
  21963. "vscr;": "𝓋",
  21964. "Wopf;": "𝕎",
  21965. "wopf;": "𝕨",
  21966. "Wscr;": "𝒲",
  21967. "wscr;": "𝓌",
  21968. "xcap;": "⋂",
  21969. "xcup;": "⋃",
  21970. "xmap;": "⟼",
  21971. "xnis;": "⋻",
  21972. "Xopf;": "𝕏",
  21973. "xopf;": "𝕩",
  21974. "Xscr;": "𝒳",
  21975. "xscr;": "𝓍",
  21976. "xvee;": "⋁",
  21977. "YAcy;": "Я",
  21978. "yacy;": "я",
  21979. "YIcy;": "Ї",
  21980. "yicy;": "ї",
  21981. "Yopf;": "𝕐",
  21982. "yopf;": "𝕪",
  21983. "Yscr;": "𝒴",
  21984. "yscr;": "𝓎",
  21985. "YUcy;": "Ю",
  21986. "yucy;": "ю",
  21987. "Yuml;": "Ÿ",
  21988. "yuml;": "ÿ",
  21989. "Zdot;": "Ż",
  21990. "zdot;": "ż",
  21991. "Zeta;": "Ζ",
  21992. "zeta;": "ζ",
  21993. "ZHcy;": "Ж",
  21994. "zhcy;": "ж",
  21995. "Zopf;": "ℤ",
  21996. "zopf;": "𝕫",
  21997. "Zscr;": "𝒵",
  21998. "zscr;": "𝓏",
  21999. "zwnj;": "‌",
  22000. Aacute: "Á",
  22001. aacute: "á",
  22002. "Acirc;": "Â",
  22003. "acirc;": "â",
  22004. "acute;": "´",
  22005. "AElig;": "Æ",
  22006. "aelig;": "æ",
  22007. Agrave: "À",
  22008. agrave: "à",
  22009. "aleph;": "ℵ",
  22010. "Alpha;": "Α",
  22011. "alpha;": "α",
  22012. "Amacr;": "Ā",
  22013. "amacr;": "ā",
  22014. "amalg;": "⨿",
  22015. "angle;": "∠",
  22016. "angrt;": "∟",
  22017. "angst;": "Å",
  22018. "Aogon;": "Ą",
  22019. "aogon;": "ą",
  22020. "Aring;": "Å",
  22021. "aring;": "å",
  22022. "asymp;": "≈",
  22023. Atilde: "Ã",
  22024. atilde: "ã",
  22025. "awint;": "⨑",
  22026. "bcong;": "≌",
  22027. "bdquo;": "„",
  22028. "bepsi;": "϶",
  22029. "blank;": "␣",
  22030. "blk12;": "▒",
  22031. "blk14;": "░",
  22032. "blk34;": "▓",
  22033. "block;": "█",
  22034. "boxDL;": "╗",
  22035. "boxDl;": "╖",
  22036. "boxdL;": "╕",
  22037. "boxdl;": "┐",
  22038. "boxDR;": "╔",
  22039. "boxDr;": "╓",
  22040. "boxdR;": "╒",
  22041. "boxdr;": "┌",
  22042. "boxHD;": "╦",
  22043. "boxHd;": "╤",
  22044. "boxhD;": "╥",
  22045. "boxhd;": "┬",
  22046. "boxHU;": "╩",
  22047. "boxHu;": "╧",
  22048. "boxhU;": "╨",
  22049. "boxhu;": "┴",
  22050. "boxUL;": "╝",
  22051. "boxUl;": "╜",
  22052. "boxuL;": "╛",
  22053. "boxul;": "┘",
  22054. "boxUR;": "╚",
  22055. "boxUr;": "╙",
  22056. "boxuR;": "╘",
  22057. "boxur;": "└",
  22058. "boxVH;": "╬",
  22059. "boxVh;": "╫",
  22060. "boxvH;": "╪",
  22061. "boxvh;": "┼",
  22062. "boxVL;": "╣",
  22063. "boxVl;": "╢",
  22064. "boxvL;": "╡",
  22065. "boxvl;": "┤",
  22066. "boxVR;": "╠",
  22067. "boxVr;": "╟",
  22068. "boxvR;": "╞",
  22069. "boxvr;": "├",
  22070. "Breve;": "˘",
  22071. "breve;": "˘",
  22072. brvbar: "¦",
  22073. "bsemi;": "⁏",
  22074. "bsime;": "⋍",
  22075. "bsolb;": "⧅",
  22076. "bumpE;": "⪮",
  22077. "bumpe;": "≏",
  22078. "caret;": "⁁",
  22079. "caron;": "ˇ",
  22080. "ccaps;": "⩍",
  22081. Ccedil: "Ç",
  22082. ccedil: "ç",
  22083. "Ccirc;": "Ĉ",
  22084. "ccirc;": "ĉ",
  22085. "ccups;": "⩌",
  22086. "cedil;": "¸",
  22087. "check;": "✓",
  22088. "clubs;": "♣",
  22089. "Colon;": "∷",
  22090. "colon;": ":",
  22091. "comma;": ",",
  22092. "crarr;": "↵",
  22093. "Cross;": "⨯",
  22094. "cross;": "✗",
  22095. "csube;": "⫑",
  22096. "csupe;": "⫒",
  22097. "ctdot;": "⋯",
  22098. "cuepr;": "⋞",
  22099. "cuesc;": "⋟",
  22100. "cupor;": "⩅",
  22101. curren: "¤",
  22102. "cuvee;": "⋎",
  22103. "cuwed;": "⋏",
  22104. "cwint;": "∱",
  22105. "Dashv;": "⫤",
  22106. "dashv;": "⊣",
  22107. "dblac;": "˝",
  22108. "ddarr;": "⇊",
  22109. "Delta;": "Δ",
  22110. "delta;": "δ",
  22111. "dharl;": "⇃",
  22112. "dharr;": "⇂",
  22113. "diams;": "♦",
  22114. "disin;": "⋲",
  22115. divide: "÷",
  22116. "doteq;": "≐",
  22117. "dtdot;": "⋱",
  22118. "dtrif;": "▾",
  22119. "duarr;": "⇵",
  22120. "duhar;": "⥯",
  22121. Eacute: "É",
  22122. eacute: "é",
  22123. "Ecirc;": "Ê",
  22124. "ecirc;": "ê",
  22125. "eDDot;": "⩷",
  22126. "efDot;": "≒",
  22127. Egrave: "È",
  22128. egrave: "è",
  22129. "Emacr;": "Ē",
  22130. "emacr;": "ē",
  22131. "empty;": "∅",
  22132. "Eogon;": "Ę",
  22133. "eogon;": "ę",
  22134. "eplus;": "⩱",
  22135. "epsiv;": "ϵ",
  22136. "eqsim;": "≂",
  22137. "Equal;": "⩵",
  22138. "equiv;": "≡",
  22139. "erarr;": "⥱",
  22140. "erDot;": "≓",
  22141. "esdot;": "≐",
  22142. "exist;": "∃",
  22143. "fflig;": "ff",
  22144. "filig;": "fi",
  22145. "fjlig;": "fj",
  22146. "fllig;": "fl",
  22147. "fltns;": "▱",
  22148. "forkv;": "⫙",
  22149. frac12: "½",
  22150. frac14: "¼",
  22151. frac34: "¾",
  22152. "frasl;": "⁄",
  22153. "frown;": "⌢",
  22154. "Gamma;": "Γ",
  22155. "gamma;": "γ",
  22156. "Gcirc;": "Ĝ",
  22157. "gcirc;": "ĝ",
  22158. "gescc;": "⪩",
  22159. "gimel;": "ℷ",
  22160. "gneqq;": "≩",
  22161. "gnsim;": "⋧",
  22162. "grave;": "`",
  22163. "gsime;": "⪎",
  22164. "gsiml;": "⪐",
  22165. "gtcir;": "⩺",
  22166. "gtdot;": "⋗",
  22167. "Hacek;": "ˇ",
  22168. "harrw;": "↭",
  22169. "Hcirc;": "Ĥ",
  22170. "hcirc;": "ĥ",
  22171. "hoarr;": "⇿",
  22172. Iacute: "Í",
  22173. iacute: "í",
  22174. "Icirc;": "Î",
  22175. "icirc;": "î",
  22176. "iexcl;": "¡",
  22177. Igrave: "Ì",
  22178. igrave: "ì",
  22179. "iiint;": "∭",
  22180. "iiota;": "℩",
  22181. "IJlig;": "IJ",
  22182. "ijlig;": "ij",
  22183. "Imacr;": "Ī",
  22184. "imacr;": "ī",
  22185. "image;": "ℑ",
  22186. "imath;": "ı",
  22187. "imped;": "Ƶ",
  22188. "infin;": "∞",
  22189. "Iogon;": "Į",
  22190. "iogon;": "į",
  22191. "iprod;": "⨼",
  22192. iquest: "¿",
  22193. "isinE;": "⋹",
  22194. "isins;": "⋴",
  22195. "isinv;": "∈",
  22196. "Iukcy;": "І",
  22197. "iukcy;": "і",
  22198. "Jcirc;": "Ĵ",
  22199. "jcirc;": "ĵ",
  22200. "jmath;": "ȷ",
  22201. "Jukcy;": "Є",
  22202. "jukcy;": "є",
  22203. "Kappa;": "Κ",
  22204. "kappa;": "κ",
  22205. "lAarr;": "⇚",
  22206. "langd;": "⦑",
  22207. "laquo;": "«",
  22208. "larrb;": "⇤",
  22209. "lates;": "⪭︀",
  22210. "lBarr;": "⤎",
  22211. "lbarr;": "⤌",
  22212. "lbbrk;": "❲",
  22213. "lbrke;": "⦋",
  22214. "lceil;": "⌈",
  22215. "ldquo;": "“",
  22216. "lescc;": "⪨",
  22217. "lhard;": "↽",
  22218. "lharu;": "↼",
  22219. "lhblk;": "▄",
  22220. "llarr;": "⇇",
  22221. "lltri;": "◺",
  22222. "lneqq;": "≨",
  22223. "lnsim;": "⋦",
  22224. "loang;": "⟬",
  22225. "loarr;": "⇽",
  22226. "lobrk;": "⟦",
  22227. "lopar;": "⦅",
  22228. "lrarr;": "⇆",
  22229. "lrhar;": "⇋",
  22230. "lrtri;": "⊿",
  22231. "lsime;": "⪍",
  22232. "lsimg;": "⪏",
  22233. "lsquo;": "‘",
  22234. "ltcir;": "⩹",
  22235. "ltdot;": "⋖",
  22236. "ltrie;": "⊴",
  22237. "ltrif;": "◂",
  22238. "mdash;": "—",
  22239. "mDDot;": "∺",
  22240. "micro;": "µ",
  22241. middot: "·",
  22242. "minus;": "−",
  22243. "mumap;": "⊸",
  22244. "nabla;": "∇",
  22245. "napid;": "≋̸",
  22246. "napos;": "ʼn",
  22247. "natur;": "♮",
  22248. "nbump;": "≎̸",
  22249. "ncong;": "≇",
  22250. "ndash;": "–",
  22251. "neArr;": "⇗",
  22252. "nearr;": "↗",
  22253. "nedot;": "≐̸",
  22254. "nesim;": "≂̸",
  22255. "ngeqq;": "≧̸",
  22256. "ngsim;": "≵",
  22257. "nhArr;": "⇎",
  22258. "nharr;": "↮",
  22259. "nhpar;": "⫲",
  22260. "nlArr;": "⇍",
  22261. "nlarr;": "↚",
  22262. "nleqq;": "≦̸",
  22263. "nless;": "≮",
  22264. "nlsim;": "≴",
  22265. "nltri;": "⋪",
  22266. "notin;": "∉",
  22267. "notni;": "∌",
  22268. "npart;": "∂̸",
  22269. "nprec;": "⊀",
  22270. "nrArr;": "⇏",
  22271. "nrarr;": "↛",
  22272. "nrtri;": "⋫",
  22273. "nsime;": "≄",
  22274. "nsmid;": "∤",
  22275. "nspar;": "∦",
  22276. "nsubE;": "⫅̸",
  22277. "nsube;": "⊈",
  22278. "nsucc;": "⊁",
  22279. "nsupE;": "⫆̸",
  22280. "nsupe;": "⊉",
  22281. Ntilde: "Ñ",
  22282. ntilde: "ñ",
  22283. "numsp;": " ",
  22284. "nvsim;": "∼⃒",
  22285. "nwArr;": "⇖",
  22286. "nwarr;": "↖",
  22287. Oacute: "Ó",
  22288. oacute: "ó",
  22289. "Ocirc;": "Ô",
  22290. "ocirc;": "ô",
  22291. "odash;": "⊝",
  22292. "OElig;": "Œ",
  22293. "oelig;": "œ",
  22294. "ofcir;": "⦿",
  22295. Ograve: "Ò",
  22296. ograve: "ò",
  22297. "ohbar;": "⦵",
  22298. "olarr;": "↺",
  22299. "olcir;": "⦾",
  22300. "oline;": "‾",
  22301. "Omacr;": "Ō",
  22302. "omacr;": "ō",
  22303. "Omega;": "Ω",
  22304. "omega;": "ω",
  22305. "operp;": "⦹",
  22306. "oplus;": "⊕",
  22307. "orarr;": "↻",
  22308. "order;": "ℴ",
  22309. Oslash: "Ø",
  22310. oslash: "ø",
  22311. Otilde: "Õ",
  22312. otilde: "õ",
  22313. "ovbar;": "⌽",
  22314. "parsl;": "⫽",
  22315. "phone;": "☎",
  22316. "plusb;": "⊞",
  22317. "pluse;": "⩲",
  22318. plusmn: "±",
  22319. "pound;": "£",
  22320. "prcue;": "≼",
  22321. "Prime;": "″",
  22322. "prime;": "′",
  22323. "prnap;": "⪹",
  22324. "prsim;": "≾",
  22325. "quest;": "?",
  22326. "rAarr;": "⇛",
  22327. "radic;": "√",
  22328. "rangd;": "⦒",
  22329. "range;": "⦥",
  22330. "raquo;": "»",
  22331. "rarrb;": "⇥",
  22332. "rarrc;": "⤳",
  22333. "rarrw;": "↝",
  22334. "ratio;": "∶",
  22335. "RBarr;": "⤐",
  22336. "rBarr;": "⤏",
  22337. "rbarr;": "⤍",
  22338. "rbbrk;": "❳",
  22339. "rbrke;": "⦌",
  22340. "rceil;": "⌉",
  22341. "rdquo;": "”",
  22342. "reals;": "ℝ",
  22343. "rhard;": "⇁",
  22344. "rharu;": "⇀",
  22345. "rlarr;": "⇄",
  22346. "rlhar;": "⇌",
  22347. "rnmid;": "⫮",
  22348. "roang;": "⟭",
  22349. "roarr;": "⇾",
  22350. "robrk;": "⟧",
  22351. "ropar;": "⦆",
  22352. "rrarr;": "⇉",
  22353. "rsquo;": "’",
  22354. "rtrie;": "⊵",
  22355. "rtrif;": "▸",
  22356. "sbquo;": "‚",
  22357. "sccue;": "≽",
  22358. "Scirc;": "Ŝ",
  22359. "scirc;": "ŝ",
  22360. "scnap;": "⪺",
  22361. "scsim;": "≿",
  22362. "sdotb;": "⊡",
  22363. "sdote;": "⩦",
  22364. "seArr;": "⇘",
  22365. "searr;": "↘",
  22366. "setmn;": "∖",
  22367. "sharp;": "♯",
  22368. "Sigma;": "Σ",
  22369. "sigma;": "σ",
  22370. "simeq;": "≃",
  22371. "simgE;": "⪠",
  22372. "simlE;": "⪟",
  22373. "simne;": "≆",
  22374. "slarr;": "←",
  22375. "smile;": "⌣",
  22376. "smtes;": "⪬︀",
  22377. "sqcap;": "⊓",
  22378. "sqcup;": "⊔",
  22379. "sqsub;": "⊏",
  22380. "sqsup;": "⊐",
  22381. "srarr;": "→",
  22382. "starf;": "★",
  22383. "strns;": "¯",
  22384. "subnE;": "⫋",
  22385. "subne;": "⊊",
  22386. "supnE;": "⫌",
  22387. "supne;": "⊋",
  22388. "swArr;": "⇙",
  22389. "swarr;": "↙",
  22390. "szlig;": "ß",
  22391. "Theta;": "Θ",
  22392. "theta;": "θ",
  22393. "thkap;": "≈",
  22394. "THORN;": "Þ",
  22395. "thorn;": "þ",
  22396. "Tilde;": "∼",
  22397. "tilde;": "˜",
  22398. "times;": "×",
  22399. "TRADE;": "™",
  22400. "trade;": "™",
  22401. "trisb;": "⧍",
  22402. "TSHcy;": "Ћ",
  22403. "tshcy;": "ћ",
  22404. "twixt;": "≬",
  22405. Uacute: "Ú",
  22406. uacute: "ú",
  22407. "Ubrcy;": "Ў",
  22408. "ubrcy;": "ў",
  22409. "Ucirc;": "Û",
  22410. "ucirc;": "û",
  22411. "udarr;": "⇅",
  22412. "udhar;": "⥮",
  22413. Ugrave: "Ù",
  22414. ugrave: "ù",
  22415. "uharl;": "↿",
  22416. "uharr;": "↾",
  22417. "uhblk;": "▀",
  22418. "ultri;": "◸",
  22419. "Umacr;": "Ū",
  22420. "umacr;": "ū",
  22421. "Union;": "⋃",
  22422. "Uogon;": "Ų",
  22423. "uogon;": "ų",
  22424. "uplus;": "⊎",
  22425. "upsih;": "ϒ",
  22426. "UpTee;": "⊥",
  22427. "Uring;": "Ů",
  22428. "uring;": "ů",
  22429. "urtri;": "◹",
  22430. "utdot;": "⋰",
  22431. "utrif;": "▴",
  22432. "uuarr;": "⇈",
  22433. "varpi;": "ϖ",
  22434. "vBarv;": "⫩",
  22435. "VDash;": "⊫",
  22436. "Vdash;": "⊩",
  22437. "vDash;": "⊨",
  22438. "vdash;": "⊢",
  22439. "veeeq;": "≚",
  22440. "vltri;": "⊲",
  22441. "vnsub;": "⊂⃒",
  22442. "vnsup;": "⊃⃒",
  22443. "vprop;": "∝",
  22444. "vrtri;": "⊳",
  22445. "Wcirc;": "Ŵ",
  22446. "wcirc;": "ŵ",
  22447. "Wedge;": "⋀",
  22448. "wedge;": "∧",
  22449. "xcirc;": "◯",
  22450. "xdtri;": "▽",
  22451. "xhArr;": "⟺",
  22452. "xharr;": "⟷",
  22453. "xlArr;": "⟸",
  22454. "xlarr;": "⟵",
  22455. "xodot;": "⨀",
  22456. "xrArr;": "⟹",
  22457. "xrarr;": "⟶",
  22458. "xutri;": "△",
  22459. Yacute: "Ý",
  22460. yacute: "ý",
  22461. "Ycirc;": "Ŷ",
  22462. "ycirc;": "ŷ",
  22463. "Aacute;": "Á",
  22464. "aacute;": "á",
  22465. "Abreve;": "Ă",
  22466. "abreve;": "ă",
  22467. "Agrave;": "À",
  22468. "agrave;": "à",
  22469. "andand;": "⩕",
  22470. "angmsd;": "∡",
  22471. "angsph;": "∢",
  22472. "apacir;": "⩯",
  22473. "approx;": "≈",
  22474. "Assign;": "≔",
  22475. "Atilde;": "Ã",
  22476. "atilde;": "ã",
  22477. "barvee;": "⊽",
  22478. "Barwed;": "⌆",
  22479. "barwed;": "⌅",
  22480. "becaus;": "∵",
  22481. "bernou;": "ℬ",
  22482. "bigcap;": "⋂",
  22483. "bigcup;": "⋃",
  22484. "bigvee;": "⋁",
  22485. "bkarow;": "⤍",
  22486. "bottom;": "⊥",
  22487. "bowtie;": "⋈",
  22488. "boxbox;": "⧉",
  22489. "bprime;": "‵",
  22490. "brvbar;": "¦",
  22491. "bullet;": "•",
  22492. "Bumpeq;": "≎",
  22493. "bumpeq;": "≏",
  22494. "Cacute;": "Ć",
  22495. "cacute;": "ć",
  22496. "capand;": "⩄",
  22497. "capcap;": "⩋",
  22498. "capcup;": "⩇",
  22499. "capdot;": "⩀",
  22500. "Ccaron;": "Č",
  22501. "ccaron;": "č",
  22502. "Ccedil;": "Ç",
  22503. "ccedil;": "ç",
  22504. "circeq;": "≗",
  22505. "cirmid;": "⫯",
  22506. "Colone;": "⩴",
  22507. "colone;": "≔",
  22508. "commat;": "@",
  22509. "compfn;": "∘",
  22510. "Conint;": "∯",
  22511. "conint;": "∮",
  22512. "coprod;": "∐",
  22513. "copysr;": "℗",
  22514. "cularr;": "↶",
  22515. "CupCap;": "≍",
  22516. "cupcap;": "⩆",
  22517. "cupcup;": "⩊",
  22518. "cupdot;": "⊍",
  22519. "curarr;": "↷",
  22520. "curren;": "¤",
  22521. "cylcty;": "⌭",
  22522. "Dagger;": "‡",
  22523. "dagger;": "†",
  22524. "daleth;": "ℸ",
  22525. "Dcaron;": "Ď",
  22526. "dcaron;": "ď",
  22527. "dfisht;": "⥿",
  22528. "divide;": "÷",
  22529. "divonx;": "⋇",
  22530. "dlcorn;": "⌞",
  22531. "dlcrop;": "⌍",
  22532. "dollar;": "$",
  22533. "DotDot;": "⃜",
  22534. "drcorn;": "⌟",
  22535. "drcrop;": "⌌",
  22536. "Dstrok;": "Đ",
  22537. "dstrok;": "đ",
  22538. "Eacute;": "É",
  22539. "eacute;": "é",
  22540. "easter;": "⩮",
  22541. "Ecaron;": "Ě",
  22542. "ecaron;": "ě",
  22543. "ecolon;": "≕",
  22544. "Egrave;": "È",
  22545. "egrave;": "è",
  22546. "egsdot;": "⪘",
  22547. "elsdot;": "⪗",
  22548. "emptyv;": "∅",
  22549. "emsp13;": " ",
  22550. "emsp14;": " ",
  22551. "eparsl;": "⧣",
  22552. "eqcirc;": "≖",
  22553. "equals;": "=",
  22554. "equest;": "≟",
  22555. "Exists;": "∃",
  22556. "female;": "♀",
  22557. "ffilig;": "ffi",
  22558. "ffllig;": "ffl",
  22559. "ForAll;": "∀",
  22560. "forall;": "∀",
  22561. "frac12;": "½",
  22562. "frac13;": "⅓",
  22563. "frac14;": "¼",
  22564. "frac15;": "⅕",
  22565. "frac16;": "⅙",
  22566. "frac18;": "⅛",
  22567. "frac23;": "⅔",
  22568. "frac25;": "⅖",
  22569. "frac34;": "¾",
  22570. "frac35;": "⅗",
  22571. "frac38;": "⅜",
  22572. "frac45;": "⅘",
  22573. "frac56;": "⅚",
  22574. "frac58;": "⅝",
  22575. "frac78;": "⅞",
  22576. "gacute;": "ǵ",
  22577. "Gammad;": "Ϝ",
  22578. "gammad;": "ϝ",
  22579. "Gbreve;": "Ğ",
  22580. "gbreve;": "ğ",
  22581. "Gcedil;": "Ģ",
  22582. "gesdot;": "⪀",
  22583. "gesles;": "⪔",
  22584. "gtlPar;": "⦕",
  22585. "gtrarr;": "⥸",
  22586. "gtrdot;": "⋗",
  22587. "gtrsim;": "≳",
  22588. "hairsp;": " ",
  22589. "hamilt;": "ℋ",
  22590. "HARDcy;": "Ъ",
  22591. "hardcy;": "ъ",
  22592. "hearts;": "♥",
  22593. "hellip;": "…",
  22594. "hercon;": "⊹",
  22595. "homtht;": "∻",
  22596. "horbar;": "―",
  22597. "hslash;": "ℏ",
  22598. "Hstrok;": "Ħ",
  22599. "hstrok;": "ħ",
  22600. "hybull;": "⁃",
  22601. "hyphen;": "‐",
  22602. "Iacute;": "Í",
  22603. "iacute;": "í",
  22604. "Igrave;": "Ì",
  22605. "igrave;": "ì",
  22606. "iiiint;": "⨌",
  22607. "iinfin;": "⧜",
  22608. "incare;": "℅",
  22609. "inodot;": "ı",
  22610. "intcal;": "⊺",
  22611. "iquest;": "¿",
  22612. "isinsv;": "⋳",
  22613. "Itilde;": "Ĩ",
  22614. "itilde;": "ĩ",
  22615. "Jsercy;": "Ј",
  22616. "jsercy;": "ј",
  22617. "kappav;": "ϰ",
  22618. "Kcedil;": "Ķ",
  22619. "kcedil;": "ķ",
  22620. "kgreen;": "ĸ",
  22621. "Lacute;": "Ĺ",
  22622. "lacute;": "ĺ",
  22623. "lagran;": "ℒ",
  22624. "Lambda;": "Λ",
  22625. "lambda;": "λ",
  22626. "langle;": "⟨",
  22627. "larrfs;": "⤝",
  22628. "larrhk;": "↩",
  22629. "larrlp;": "↫",
  22630. "larrpl;": "⤹",
  22631. "larrtl;": "↢",
  22632. "lAtail;": "⤛",
  22633. "latail;": "⤙",
  22634. "lbrace;": "{",
  22635. "lbrack;": "[",
  22636. "Lcaron;": "Ľ",
  22637. "lcaron;": "ľ",
  22638. "Lcedil;": "Ļ",
  22639. "lcedil;": "ļ",
  22640. "ldquor;": "„",
  22641. "lesdot;": "⩿",
  22642. "lesges;": "⪓",
  22643. "lfisht;": "⥼",
  22644. "lfloor;": "⌊",
  22645. "lharul;": "⥪",
  22646. "llhard;": "⥫",
  22647. "Lmidot;": "Ŀ",
  22648. "lmidot;": "ŀ",
  22649. "lmoust;": "⎰",
  22650. "loplus;": "⨭",
  22651. "lowast;": "∗",
  22652. "lowbar;": "_",
  22653. "lparlt;": "⦓",
  22654. "lrhard;": "⥭",
  22655. "lsaquo;": "‹",
  22656. "lsquor;": "‚",
  22657. "Lstrok;": "Ł",
  22658. "lstrok;": "ł",
  22659. "lthree;": "⋋",
  22660. "ltimes;": "⋉",
  22661. "ltlarr;": "⥶",
  22662. "ltrPar;": "⦖",
  22663. "mapsto;": "↦",
  22664. "marker;": "▮",
  22665. "mcomma;": "⨩",
  22666. "midast;": "*",
  22667. "midcir;": "⫰",
  22668. "middot;": "·",
  22669. "minusb;": "⊟",
  22670. "minusd;": "∸",
  22671. "mnplus;": "∓",
  22672. "models;": "⊧",
  22673. "mstpos;": "∾",
  22674. "Nacute;": "Ń",
  22675. "nacute;": "ń",
  22676. "nbumpe;": "≏̸",
  22677. "Ncaron;": "Ň",
  22678. "ncaron;": "ň",
  22679. "Ncedil;": "Ņ",
  22680. "ncedil;": "ņ",
  22681. "nearhk;": "⤤",
  22682. "nequiv;": "≢",
  22683. "nesear;": "⤨",
  22684. "nexist;": "∄",
  22685. "nltrie;": "⋬",
  22686. "notinE;": "⋹̸",
  22687. "nparsl;": "⫽⃥",
  22688. "nprcue;": "⋠",
  22689. "nrarrc;": "⤳̸",
  22690. "nrarrw;": "↝̸",
  22691. "nrtrie;": "⋭",
  22692. "nsccue;": "⋡",
  22693. "nsimeq;": "≄",
  22694. "Ntilde;": "Ñ",
  22695. "ntilde;": "ñ",
  22696. "numero;": "№",
  22697. "nVDash;": "⊯",
  22698. "nVdash;": "⊮",
  22699. "nvDash;": "⊭",
  22700. "nvdash;": "⊬",
  22701. "nvHarr;": "⤄",
  22702. "nvlArr;": "⤂",
  22703. "nvrArr;": "⤃",
  22704. "nwarhk;": "⤣",
  22705. "nwnear;": "⤧",
  22706. "Oacute;": "Ó",
  22707. "oacute;": "ó",
  22708. "Odblac;": "Ő",
  22709. "odblac;": "ő",
  22710. "odsold;": "⦼",
  22711. "Ograve;": "Ò",
  22712. "ograve;": "ò",
  22713. "ominus;": "⊖",
  22714. "origof;": "⊶",
  22715. "Oslash;": "Ø",
  22716. "oslash;": "ø",
  22717. "Otilde;": "Õ",
  22718. "otilde;": "õ",
  22719. "Otimes;": "⨷",
  22720. "otimes;": "⊗",
  22721. "parsim;": "⫳",
  22722. "percnt;": "%",
  22723. "period;": ".",
  22724. "permil;": "‰",
  22725. "phmmat;": "ℳ",
  22726. "planck;": "ℏ",
  22727. "plankv;": "ℏ",
  22728. "plusdo;": "∔",
  22729. "plusdu;": "⨥",
  22730. "plusmn;": "±",
  22731. "preceq;": "⪯",
  22732. "primes;": "ℙ",
  22733. "prnsim;": "⋨",
  22734. "propto;": "∝",
  22735. "prurel;": "⊰",
  22736. "puncsp;": " ",
  22737. "qprime;": "⁗",
  22738. "Racute;": "Ŕ",
  22739. "racute;": "ŕ",
  22740. "rangle;": "⟩",
  22741. "rarrap;": "⥵",
  22742. "rarrfs;": "⤞",
  22743. "rarrhk;": "↪",
  22744. "rarrlp;": "↬",
  22745. "rarrpl;": "⥅",
  22746. "Rarrtl;": "⤖",
  22747. "rarrtl;": "↣",
  22748. "rAtail;": "⤜",
  22749. "ratail;": "⤚",
  22750. "rbrace;": "}",
  22751. "rbrack;": "]",
  22752. "Rcaron;": "Ř",
  22753. "rcaron;": "ř",
  22754. "Rcedil;": "Ŗ",
  22755. "rcedil;": "ŗ",
  22756. "rdquor;": "”",
  22757. "rfisht;": "⥽",
  22758. "rfloor;": "⌋",
  22759. "rharul;": "⥬",
  22760. "rmoust;": "⎱",
  22761. "roplus;": "⨮",
  22762. "rpargt;": "⦔",
  22763. "rsaquo;": "›",
  22764. "rsquor;": "’",
  22765. "rthree;": "⋌",
  22766. "rtimes;": "⋊",
  22767. "Sacute;": "Ś",
  22768. "sacute;": "ś",
  22769. "Scaron;": "Š",
  22770. "scaron;": "š",
  22771. "Scedil;": "Ş",
  22772. "scedil;": "ş",
  22773. "scnsim;": "⋩",
  22774. "searhk;": "⤥",
  22775. "seswar;": "⤩",
  22776. "sfrown;": "⌢",
  22777. "SHCHcy;": "Щ",
  22778. "shchcy;": "щ",
  22779. "sigmaf;": "ς",
  22780. "sigmav;": "ς",
  22781. "simdot;": "⩪",
  22782. "smashp;": "⨳",
  22783. "SOFTcy;": "Ь",
  22784. "softcy;": "ь",
  22785. "solbar;": "⌿",
  22786. "spades;": "♠",
  22787. "sqcaps;": "⊓︀",
  22788. "sqcups;": "⊔︀",
  22789. "sqsube;": "⊑",
  22790. "sqsupe;": "⊒",
  22791. "Square;": "□",
  22792. "square;": "□",
  22793. "squarf;": "▪",
  22794. "ssetmn;": "∖",
  22795. "ssmile;": "⌣",
  22796. "sstarf;": "⋆",
  22797. "subdot;": "⪽",
  22798. "Subset;": "⋐",
  22799. "subset;": "⊂",
  22800. "subsim;": "⫇",
  22801. "subsub;": "⫕",
  22802. "subsup;": "⫓",
  22803. "succeq;": "⪰",
  22804. "supdot;": "⪾",
  22805. "Supset;": "⋑",
  22806. "supset;": "⊃",
  22807. "supsim;": "⫈",
  22808. "supsub;": "⫔",
  22809. "supsup;": "⫖",
  22810. "swarhk;": "⤦",
  22811. "swnwar;": "⤪",
  22812. "target;": "⌖",
  22813. "Tcaron;": "Ť",
  22814. "tcaron;": "ť",
  22815. "Tcedil;": "Ţ",
  22816. "tcedil;": "ţ",
  22817. "telrec;": "⌕",
  22818. "there4;": "∴",
  22819. "thetav;": "ϑ",
  22820. "thinsp;": " ",
  22821. "thksim;": "∼",
  22822. "timesb;": "⊠",
  22823. "timesd;": "⨰",
  22824. "topbot;": "⌶",
  22825. "topcir;": "⫱",
  22826. "tprime;": "‴",
  22827. "tridot;": "◬",
  22828. "Tstrok;": "Ŧ",
  22829. "tstrok;": "ŧ",
  22830. "Uacute;": "Ú",
  22831. "uacute;": "ú",
  22832. "Ubreve;": "Ŭ",
  22833. "ubreve;": "ŭ",
  22834. "Udblac;": "Ű",
  22835. "udblac;": "ű",
  22836. "ufisht;": "⥾",
  22837. "Ugrave;": "Ù",
  22838. "ugrave;": "ù",
  22839. "ulcorn;": "⌜",
  22840. "ulcrop;": "⌏",
  22841. "urcorn;": "⌝",
  22842. "urcrop;": "⌎",
  22843. "Utilde;": "Ũ",
  22844. "utilde;": "ũ",
  22845. "vangrt;": "⦜",
  22846. "varphi;": "ϕ",
  22847. "varrho;": "ϱ",
  22848. "Vdashl;": "⫦",
  22849. "veebar;": "⊻",
  22850. "vellip;": "⋮",
  22851. "Verbar;": "‖",
  22852. "verbar;": "|",
  22853. "vsubnE;": "⫋︀",
  22854. "vsubne;": "⊊︀",
  22855. "vsupnE;": "⫌︀",
  22856. "vsupne;": "⊋︀",
  22857. "Vvdash;": "⊪",
  22858. "wedbar;": "⩟",
  22859. "wedgeq;": "≙",
  22860. "weierp;": "℘",
  22861. "wreath;": "≀",
  22862. "xoplus;": "⨁",
  22863. "xotime;": "⨂",
  22864. "xsqcup;": "⨆",
  22865. "xuplus;": "⨄",
  22866. "xwedge;": "⋀",
  22867. "Yacute;": "Ý",
  22868. "yacute;": "ý",
  22869. "Zacute;": "Ź",
  22870. "zacute;": "ź",
  22871. "Zcaron;": "Ž",
  22872. "zcaron;": "ž",
  22873. "zeetrf;": "ℨ",
  22874. "alefsym;": "ℵ",
  22875. "angrtvb;": "⊾",
  22876. "angzarr;": "⍼",
  22877. "asympeq;": "≍",
  22878. "backsim;": "∽",
  22879. "Because;": "∵",
  22880. "because;": "∵",
  22881. "bemptyv;": "⦰",
  22882. "between;": "≬",
  22883. "bigcirc;": "◯",
  22884. "bigodot;": "⨀",
  22885. "bigstar;": "★",
  22886. "bnequiv;": "≡⃥",
  22887. "boxplus;": "⊞",
  22888. "Cayleys;": "ℭ",
  22889. "Cconint;": "∰",
  22890. "ccupssm;": "⩐",
  22891. "Cedilla;": "¸",
  22892. "cemptyv;": "⦲",
  22893. "cirscir;": "⧂",
  22894. "coloneq;": "≔",
  22895. "congdot;": "⩭",
  22896. "cudarrl;": "⤸",
  22897. "cudarrr;": "⤵",
  22898. "cularrp;": "⤽",
  22899. "curarrm;": "⤼",
  22900. "dbkarow;": "⤏",
  22901. "ddagger;": "‡",
  22902. "ddotseq;": "⩷",
  22903. "demptyv;": "⦱",
  22904. "Diamond;": "⋄",
  22905. "diamond;": "⋄",
  22906. "digamma;": "ϝ",
  22907. "dotplus;": "∔",
  22908. "DownTee;": "⊤",
  22909. "dwangle;": "⦦",
  22910. "Element;": "∈",
  22911. "Epsilon;": "Ε",
  22912. "epsilon;": "ε",
  22913. "eqcolon;": "≕",
  22914. "equivDD;": "⩸",
  22915. "gesdoto;": "⪂",
  22916. "gtquest;": "⩼",
  22917. "gtrless;": "≷",
  22918. "harrcir;": "⥈",
  22919. "Implies;": "⇒",
  22920. "intprod;": "⨼",
  22921. "isindot;": "⋵",
  22922. "larrbfs;": "⤟",
  22923. "larrsim;": "⥳",
  22924. "lbrksld;": "⦏",
  22925. "lbrkslu;": "⦍",
  22926. "ldrdhar;": "⥧",
  22927. "LeftTee;": "⊣",
  22928. "lesdoto;": "⪁",
  22929. "lessdot;": "⋖",
  22930. "lessgtr;": "≶",
  22931. "lesssim;": "≲",
  22932. "lotimes;": "⨴",
  22933. "lozenge;": "◊",
  22934. "ltquest;": "⩻",
  22935. "luruhar;": "⥦",
  22936. "maltese;": "✠",
  22937. "minusdu;": "⨪",
  22938. "napprox;": "≉",
  22939. "natural;": "♮",
  22940. "nearrow;": "↗",
  22941. "NewLine;": "\n",
  22942. "nexists;": "∄",
  22943. "NoBreak;": "⁠",
  22944. "notinva;": "∉",
  22945. "notinvb;": "⋷",
  22946. "notinvc;": "⋶",
  22947. "NotLess;": "≮",
  22948. "notniva;": "∌",
  22949. "notnivb;": "⋾",
  22950. "notnivc;": "⋽",
  22951. "npolint;": "⨔",
  22952. "npreceq;": "⪯̸",
  22953. "nsqsube;": "⋢",
  22954. "nsqsupe;": "⋣",
  22955. "nsubset;": "⊂⃒",
  22956. "nsucceq;": "⪰̸",
  22957. "nsupset;": "⊃⃒",
  22958. "nvinfin;": "⧞",
  22959. "nvltrie;": "⊴⃒",
  22960. "nvrtrie;": "⊵⃒",
  22961. "nwarrow;": "↖",
  22962. "olcross;": "⦻",
  22963. "Omicron;": "Ο",
  22964. "omicron;": "ο",
  22965. "orderof;": "ℴ",
  22966. "orslope;": "⩗",
  22967. "OverBar;": "‾",
  22968. "pertenk;": "‱",
  22969. "planckh;": "ℎ",
  22970. "pluscir;": "⨢",
  22971. "plussim;": "⨦",
  22972. "plustwo;": "⨧",
  22973. "precsim;": "≾",
  22974. "Product;": "∏",
  22975. "quatint;": "⨖",
  22976. "questeq;": "≟",
  22977. "rarrbfs;": "⤠",
  22978. "rarrsim;": "⥴",
  22979. "rbrksld;": "⦎",
  22980. "rbrkslu;": "⦐",
  22981. "rdldhar;": "⥩",
  22982. "realine;": "ℛ",
  22983. "rotimes;": "⨵",
  22984. "ruluhar;": "⥨",
  22985. "searrow;": "↘",
  22986. "simplus;": "⨤",
  22987. "simrarr;": "⥲",
  22988. "subedot;": "⫃",
  22989. "submult;": "⫁",
  22990. "subplus;": "⪿",
  22991. "subrarr;": "⥹",
  22992. "succsim;": "≿",
  22993. "supdsub;": "⫘",
  22994. "supedot;": "⫄",
  22995. "suphsol;": "⟉",
  22996. "suphsub;": "⫗",
  22997. "suplarr;": "⥻",
  22998. "supmult;": "⫂",
  22999. "supplus;": "⫀",
  23000. "swarrow;": "↙",
  23001. "topfork;": "⫚",
  23002. "triplus;": "⨹",
  23003. "tritime;": "⨻",
  23004. "UpArrow;": "↑",
  23005. "Uparrow;": "⇑",
  23006. "uparrow;": "↑",
  23007. "Upsilon;": "Υ",
  23008. "upsilon;": "υ",
  23009. "uwangle;": "⦧",
  23010. "vzigzag;": "⦚",
  23011. "zigrarr;": "⇝",
  23012. "andslope;": "⩘",
  23013. "angmsdaa;": "⦨",
  23014. "angmsdab;": "⦩",
  23015. "angmsdac;": "⦪",
  23016. "angmsdad;": "⦫",
  23017. "angmsdae;": "⦬",
  23018. "angmsdaf;": "⦭",
  23019. "angmsdag;": "⦮",
  23020. "angmsdah;": "⦯",
  23021. "angrtvbd;": "⦝",
  23022. "approxeq;": "≊",
  23023. "awconint;": "∳",
  23024. "backcong;": "≌",
  23025. "barwedge;": "⌅",
  23026. "bbrktbrk;": "⎶",
  23027. "bigoplus;": "⨁",
  23028. "bigsqcup;": "⨆",
  23029. "biguplus;": "⨄",
  23030. "bigwedge;": "⋀",
  23031. "boxminus;": "⊟",
  23032. "boxtimes;": "⊠",
  23033. "bsolhsub;": "⟈",
  23034. "capbrcup;": "⩉",
  23035. "circledR;": "®",
  23036. "circledS;": "Ⓢ",
  23037. "cirfnint;": "⨐",
  23038. "clubsuit;": "♣",
  23039. "cupbrcap;": "⩈",
  23040. "curlyvee;": "⋎",
  23041. "cwconint;": "∲",
  23042. "DDotrahd;": "⤑",
  23043. "doteqdot;": "≑",
  23044. "DotEqual;": "≐",
  23045. "dotminus;": "∸",
  23046. "drbkarow;": "⤐",
  23047. "dzigrarr;": "⟿",
  23048. "elinters;": "⏧",
  23049. "emptyset;": "∅",
  23050. "eqvparsl;": "⧥",
  23051. "fpartint;": "⨍",
  23052. "geqslant;": "⩾",
  23053. "gesdotol;": "⪄",
  23054. "gnapprox;": "⪊",
  23055. "hksearow;": "⤥",
  23056. "hkswarow;": "⤦",
  23057. "imagline;": "ℐ",
  23058. "imagpart;": "ℑ",
  23059. "infintie;": "⧝",
  23060. "integers;": "ℤ",
  23061. "Integral;": "∫",
  23062. "intercal;": "⊺",
  23063. "intlarhk;": "⨗",
  23064. "laemptyv;": "⦴",
  23065. "ldrushar;": "⥋",
  23066. "leqslant;": "⩽",
  23067. "lesdotor;": "⪃",
  23068. "LessLess;": "⪡",
  23069. "llcorner;": "⌞",
  23070. "lnapprox;": "⪉",
  23071. "lrcorner;": "⌟",
  23072. "lurdshar;": "⥊",
  23073. "mapstoup;": "↥",
  23074. "multimap;": "⊸",
  23075. "naturals;": "ℕ",
  23076. "ncongdot;": "⩭̸",
  23077. "NotEqual;": "≠",
  23078. "notindot;": "⋵̸",
  23079. "NotTilde;": "≁",
  23080. "otimesas;": "⨶",
  23081. "parallel;": "∥",
  23082. "PartialD;": "∂",
  23083. "plusacir;": "⨣",
  23084. "pointint;": "⨕",
  23085. "Precedes;": "≺",
  23086. "precneqq;": "⪵",
  23087. "precnsim;": "⋨",
  23088. "profalar;": "⌮",
  23089. "profline;": "⌒",
  23090. "profsurf;": "⌓",
  23091. "raemptyv;": "⦳",
  23092. "realpart;": "ℜ",
  23093. "RightTee;": "⊢",
  23094. "rppolint;": "⨒",
  23095. "rtriltri;": "⧎",
  23096. "scpolint;": "⨓",
  23097. "setminus;": "∖",
  23098. "shortmid;": "∣",
  23099. "smeparsl;": "⧤",
  23100. "sqsubset;": "⊏",
  23101. "sqsupset;": "⊐",
  23102. "subseteq;": "⊆",
  23103. "Succeeds;": "≻",
  23104. "succneqq;": "⪶",
  23105. "succnsim;": "⋩",
  23106. "SuchThat;": "∋",
  23107. "Superset;": "⊃",
  23108. "supseteq;": "⊇",
  23109. "thetasym;": "ϑ",
  23110. "thicksim;": "∼",
  23111. "timesbar;": "⨱",
  23112. "triangle;": "▵",
  23113. "triminus;": "⨺",
  23114. "trpezium;": "⏢",
  23115. "Uarrocir;": "⥉",
  23116. "ulcorner;": "⌜",
  23117. "UnderBar;": "_",
  23118. "urcorner;": "⌝",
  23119. "varkappa;": "ϰ",
  23120. "varsigma;": "ς",
  23121. "vartheta;": "ϑ",
  23122. "backprime;": "‵",
  23123. "backsimeq;": "⋍",
  23124. "Backslash;": "∖",
  23125. "bigotimes;": "⨂",
  23126. "CenterDot;": "·",
  23127. "centerdot;": "·",
  23128. "checkmark;": "✓",
  23129. "CircleDot;": "⊙",
  23130. "complexes;": "ℂ",
  23131. "Congruent;": "≡",
  23132. "Coproduct;": "∐",
  23133. "dotsquare;": "⊡",
  23134. "DoubleDot;": "¨",
  23135. "DownArrow;": "↓",
  23136. "Downarrow;": "⇓",
  23137. "downarrow;": "↓",
  23138. "DownBreve;": "̑",
  23139. "gtrapprox;": "⪆",
  23140. "gtreqless;": "⋛",
  23141. "gvertneqq;": "≩︀",
  23142. "heartsuit;": "♥",
  23143. "HumpEqual;": "≏",
  23144. "LeftArrow;": "←",
  23145. "Leftarrow;": "⇐",
  23146. "leftarrow;": "←",
  23147. "LeftFloor;": "⌊",
  23148. "lesseqgtr;": "⋚",
  23149. "LessTilde;": "≲",
  23150. "lvertneqq;": "≨︀",
  23151. "Mellintrf;": "ℳ",
  23152. "MinusPlus;": "∓",
  23153. "ngeqslant;": "⩾̸",
  23154. "nleqslant;": "⩽̸",
  23155. "NotCupCap;": "≭",
  23156. "NotExists;": "∄",
  23157. "NotSubset;": "⊂⃒",
  23158. "nparallel;": "∦",
  23159. "nshortmid;": "∤",
  23160. "nsubseteq;": "⊈",
  23161. "nsupseteq;": "⊉",
  23162. "OverBrace;": "⏞",
  23163. "pitchfork;": "⋔",
  23164. "PlusMinus;": "±",
  23165. "rationals;": "ℚ",
  23166. "spadesuit;": "♠",
  23167. "subseteqq;": "⫅",
  23168. "subsetneq;": "⊊",
  23169. "supseteqq;": "⫆",
  23170. "supsetneq;": "⊋",
  23171. "Therefore;": "∴",
  23172. "therefore;": "∴",
  23173. "ThinSpace;": " ",
  23174. "triangleq;": "≜",
  23175. "TripleDot;": "⃛",
  23176. "UnionPlus;": "⊎",
  23177. "varpropto;": "∝",
  23178. "Bernoullis;": "ℬ",
  23179. "circledast;": "⊛",
  23180. "CirclePlus;": "⊕",
  23181. "complement;": "∁",
  23182. "curlywedge;": "⋏",
  23183. "eqslantgtr;": "⪖",
  23184. "EqualTilde;": "≂",
  23185. "Fouriertrf;": "ℱ",
  23186. "gtreqqless;": "⪌",
  23187. "ImaginaryI;": "ⅈ",
  23188. "Laplacetrf;": "ℒ",
  23189. "LeftVector;": "↼",
  23190. "lessapprox;": "⪅",
  23191. "lesseqqgtr;": "⪋",
  23192. "Lleftarrow;": "⇚",
  23193. "lmoustache;": "⎰",
  23194. "longmapsto;": "⟼",
  23195. "mapstodown;": "↧",
  23196. "mapstoleft;": "↤",
  23197. "nLeftarrow;": "⇍",
  23198. "nleftarrow;": "↚",
  23199. "NotElement;": "∉",
  23200. "NotGreater;": "≯",
  23201. "nsubseteqq;": "⫅̸",
  23202. "nsupseteqq;": "⫆̸",
  23203. "precapprox;": "⪷",
  23204. "Proportion;": "∷",
  23205. "RightArrow;": "→",
  23206. "Rightarrow;": "⇒",
  23207. "rightarrow;": "→",
  23208. "RightFloor;": "⌋",
  23209. "rmoustache;": "⎱",
  23210. "sqsubseteq;": "⊑",
  23211. "sqsupseteq;": "⊒",
  23212. "subsetneqq;": "⫋",
  23213. "succapprox;": "⪸",
  23214. "supsetneqq;": "⫌",
  23215. "ThickSpace;": "  ",
  23216. "TildeEqual;": "≃",
  23217. "TildeTilde;": "≈",
  23218. "UnderBrace;": "⏟",
  23219. "UpArrowBar;": "⤒",
  23220. "UpTeeArrow;": "↥",
  23221. "upuparrows;": "⇈",
  23222. "varepsilon;": "ϵ",
  23223. "varnothing;": "∅",
  23224. "backepsilon;": "϶",
  23225. "blacksquare;": "▪",
  23226. "circledcirc;": "⊚",
  23227. "circleddash;": "⊝",
  23228. "CircleMinus;": "⊖",
  23229. "CircleTimes;": "⊗",
  23230. "curlyeqprec;": "⋞",
  23231. "curlyeqsucc;": "⋟",
  23232. "diamondsuit;": "♦",
  23233. "eqslantless;": "⪕",
  23234. "Equilibrium;": "⇌",
  23235. "expectation;": "ℰ",
  23236. "GreaterLess;": "≷",
  23237. "LeftCeiling;": "⌈",
  23238. "LessGreater;": "≶",
  23239. "MediumSpace;": " ",
  23240. "NotLessLess;": "≪̸",
  23241. "NotPrecedes;": "⊀",
  23242. "NotSucceeds;": "⊁",
  23243. "NotSuperset;": "⊃⃒",
  23244. "nRightarrow;": "⇏",
  23245. "nrightarrow;": "↛",
  23246. "OverBracket;": "⎴",
  23247. "preccurlyeq;": "≼",
  23248. "precnapprox;": "⪹",
  23249. "quaternions;": "ℍ",
  23250. "RightVector;": "⇀",
  23251. "Rrightarrow;": "⇛",
  23252. "RuleDelayed;": "⧴",
  23253. "SmallCircle;": "∘",
  23254. "SquareUnion;": "⊔",
  23255. "straightphi;": "ϕ",
  23256. "SubsetEqual;": "⊆",
  23257. "succcurlyeq;": "≽",
  23258. "succnapprox;": "⪺",
  23259. "thickapprox;": "≈",
  23260. "UpDownArrow;": "↕",
  23261. "Updownarrow;": "⇕",
  23262. "updownarrow;": "↕",
  23263. "VerticalBar;": "∣",
  23264. "blacklozenge;": "⧫",
  23265. "DownArrowBar;": "⤓",
  23266. "DownTeeArrow;": "↧",
  23267. "ExponentialE;": "ⅇ",
  23268. "exponentiale;": "ⅇ",
  23269. "GreaterEqual;": "≥",
  23270. "GreaterTilde;": "≳",
  23271. "HilbertSpace;": "ℋ",
  23272. "HumpDownHump;": "≎",
  23273. "Intersection;": "⋂",
  23274. "LeftArrowBar;": "⇤",
  23275. "LeftTeeArrow;": "↤",
  23276. "LeftTriangle;": "⊲",
  23277. "LeftUpVector;": "↿",
  23278. "NotCongruent;": "≢",
  23279. "NotHumpEqual;": "≏̸",
  23280. "NotLessEqual;": "≰",
  23281. "NotLessTilde;": "≴",
  23282. "Proportional;": "∝",
  23283. "RightCeiling;": "⌉",
  23284. "risingdotseq;": "≓",
  23285. "RoundImplies;": "⥰",
  23286. "ShortUpArrow;": "↑",
  23287. "SquareSubset;": "⊏",
  23288. "triangledown;": "▿",
  23289. "triangleleft;": "◃",
  23290. "UnderBracket;": "⎵",
  23291. "varsubsetneq;": "⊊︀",
  23292. "varsupsetneq;": "⊋︀",
  23293. "VerticalLine;": "|",
  23294. "ApplyFunction;": "⁡",
  23295. "bigtriangleup;": "△",
  23296. "blacktriangle;": "▴",
  23297. "DifferentialD;": "ⅆ",
  23298. "divideontimes;": "⋇",
  23299. "DoubleLeftTee;": "⫤",
  23300. "DoubleUpArrow;": "⇑",
  23301. "fallingdotseq;": "≒",
  23302. "hookleftarrow;": "↩",
  23303. "leftarrowtail;": "↢",
  23304. "leftharpoonup;": "↼",
  23305. "LeftTeeVector;": "⥚",
  23306. "LeftVectorBar;": "⥒",
  23307. "LessFullEqual;": "≦",
  23308. "LongLeftArrow;": "⟵",
  23309. "Longleftarrow;": "⟸",
  23310. "longleftarrow;": "⟵",
  23311. "looparrowleft;": "↫",
  23312. "measuredangle;": "∡",
  23313. "NotEqualTilde;": "≂̸",
  23314. "NotTildeEqual;": "≄",
  23315. "NotTildeTilde;": "≉",
  23316. "ntriangleleft;": "⋪",
  23317. "Poincareplane;": "ℌ",
  23318. "PrecedesEqual;": "⪯",
  23319. "PrecedesTilde;": "≾",
  23320. "RightArrowBar;": "⇥",
  23321. "RightTeeArrow;": "↦",
  23322. "RightTriangle;": "⊳",
  23323. "RightUpVector;": "↾",
  23324. "shortparallel;": "∥",
  23325. "smallsetminus;": "∖",
  23326. "SucceedsEqual;": "⪰",
  23327. "SucceedsTilde;": "≿",
  23328. "SupersetEqual;": "⊇",
  23329. "triangleright;": "▹",
  23330. "UpEquilibrium;": "⥮",
  23331. "upharpoonleft;": "↿",
  23332. "varsubsetneqq;": "⫋︀",
  23333. "varsupsetneqq;": "⫌︀",
  23334. "VerticalTilde;": "≀",
  23335. "VeryThinSpace;": " ",
  23336. "curvearrowleft;": "↶",
  23337. "DiacriticalDot;": "˙",
  23338. "doublebarwedge;": "⌆",
  23339. "DoubleRightTee;": "⊨",
  23340. "downdownarrows;": "⇊",
  23341. "DownLeftVector;": "↽",
  23342. "GreaterGreater;": "⪢",
  23343. "hookrightarrow;": "↪",
  23344. "HorizontalLine;": "─",
  23345. "InvisibleComma;": "⁣",
  23346. "InvisibleTimes;": "⁢",
  23347. "LeftDownVector;": "⇃",
  23348. "leftleftarrows;": "⇇",
  23349. "LeftRightArrow;": "↔",
  23350. "Leftrightarrow;": "⇔",
  23351. "leftrightarrow;": "↔",
  23352. "leftthreetimes;": "⋋",
  23353. "LessSlantEqual;": "⩽",
  23354. "LongRightArrow;": "⟶",
  23355. "Longrightarrow;": "⟹",
  23356. "longrightarrow;": "⟶",
  23357. "looparrowright;": "↬",
  23358. "LowerLeftArrow;": "↙",
  23359. "NestedLessLess;": "≪",
  23360. "NotGreaterLess;": "≹",
  23361. "NotLessGreater;": "≸",
  23362. "NotSubsetEqual;": "⊈",
  23363. "NotVerticalBar;": "∤",
  23364. "nshortparallel;": "∦",
  23365. "ntriangleright;": "⋫",
  23366. "OpenCurlyQuote;": "‘",
  23367. "ReverseElement;": "∋",
  23368. "rightarrowtail;": "↣",
  23369. "rightharpoonup;": "⇀",
  23370. "RightTeeVector;": "⥛",
  23371. "RightVectorBar;": "⥓",
  23372. "ShortDownArrow;": "↓",
  23373. "ShortLeftArrow;": "←",
  23374. "SquareSuperset;": "⊐",
  23375. "TildeFullEqual;": "≅",
  23376. "trianglelefteq;": "⊴",
  23377. "upharpoonright;": "↾",
  23378. "UpperLeftArrow;": "↖",
  23379. "ZeroWidthSpace;": "​",
  23380. "bigtriangledown;": "▽",
  23381. "circlearrowleft;": "↺",
  23382. "CloseCurlyQuote;": "’",
  23383. "ContourIntegral;": "∮",
  23384. "curvearrowright;": "↷",
  23385. "DoubleDownArrow;": "⇓",
  23386. "DoubleLeftArrow;": "⇐",
  23387. "downharpoonleft;": "⇃",
  23388. "DownRightVector;": "⇁",
  23389. "leftharpoondown;": "↽",
  23390. "leftrightarrows;": "⇆",
  23391. "LeftRightVector;": "⥎",
  23392. "LeftTriangleBar;": "⧏",
  23393. "LeftUpTeeVector;": "⥠",
  23394. "LeftUpVectorBar;": "⥘",
  23395. "LowerRightArrow;": "↘",
  23396. "nLeftrightarrow;": "⇎",
  23397. "nleftrightarrow;": "↮",
  23398. "NotGreaterEqual;": "≱",
  23399. "NotGreaterTilde;": "≵",
  23400. "NotHumpDownHump;": "≎̸",
  23401. "NotLeftTriangle;": "⋪",
  23402. "NotSquareSubset;": "⊏̸",
  23403. "ntrianglelefteq;": "⋬",
  23404. "OverParenthesis;": "⏜",
  23405. "RightDownVector;": "⇂",
  23406. "rightleftarrows;": "⇄",
  23407. "rightsquigarrow;": "↝",
  23408. "rightthreetimes;": "⋌",
  23409. "ShortRightArrow;": "→",
  23410. "straightepsilon;": "ϵ",
  23411. "trianglerighteq;": "⊵",
  23412. "UpperRightArrow;": "↗",
  23413. "vartriangleleft;": "⊲",
  23414. "circlearrowright;": "↻",
  23415. "DiacriticalAcute;": "´",
  23416. "DiacriticalGrave;": "`",
  23417. "DiacriticalTilde;": "˜",
  23418. "DoubleRightArrow;": "⇒",
  23419. "DownArrowUpArrow;": "⇵",
  23420. "downharpoonright;": "⇂",
  23421. "EmptySmallSquare;": "◻",
  23422. "GreaterEqualLess;": "⋛",
  23423. "GreaterFullEqual;": "≧",
  23424. "LeftAngleBracket;": "⟨",
  23425. "LeftUpDownVector;": "⥑",
  23426. "LessEqualGreater;": "⋚",
  23427. "NonBreakingSpace;": " ",
  23428. "NotPrecedesEqual;": "⪯̸",
  23429. "NotRightTriangle;": "⋫",
  23430. "NotSucceedsEqual;": "⪰̸",
  23431. "NotSucceedsTilde;": "≿̸",
  23432. "NotSupersetEqual;": "⊉",
  23433. "ntrianglerighteq;": "⋭",
  23434. "rightharpoondown;": "⇁",
  23435. "rightrightarrows;": "⇉",
  23436. "RightTriangleBar;": "⧐",
  23437. "RightUpTeeVector;": "⥜",
  23438. "RightUpVectorBar;": "⥔",
  23439. "twoheadleftarrow;": "↞",
  23440. "UnderParenthesis;": "⏝",
  23441. "UpArrowDownArrow;": "⇅",
  23442. "vartriangleright;": "⊳",
  23443. "blacktriangledown;": "▾",
  23444. "blacktriangleleft;": "◂",
  23445. "DoubleUpDownArrow;": "⇕",
  23446. "DoubleVerticalBar;": "∥",
  23447. "DownLeftTeeVector;": "⥞",
  23448. "DownLeftVectorBar;": "⥖",
  23449. "FilledSmallSquare;": "◼",
  23450. "GreaterSlantEqual;": "⩾",
  23451. "LeftDoubleBracket;": "⟦",
  23452. "LeftDownTeeVector;": "⥡",
  23453. "LeftDownVectorBar;": "⥙",
  23454. "leftrightharpoons;": "⇋",
  23455. "LeftTriangleEqual;": "⊴",
  23456. "NegativeThinSpace;": "​",
  23457. "NotGreaterGreater;": "≫̸",
  23458. "NotLessSlantEqual;": "⩽̸",
  23459. "NotNestedLessLess;": "⪡̸",
  23460. "NotReverseElement;": "∌",
  23461. "NotSquareSuperset;": "⊐̸",
  23462. "NotTildeFullEqual;": "≇",
  23463. "RightAngleBracket;": "⟩",
  23464. "rightleftharpoons;": "⇌",
  23465. "RightUpDownVector;": "⥏",
  23466. "SquareSubsetEqual;": "⊑",
  23467. "twoheadrightarrow;": "↠",
  23468. "VerticalSeparator;": "❘",
  23469. "blacktriangleright;": "▸",
  23470. "DownRightTeeVector;": "⥟",
  23471. "DownRightVectorBar;": "⥗",
  23472. "LongLeftRightArrow;": "⟷",
  23473. "Longleftrightarrow;": "⟺",
  23474. "longleftrightarrow;": "⟷",
  23475. "NegativeThickSpace;": "​",
  23476. "NotLeftTriangleBar;": "⧏̸",
  23477. "PrecedesSlantEqual;": "≼",
  23478. "ReverseEquilibrium;": "⇋",
  23479. "RightDoubleBracket;": "⟧",
  23480. "RightDownTeeVector;": "⥝",
  23481. "RightDownVectorBar;": "⥕",
  23482. "RightTriangleEqual;": "⊵",
  23483. "SquareIntersection;": "⊓",
  23484. "SucceedsSlantEqual;": "≽",
  23485. "DoubleLongLeftArrow;": "⟸",
  23486. "DownLeftRightVector;": "⥐",
  23487. "LeftArrowRightArrow;": "⇆",
  23488. "leftrightsquigarrow;": "↭",
  23489. "NegativeMediumSpace;": "​",
  23490. "NotGreaterFullEqual;": "≧̸",
  23491. "NotRightTriangleBar;": "⧐̸",
  23492. "RightArrowLeftArrow;": "⇄",
  23493. "SquareSupersetEqual;": "⊒",
  23494. "CapitalDifferentialD;": "ⅅ",
  23495. "DoubleLeftRightArrow;": "⇔",
  23496. "DoubleLongRightArrow;": "⟹",
  23497. "EmptyVerySmallSquare;": "▫",
  23498. "NestedGreaterGreater;": "≫",
  23499. "NotDoubleVerticalBar;": "∦",
  23500. "NotGreaterSlantEqual;": "⩾̸",
  23501. "NotLeftTriangleEqual;": "⋬",
  23502. "NotSquareSubsetEqual;": "⋢",
  23503. "OpenCurlyDoubleQuote;": "“",
  23504. "ReverseUpEquilibrium;": "⥯",
  23505. "CloseCurlyDoubleQuote;": "”",
  23506. "DoubleContourIntegral;": "∯",
  23507. "FilledVerySmallSquare;": "▪",
  23508. "NegativeVeryThinSpace;": "​",
  23509. "NotPrecedesSlantEqual;": "⋠",
  23510. "NotRightTriangleEqual;": "⋭",
  23511. "NotSucceedsSlantEqual;": "⋡",
  23512. "DiacriticalDoubleAcute;": "˝",
  23513. "NotSquareSupersetEqual;": "⋣",
  23514. "NotNestedGreaterGreater;": "⪢̸",
  23515. "ClockwiseContourIntegral;": "∲",
  23516. "DoubleLongLeftRightArrow;": "⟺",
  23517. "CounterClockwiseContourIntegral;": "∳"
  23518. };
  23519. // lazy compute this to make this file tree-shakable for browser
  23520. let maxCRNameLength;
  23521. const decodeHtml = (rawText, asAttr) => {
  23522. let offset = 0;
  23523. const end = rawText.length;
  23524. let decodedText = '';
  23525. function advance(length) {
  23526. offset += length;
  23527. rawText = rawText.slice(length);
  23528. }
  23529. while (offset < end) {
  23530. const head = /&(?:#x?)?/i.exec(rawText);
  23531. if (!head || offset + head.index >= end) {
  23532. const remaining = end - offset;
  23533. decodedText += rawText.slice(0, remaining);
  23534. advance(remaining);
  23535. break;
  23536. }
  23537. // Advance to the "&".
  23538. decodedText += rawText.slice(0, head.index);
  23539. advance(head.index);
  23540. if (head[0] === '&') {
  23541. // Named character reference.
  23542. let name = '';
  23543. let value = undefined;
  23544. if (/[0-9a-z]/i.test(rawText[1])) {
  23545. if (!maxCRNameLength) {
  23546. maxCRNameLength = Object.keys(namedCharacterReferences).reduce((max, name) => Math.max(max, name.length), 0);
  23547. }
  23548. for (let length = maxCRNameLength; !value && length > 0; --length) {
  23549. name = rawText.slice(1, 1 + length);
  23550. value = namedCharacterReferences[name];
  23551. }
  23552. if (value) {
  23553. const semi = name.endsWith(';');
  23554. if (asAttr &&
  23555. !semi &&
  23556. /[=a-z0-9]/i.test(rawText[name.length + 1] || '')) {
  23557. decodedText += '&' + name;
  23558. advance(1 + name.length);
  23559. }
  23560. else {
  23561. decodedText += value;
  23562. advance(1 + name.length);
  23563. }
  23564. }
  23565. else {
  23566. decodedText += '&' + name;
  23567. advance(1 + name.length);
  23568. }
  23569. }
  23570. else {
  23571. decodedText += '&';
  23572. advance(1);
  23573. }
  23574. }
  23575. else {
  23576. // Numeric character reference.
  23577. const hex = head[0] === '&#x';
  23578. const pattern = hex ? /^&#x([0-9a-f]+);?/i : /^&#([0-9]+);?/;
  23579. const body = pattern.exec(rawText);
  23580. if (!body) {
  23581. decodedText += head[0];
  23582. advance(head[0].length);
  23583. }
  23584. else {
  23585. // https://html.spec.whatwg.org/multipage/parsing.html#numeric-character-reference-end-state
  23586. let cp = Number.parseInt(body[1], hex ? 16 : 10);
  23587. if (cp === 0) {
  23588. cp = 0xfffd;
  23589. }
  23590. else if (cp > 0x10ffff) {
  23591. cp = 0xfffd;
  23592. }
  23593. else if (cp >= 0xd800 && cp <= 0xdfff) {
  23594. cp = 0xfffd;
  23595. }
  23596. else if ((cp >= 0xfdd0 && cp <= 0xfdef) || (cp & 0xfffe) === 0xfffe) ;
  23597. else if ((cp >= 0x01 && cp <= 0x08) ||
  23598. cp === 0x0b ||
  23599. (cp >= 0x0d && cp <= 0x1f) ||
  23600. (cp >= 0x7f && cp <= 0x9f)) {
  23601. cp = CCR_REPLACEMENTS[cp] || cp;
  23602. }
  23603. decodedText += String.fromCodePoint(cp);
  23604. advance(body[0].length);
  23605. }
  23606. }
  23607. }
  23608. return decodedText;
  23609. };
  23610. // https://html.spec.whatwg.org/multipage/parsing.html#numeric-character-reference-end-state
  23611. const CCR_REPLACEMENTS = {
  23612. 0x80: 0x20ac,
  23613. 0x82: 0x201a,
  23614. 0x83: 0x0192,
  23615. 0x84: 0x201e,
  23616. 0x85: 0x2026,
  23617. 0x86: 0x2020,
  23618. 0x87: 0x2021,
  23619. 0x88: 0x02c6,
  23620. 0x89: 0x2030,
  23621. 0x8a: 0x0160,
  23622. 0x8b: 0x2039,
  23623. 0x8c: 0x0152,
  23624. 0x8e: 0x017d,
  23625. 0x91: 0x2018,
  23626. 0x92: 0x2019,
  23627. 0x93: 0x201c,
  23628. 0x94: 0x201d,
  23629. 0x95: 0x2022,
  23630. 0x96: 0x2013,
  23631. 0x97: 0x2014,
  23632. 0x98: 0x02dc,
  23633. 0x99: 0x2122,
  23634. 0x9a: 0x0161,
  23635. 0x9b: 0x203a,
  23636. 0x9c: 0x0153,
  23637. 0x9e: 0x017e,
  23638. 0x9f: 0x0178
  23639. };
  23640. const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
  23641. const parserOptions = {
  23642. isVoidTag,
  23643. isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
  23644. isPreTag: tag => tag === 'pre',
  23645. decodeEntities: decodeHtml,
  23646. isBuiltInComponent: (tag) => {
  23647. if (isBuiltInType(tag, `Transition`)) {
  23648. return TRANSITION;
  23649. }
  23650. else if (isBuiltInType(tag, `TransitionGroup`)) {
  23651. return TRANSITION_GROUP;
  23652. }
  23653. },
  23654. // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
  23655. getNamespace(tag, parent) {
  23656. let ns = parent ? parent.ns : 0 /* DOMNamespaces.HTML */;
  23657. if (parent && ns === 2 /* DOMNamespaces.MATH_ML */) {
  23658. if (parent.tag === 'annotation-xml') {
  23659. if (tag === 'svg') {
  23660. return 1 /* DOMNamespaces.SVG */;
  23661. }
  23662. if (parent.props.some(a => a.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  23663. a.name === 'encoding' &&
  23664. a.value != null &&
  23665. (a.value.content === 'text/html' ||
  23666. a.value.content === 'application/xhtml+xml'))) {
  23667. ns = 0 /* DOMNamespaces.HTML */;
  23668. }
  23669. }
  23670. else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
  23671. tag !== 'mglyph' &&
  23672. tag !== 'malignmark') {
  23673. ns = 0 /* DOMNamespaces.HTML */;
  23674. }
  23675. }
  23676. else if (parent && ns === 1 /* DOMNamespaces.SVG */) {
  23677. if (parent.tag === 'foreignObject' ||
  23678. parent.tag === 'desc' ||
  23679. parent.tag === 'title') {
  23680. ns = 0 /* DOMNamespaces.HTML */;
  23681. }
  23682. }
  23683. if (ns === 0 /* DOMNamespaces.HTML */) {
  23684. if (tag === 'svg') {
  23685. return 1 /* DOMNamespaces.SVG */;
  23686. }
  23687. if (tag === 'math') {
  23688. return 2 /* DOMNamespaces.MATH_ML */;
  23689. }
  23690. }
  23691. return ns;
  23692. },
  23693. // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
  23694. getTextMode({ tag, ns }) {
  23695. if (ns === 0 /* DOMNamespaces.HTML */) {
  23696. if (tag === 'textarea' || tag === 'title') {
  23697. return 1 /* TextModes.RCDATA */;
  23698. }
  23699. if (isRawTextContainer(tag)) {
  23700. return 2 /* TextModes.RAWTEXT */;
  23701. }
  23702. }
  23703. return 0 /* TextModes.DATA */;
  23704. }
  23705. };
  23706. // Parse inline CSS strings for static style attributes into an object.
  23707. // This is a NodeTransform since it works on the static `style` attribute and
  23708. // converts it into a dynamic equivalent:
  23709. // style="color: red" -> :style='{ "color": "red" }'
  23710. // It is then processed by `transformElement` and included in the generated
  23711. // props.
  23712. const transformStyle = node => {
  23713. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  23714. node.props.forEach((p, i) => {
  23715. if (p.type === 6 /* NodeTypes.ATTRIBUTE */ && p.name === 'style' && p.value) {
  23716. // replace p with an expression node
  23717. node.props[i] = {
  23718. type: 7 /* NodeTypes.DIRECTIVE */,
  23719. name: `bind`,
  23720. arg: createSimpleExpression(`style`, true, p.loc),
  23721. exp: parseInlineCSS(p.value.content, p.loc),
  23722. modifiers: [],
  23723. loc: p.loc
  23724. };
  23725. }
  23726. });
  23727. }
  23728. };
  23729. const parseInlineCSS = (cssText, loc) => {
  23730. const normalized = parseStringStyle(cssText);
  23731. return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  23732. };
  23733. function createDOMCompilerError(code, loc) {
  23734. return createCompilerError(code, loc, DOMErrorMessages );
  23735. }
  23736. const DOMErrorMessages = {
  23737. [51 /* DOMErrorCodes.X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
  23738. [52 /* DOMErrorCodes.X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
  23739. [53 /* DOMErrorCodes.X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
  23740. [54 /* DOMErrorCodes.X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
  23741. [55 /* DOMErrorCodes.X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
  23742. [56 /* DOMErrorCodes.X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
  23743. [57 /* DOMErrorCodes.X_V_MODEL_ON_FILE_INPUT_ELEMENT */]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`,
  23744. [58 /* DOMErrorCodes.X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
  23745. [59 /* DOMErrorCodes.X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
  23746. [60 /* DOMErrorCodes.X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
  23747. [61 /* DOMErrorCodes.X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
  23748. };
  23749. const transformVHtml = (dir, node, context) => {
  23750. const { exp, loc } = dir;
  23751. if (!exp) {
  23752. context.onError(createDOMCompilerError(51 /* DOMErrorCodes.X_V_HTML_NO_EXPRESSION */, loc));
  23753. }
  23754. if (node.children.length) {
  23755. context.onError(createDOMCompilerError(52 /* DOMErrorCodes.X_V_HTML_WITH_CHILDREN */, loc));
  23756. node.children.length = 0;
  23757. }
  23758. return {
  23759. props: [
  23760. createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
  23761. ]
  23762. };
  23763. };
  23764. const transformVText = (dir, node, context) => {
  23765. const { exp, loc } = dir;
  23766. if (!exp) {
  23767. context.onError(createDOMCompilerError(53 /* DOMErrorCodes.X_V_TEXT_NO_EXPRESSION */, loc));
  23768. }
  23769. if (node.children.length) {
  23770. context.onError(createDOMCompilerError(54 /* DOMErrorCodes.X_V_TEXT_WITH_CHILDREN */, loc));
  23771. node.children.length = 0;
  23772. }
  23773. return {
  23774. props: [
  23775. createObjectProperty(createSimpleExpression(`textContent`, true), exp
  23776. ? getConstantType(exp, context) > 0
  23777. ? exp
  23778. : createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
  23779. : createSimpleExpression('', true))
  23780. ]
  23781. };
  23782. };
  23783. const transformModel = (dir, node, context) => {
  23784. const baseResult = transformModel$1(dir, node, context);
  23785. // base transform has errors OR component v-model (only need props)
  23786. if (!baseResult.props.length || node.tagType === 1 /* ElementTypes.COMPONENT */) {
  23787. return baseResult;
  23788. }
  23789. if (dir.arg) {
  23790. context.onError(createDOMCompilerError(56 /* DOMErrorCodes.X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
  23791. }
  23792. function checkDuplicatedValue() {
  23793. const value = findProp(node, 'value');
  23794. if (value) {
  23795. context.onError(createDOMCompilerError(58 /* DOMErrorCodes.X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
  23796. }
  23797. }
  23798. const { tag } = node;
  23799. const isCustomElement = context.isCustomElement(tag);
  23800. if (tag === 'input' ||
  23801. tag === 'textarea' ||
  23802. tag === 'select' ||
  23803. isCustomElement) {
  23804. let directiveToUse = V_MODEL_TEXT;
  23805. let isInvalidType = false;
  23806. if (tag === 'input' || isCustomElement) {
  23807. const type = findProp(node, `type`);
  23808. if (type) {
  23809. if (type.type === 7 /* NodeTypes.DIRECTIVE */) {
  23810. // :type="foo"
  23811. directiveToUse = V_MODEL_DYNAMIC;
  23812. }
  23813. else if (type.value) {
  23814. switch (type.value.content) {
  23815. case 'radio':
  23816. directiveToUse = V_MODEL_RADIO;
  23817. break;
  23818. case 'checkbox':
  23819. directiveToUse = V_MODEL_CHECKBOX;
  23820. break;
  23821. case 'file':
  23822. isInvalidType = true;
  23823. context.onError(createDOMCompilerError(57 /* DOMErrorCodes.X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
  23824. break;
  23825. default:
  23826. // text type
  23827. checkDuplicatedValue();
  23828. break;
  23829. }
  23830. }
  23831. }
  23832. else if (hasDynamicKeyVBind(node)) {
  23833. // element has bindings with dynamic keys, which can possibly contain
  23834. // "type".
  23835. directiveToUse = V_MODEL_DYNAMIC;
  23836. }
  23837. else {
  23838. // text type
  23839. checkDuplicatedValue();
  23840. }
  23841. }
  23842. else if (tag === 'select') {
  23843. directiveToUse = V_MODEL_SELECT;
  23844. }
  23845. else {
  23846. // textarea
  23847. checkDuplicatedValue();
  23848. }
  23849. // inject runtime directive
  23850. // by returning the helper symbol via needRuntime
  23851. // the import will replaced a resolveDirective call.
  23852. if (!isInvalidType) {
  23853. baseResult.needRuntime = context.helper(directiveToUse);
  23854. }
  23855. }
  23856. else {
  23857. context.onError(createDOMCompilerError(55 /* DOMErrorCodes.X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
  23858. }
  23859. // native vmodel doesn't need the `modelValue` props since they are also
  23860. // passed to the runtime as `binding.value`. removing it reduces code size.
  23861. baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  23862. p.key.content === 'modelValue'));
  23863. return baseResult;
  23864. };
  23865. const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
  23866. const isNonKeyModifier = /*#__PURE__*/ makeMap(
  23867. // event propagation management
  23868. `stop,prevent,self,` +
  23869. // system modifiers + exact
  23870. `ctrl,shift,alt,meta,exact,` +
  23871. // mouse
  23872. `middle`);
  23873. // left & right could be mouse or key modifiers based on event type
  23874. const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
  23875. const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
  23876. const resolveModifiers = (key, modifiers, context, loc) => {
  23877. const keyModifiers = [];
  23878. const nonKeyModifiers = [];
  23879. const eventOptionModifiers = [];
  23880. for (let i = 0; i < modifiers.length; i++) {
  23881. const modifier = modifiers[i];
  23882. if (isEventOptionModifier(modifier)) {
  23883. // eventOptionModifiers: modifiers for addEventListener() options,
  23884. // e.g. .passive & .capture
  23885. eventOptionModifiers.push(modifier);
  23886. }
  23887. else {
  23888. // runtimeModifiers: modifiers that needs runtime guards
  23889. if (maybeKeyModifier(modifier)) {
  23890. if (isStaticExp(key)) {
  23891. if (isKeyboardEvent(key.content)) {
  23892. keyModifiers.push(modifier);
  23893. }
  23894. else {
  23895. nonKeyModifiers.push(modifier);
  23896. }
  23897. }
  23898. else {
  23899. keyModifiers.push(modifier);
  23900. nonKeyModifiers.push(modifier);
  23901. }
  23902. }
  23903. else {
  23904. if (isNonKeyModifier(modifier)) {
  23905. nonKeyModifiers.push(modifier);
  23906. }
  23907. else {
  23908. keyModifiers.push(modifier);
  23909. }
  23910. }
  23911. }
  23912. }
  23913. return {
  23914. keyModifiers,
  23915. nonKeyModifiers,
  23916. eventOptionModifiers
  23917. };
  23918. };
  23919. const transformClick = (key, event) => {
  23920. const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
  23921. return isStaticClick
  23922. ? createSimpleExpression(event, true)
  23923. : key.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */
  23924. ? createCompoundExpression([
  23925. `(`,
  23926. key,
  23927. `) === "onClick" ? "${event}" : (`,
  23928. key,
  23929. `)`
  23930. ])
  23931. : key;
  23932. };
  23933. const transformOn = (dir, node, context) => {
  23934. return transformOn$1(dir, node, context, baseResult => {
  23935. const { modifiers } = dir;
  23936. if (!modifiers.length)
  23937. return baseResult;
  23938. let { key, value: handlerExp } = baseResult.props[0];
  23939. const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
  23940. // normalize click.right and click.middle since they don't actually fire
  23941. if (nonKeyModifiers.includes('right')) {
  23942. key = transformClick(key, `onContextmenu`);
  23943. }
  23944. if (nonKeyModifiers.includes('middle')) {
  23945. key = transformClick(key, `onMouseup`);
  23946. }
  23947. if (nonKeyModifiers.length) {
  23948. handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
  23949. handlerExp,
  23950. JSON.stringify(nonKeyModifiers)
  23951. ]);
  23952. }
  23953. if (keyModifiers.length &&
  23954. // if event name is dynamic, always wrap with keys guard
  23955. (!isStaticExp(key) || isKeyboardEvent(key.content))) {
  23956. handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
  23957. handlerExp,
  23958. JSON.stringify(keyModifiers)
  23959. ]);
  23960. }
  23961. if (eventOptionModifiers.length) {
  23962. const modifierPostfix = eventOptionModifiers.map(capitalize$1).join('');
  23963. key = isStaticExp(key)
  23964. ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
  23965. : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
  23966. }
  23967. return {
  23968. props: [createObjectProperty(key, handlerExp)]
  23969. };
  23970. });
  23971. };
  23972. const transformShow = (dir, node, context) => {
  23973. const { exp, loc } = dir;
  23974. if (!exp) {
  23975. context.onError(createDOMCompilerError(59 /* DOMErrorCodes.X_V_SHOW_NO_EXPRESSION */, loc));
  23976. }
  23977. return {
  23978. props: [],
  23979. needRuntime: context.helper(V_SHOW)
  23980. };
  23981. };
  23982. const transformTransition = (node, context) => {
  23983. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  23984. node.tagType === 1 /* ElementTypes.COMPONENT */) {
  23985. const component = context.isBuiltInComponent(node.tag);
  23986. if (component === TRANSITION) {
  23987. return () => {
  23988. if (!node.children.length) {
  23989. return;
  23990. }
  23991. // warn multiple transition children
  23992. if (hasMultipleChildren(node)) {
  23993. context.onError(createDOMCompilerError(60 /* DOMErrorCodes.X_TRANSITION_INVALID_CHILDREN */, {
  23994. start: node.children[0].loc.start,
  23995. end: node.children[node.children.length - 1].loc.end,
  23996. source: ''
  23997. }));
  23998. }
  23999. // check if it's s single child w/ v-show
  24000. // if yes, inject "persisted: true" to the transition props
  24001. const child = node.children[0];
  24002. if (child.type === 1 /* NodeTypes.ELEMENT */) {
  24003. for (const p of child.props) {
  24004. if (p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'show') {
  24005. node.props.push({
  24006. type: 6 /* NodeTypes.ATTRIBUTE */,
  24007. name: 'persisted',
  24008. value: undefined,
  24009. loc: node.loc
  24010. });
  24011. }
  24012. }
  24013. }
  24014. };
  24015. }
  24016. }
  24017. };
  24018. function hasMultipleChildren(node) {
  24019. // #1352 filter out potential comment nodes.
  24020. const children = (node.children = node.children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */ &&
  24021. !(c.type === 2 /* NodeTypes.TEXT */ && !c.content.trim())));
  24022. const child = children[0];
  24023. return (children.length !== 1 ||
  24024. child.type === 11 /* NodeTypes.FOR */ ||
  24025. (child.type === 9 /* NodeTypes.IF */ && child.branches.some(hasMultipleChildren)));
  24026. }
  24027. /**
  24028. * This module is Node-only.
  24029. */
  24030. /**
  24031. * Regex for replacing placeholders for embedded constant variables
  24032. * (e.g. import URL string constants generated by compiler-sfc)
  24033. */
  24034. const expReplaceRE = /__VUE_EXP_START__(.*?)__VUE_EXP_END__/g;
  24035. /**
  24036. * Turn eligible hoisted static trees into stringified static nodes, e.g.
  24037. *
  24038. * ```js
  24039. * const _hoisted_1 = createStaticVNode(`<div class="foo">bar</div>`)
  24040. * ```
  24041. *
  24042. * A single static vnode can contain stringified content for **multiple**
  24043. * consecutive nodes (element and plain text), called a "chunk".
  24044. * `@vue/runtime-dom` will create the content via innerHTML in a hidden
  24045. * container element and insert all the nodes in place. The call must also
  24046. * provide the number of nodes contained in the chunk so that during hydration
  24047. * we can know how many nodes the static vnode should adopt.
  24048. *
  24049. * The optimization scans a children list that contains hoisted nodes, and
  24050. * tries to find the largest chunk of consecutive hoisted nodes before running
  24051. * into a non-hoisted node or the end of the list. A chunk is then converted
  24052. * into a single static vnode and replaces the hoisted expression of the first
  24053. * node in the chunk. Other nodes in the chunk are considered "merged" and
  24054. * therefore removed from both the hoist list and the children array.
  24055. *
  24056. * This optimization is only performed in Node.js.
  24057. */
  24058. const stringifyStatic = (children, context, parent) => {
  24059. // bail stringification for slot content
  24060. if (context.scopes.vSlot > 0) {
  24061. return;
  24062. }
  24063. let nc = 0; // current node count
  24064. let ec = 0; // current element with binding count
  24065. const currentChunk = [];
  24066. const stringifyCurrentChunk = (currentIndex) => {
  24067. if (nc >= 20 /* StringifyThresholds.NODE_COUNT */ ||
  24068. ec >= 5 /* StringifyThresholds.ELEMENT_WITH_BINDING_COUNT */) {
  24069. // combine all currently eligible nodes into a single static vnode call
  24070. const staticCall = createCallExpression(context.helper(CREATE_STATIC), [
  24071. JSON.stringify(currentChunk.map(node => stringifyNode(node, context)).join('')).replace(expReplaceRE, `" + $1 + "`),
  24072. // the 2nd argument indicates the number of DOM nodes this static vnode
  24073. // will insert / hydrate
  24074. String(currentChunk.length)
  24075. ]);
  24076. // replace the first node's hoisted expression with the static vnode call
  24077. replaceHoist(currentChunk[0], staticCall, context);
  24078. if (currentChunk.length > 1) {
  24079. for (let i = 1; i < currentChunk.length; i++) {
  24080. // for the merged nodes, set their hoisted expression to null
  24081. replaceHoist(currentChunk[i], null, context);
  24082. }
  24083. // also remove merged nodes from children
  24084. const deleteCount = currentChunk.length - 1;
  24085. children.splice(currentIndex - currentChunk.length + 1, deleteCount);
  24086. return deleteCount;
  24087. }
  24088. }
  24089. return 0;
  24090. };
  24091. let i = 0;
  24092. for (; i < children.length; i++) {
  24093. const child = children[i];
  24094. const hoisted = getHoistedNode(child);
  24095. if (hoisted) {
  24096. // presence of hoisted means child must be a stringifiable node
  24097. const node = child;
  24098. const result = analyzeNode(node);
  24099. if (result) {
  24100. // node is stringifiable, record state
  24101. nc += result[0];
  24102. ec += result[1];
  24103. currentChunk.push(node);
  24104. continue;
  24105. }
  24106. }
  24107. // we only reach here if we ran into a node that is not stringifiable
  24108. // check if currently analyzed nodes meet criteria for stringification.
  24109. // adjust iteration index
  24110. i -= stringifyCurrentChunk(i);
  24111. // reset state
  24112. nc = 0;
  24113. ec = 0;
  24114. currentChunk.length = 0;
  24115. }
  24116. // in case the last node was also stringifiable
  24117. stringifyCurrentChunk(i);
  24118. };
  24119. const getHoistedNode = (node) => ((node.type === 1 /* NodeTypes.ELEMENT */ && node.tagType === 0 /* ElementTypes.ELEMENT */) ||
  24120. node.type == 12 /* NodeTypes.TEXT_CALL */) &&
  24121. node.codegenNode &&
  24122. node.codegenNode.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  24123. node.codegenNode.hoisted;
  24124. const dataAriaRE = /^(data|aria)-/;
  24125. const isStringifiableAttr = (name, ns) => {
  24126. return ((ns === 0 /* DOMNamespaces.HTML */
  24127. ? isKnownHtmlAttr(name)
  24128. : ns === 1 /* DOMNamespaces.SVG */
  24129. ? isKnownSvgAttr(name)
  24130. : false) || dataAriaRE.test(name));
  24131. };
  24132. const replaceHoist = (node, replacement, context) => {
  24133. const hoistToReplace = node.codegenNode.hoisted;
  24134. context.hoists[context.hoists.indexOf(hoistToReplace)] = replacement;
  24135. };
  24136. const isNonStringifiable = /*#__PURE__*/ makeMap(`caption,thead,tr,th,tbody,td,tfoot,colgroup,col`);
  24137. /**
  24138. * for a hoisted node, analyze it and return:
  24139. * - false: bailed (contains non-stringifiable props or runtime constant)
  24140. * - [nc, ec] where
  24141. * - nc is the number of nodes inside
  24142. * - ec is the number of element with bindings inside
  24143. */
  24144. function analyzeNode(node) {
  24145. if (node.type === 1 /* NodeTypes.ELEMENT */ && isNonStringifiable(node.tag)) {
  24146. return false;
  24147. }
  24148. if (node.type === 12 /* NodeTypes.TEXT_CALL */) {
  24149. return [1, 0];
  24150. }
  24151. let nc = 1; // node count
  24152. let ec = node.props.length > 0 ? 1 : 0; // element w/ binding count
  24153. let bailed = false;
  24154. const bail = () => {
  24155. bailed = true;
  24156. return false;
  24157. };
  24158. // TODO: check for cases where using innerHTML will result in different
  24159. // output compared to imperative node insertions.
  24160. // probably only need to check for most common case
  24161. // i.e. non-phrasing-content tags inside `<p>`
  24162. function walk(node) {
  24163. for (let i = 0; i < node.props.length; i++) {
  24164. const p = node.props[i];
  24165. // bail on non-attr bindings
  24166. if (p.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  24167. !isStringifiableAttr(p.name, node.ns)) {
  24168. return bail();
  24169. }
  24170. if (p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'bind') {
  24171. // bail on non-attr bindings
  24172. if (p.arg &&
  24173. (p.arg.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */ ||
  24174. (p.arg.isStatic && !isStringifiableAttr(p.arg.content, node.ns)))) {
  24175. return bail();
  24176. }
  24177. if (p.exp &&
  24178. (p.exp.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */ ||
  24179. p.exp.constType < 3 /* ConstantTypes.CAN_STRINGIFY */)) {
  24180. return bail();
  24181. }
  24182. }
  24183. }
  24184. for (let i = 0; i < node.children.length; i++) {
  24185. nc++;
  24186. const child = node.children[i];
  24187. if (child.type === 1 /* NodeTypes.ELEMENT */) {
  24188. if (child.props.length > 0) {
  24189. ec++;
  24190. }
  24191. walk(child);
  24192. if (bailed) {
  24193. return false;
  24194. }
  24195. }
  24196. }
  24197. return true;
  24198. }
  24199. return walk(node) ? [nc, ec] : false;
  24200. }
  24201. function stringifyNode(node, context) {
  24202. if (isString$2(node)) {
  24203. return node;
  24204. }
  24205. if (isSymbol$1(node)) {
  24206. return ``;
  24207. }
  24208. switch (node.type) {
  24209. case 1 /* NodeTypes.ELEMENT */:
  24210. return stringifyElement(node, context);
  24211. case 2 /* NodeTypes.TEXT */:
  24212. return escapeHtml(node.content);
  24213. case 3 /* NodeTypes.COMMENT */:
  24214. return `<!--${escapeHtml(node.content)}-->`;
  24215. case 5 /* NodeTypes.INTERPOLATION */:
  24216. return escapeHtml(toDisplayString(evaluateConstant(node.content)));
  24217. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  24218. return escapeHtml(evaluateConstant(node));
  24219. case 12 /* NodeTypes.TEXT_CALL */:
  24220. return stringifyNode(node.content, context);
  24221. default:
  24222. // static trees will not contain if/for nodes
  24223. return '';
  24224. }
  24225. }
  24226. function stringifyElement(node, context) {
  24227. let res = `<${node.tag}`;
  24228. let innerHTML = '';
  24229. for (let i = 0; i < node.props.length; i++) {
  24230. const p = node.props[i];
  24231. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  24232. res += ` ${p.name}`;
  24233. if (p.value) {
  24234. res += `="${escapeHtml(p.value.content)}"`;
  24235. }
  24236. }
  24237. else if (p.type === 7 /* NodeTypes.DIRECTIVE */) {
  24238. if (p.name === 'bind') {
  24239. const exp = p.exp;
  24240. if (exp.content[0] === '_') {
  24241. // internally generated string constant references
  24242. // e.g. imported URL strings via compiler-sfc transformAssetUrl plugin
  24243. res += ` ${p.arg.content}="__VUE_EXP_START__${exp.content}__VUE_EXP_END__"`;
  24244. continue;
  24245. }
  24246. // #6568
  24247. if (isBooleanAttr(p.arg.content) &&
  24248. exp.content === 'false') {
  24249. continue;
  24250. }
  24251. // constant v-bind, e.g. :foo="1"
  24252. let evaluated = evaluateConstant(exp);
  24253. if (evaluated != null) {
  24254. const arg = p.arg && p.arg.content;
  24255. if (arg === 'class') {
  24256. evaluated = normalizeClass(evaluated);
  24257. }
  24258. else if (arg === 'style') {
  24259. evaluated = stringifyStyle(normalizeStyle(evaluated));
  24260. }
  24261. res += ` ${p.arg.content}="${escapeHtml(evaluated)}"`;
  24262. }
  24263. }
  24264. else if (p.name === 'html') {
  24265. // #5439 v-html with constant value
  24266. // not sure why would anyone do this but it can happen
  24267. innerHTML = evaluateConstant(p.exp);
  24268. }
  24269. else if (p.name === 'text') {
  24270. innerHTML = escapeHtml(toDisplayString(evaluateConstant(p.exp)));
  24271. }
  24272. }
  24273. }
  24274. if (context.scopeId) {
  24275. res += ` ${context.scopeId}`;
  24276. }
  24277. res += `>`;
  24278. if (innerHTML) {
  24279. res += innerHTML;
  24280. }
  24281. else {
  24282. for (let i = 0; i < node.children.length; i++) {
  24283. res += stringifyNode(node.children[i], context);
  24284. }
  24285. }
  24286. if (!isVoidTag(node.tag)) {
  24287. res += `</${node.tag}>`;
  24288. }
  24289. return res;
  24290. }
  24291. // __UNSAFE__
  24292. // Reason: eval.
  24293. // It's technically safe to eval because only constant expressions are possible
  24294. // here, e.g. `{{ 1 }}` or `{{ 'foo' }}`
  24295. // in addition, constant exps bail on presence of parens so you can't even
  24296. // run JSFuck in here. But we mark it unsafe for security review purposes.
  24297. // (see compiler-core/src/transforms/transformExpression)
  24298. function evaluateConstant(exp) {
  24299. if (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  24300. return new Function(`return ${exp.content}`)();
  24301. }
  24302. else {
  24303. // compound
  24304. let res = ``;
  24305. exp.children.forEach(c => {
  24306. if (isString$2(c) || isSymbol$1(c)) {
  24307. return;
  24308. }
  24309. if (c.type === 2 /* NodeTypes.TEXT */) {
  24310. res += c.content;
  24311. }
  24312. else if (c.type === 5 /* NodeTypes.INTERPOLATION */) {
  24313. res += toDisplayString(evaluateConstant(c.content));
  24314. }
  24315. else {
  24316. res += evaluateConstant(c);
  24317. }
  24318. });
  24319. return res;
  24320. }
  24321. }
  24322. const ignoreSideEffectTags = (node, context) => {
  24323. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  24324. node.tagType === 0 /* ElementTypes.ELEMENT */ &&
  24325. (node.tag === 'script' || node.tag === 'style')) {
  24326. context.onError(createDOMCompilerError(61 /* DOMErrorCodes.X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
  24327. context.removeNode();
  24328. }
  24329. };
  24330. const DOMNodeTransforms = [
  24331. transformStyle,
  24332. ...([transformTransition] )
  24333. ];
  24334. const DOMDirectiveTransforms = {
  24335. cloak: noopDirectiveTransform,
  24336. html: transformVHtml,
  24337. text: transformVText,
  24338. model: transformModel,
  24339. on: transformOn,
  24340. show: transformShow
  24341. };
  24342. function compile$1(template, options = {}) {
  24343. return baseCompile(template, extend({}, parserOptions, options, {
  24344. nodeTransforms: [
  24345. // ignore <script> and <tag>
  24346. // this is not put inside DOMNodeTransforms because that list is used
  24347. // by compiler-ssr to generate vnode fallback branches
  24348. ignoreSideEffectTags,
  24349. ...DOMNodeTransforms,
  24350. ...(options.nodeTransforms || [])
  24351. ],
  24352. directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
  24353. transformHoist: stringifyStatic
  24354. }));
  24355. }
  24356. function parse$8(template, options = {}) {
  24357. return baseParse(template, extend({}, parserOptions, options));
  24358. }
  24359. var CompilerDOM = /*#__PURE__*/Object.freeze({
  24360. __proto__: null,
  24361. BASE_TRANSITION: BASE_TRANSITION,
  24362. CAMELIZE: CAMELIZE,
  24363. CAPITALIZE: CAPITALIZE,
  24364. CREATE_BLOCK: CREATE_BLOCK,
  24365. CREATE_COMMENT: CREATE_COMMENT,
  24366. CREATE_ELEMENT_BLOCK: CREATE_ELEMENT_BLOCK,
  24367. CREATE_ELEMENT_VNODE: CREATE_ELEMENT_VNODE,
  24368. CREATE_SLOTS: CREATE_SLOTS,
  24369. CREATE_STATIC: CREATE_STATIC,
  24370. CREATE_TEXT: CREATE_TEXT,
  24371. CREATE_VNODE: CREATE_VNODE,
  24372. DOMDirectiveTransforms: DOMDirectiveTransforms,
  24373. DOMNodeTransforms: DOMNodeTransforms,
  24374. FRAGMENT: FRAGMENT,
  24375. GUARD_REACTIVE_PROPS: GUARD_REACTIVE_PROPS,
  24376. IS_MEMO_SAME: IS_MEMO_SAME,
  24377. IS_REF: IS_REF,
  24378. KEEP_ALIVE: KEEP_ALIVE,
  24379. MERGE_PROPS: MERGE_PROPS,
  24380. NORMALIZE_CLASS: NORMALIZE_CLASS,
  24381. NORMALIZE_PROPS: NORMALIZE_PROPS,
  24382. NORMALIZE_STYLE: NORMALIZE_STYLE,
  24383. OPEN_BLOCK: OPEN_BLOCK,
  24384. POP_SCOPE_ID: POP_SCOPE_ID,
  24385. PUSH_SCOPE_ID: PUSH_SCOPE_ID,
  24386. RENDER_LIST: RENDER_LIST,
  24387. RENDER_SLOT: RENDER_SLOT,
  24388. RESOLVE_COMPONENT: RESOLVE_COMPONENT,
  24389. RESOLVE_DIRECTIVE: RESOLVE_DIRECTIVE,
  24390. RESOLVE_DYNAMIC_COMPONENT: RESOLVE_DYNAMIC_COMPONENT,
  24391. RESOLVE_FILTER: RESOLVE_FILTER,
  24392. SET_BLOCK_TRACKING: SET_BLOCK_TRACKING,
  24393. SUSPENSE: SUSPENSE,
  24394. TELEPORT: TELEPORT,
  24395. TO_DISPLAY_STRING: TO_DISPLAY_STRING,
  24396. TO_HANDLERS: TO_HANDLERS,
  24397. TO_HANDLER_KEY: TO_HANDLER_KEY,
  24398. TRANSITION: TRANSITION,
  24399. TRANSITION_GROUP: TRANSITION_GROUP,
  24400. UNREF: UNREF,
  24401. V_MODEL_CHECKBOX: V_MODEL_CHECKBOX,
  24402. V_MODEL_DYNAMIC: V_MODEL_DYNAMIC,
  24403. V_MODEL_RADIO: V_MODEL_RADIO,
  24404. V_MODEL_SELECT: V_MODEL_SELECT,
  24405. V_MODEL_TEXT: V_MODEL_TEXT,
  24406. V_ON_WITH_KEYS: V_ON_WITH_KEYS,
  24407. V_ON_WITH_MODIFIERS: V_ON_WITH_MODIFIERS,
  24408. V_SHOW: V_SHOW,
  24409. WITH_CTX: WITH_CTX,
  24410. WITH_DIRECTIVES: WITH_DIRECTIVES,
  24411. WITH_MEMO: WITH_MEMO,
  24412. advancePositionWithClone: advancePositionWithClone,
  24413. advancePositionWithMutation: advancePositionWithMutation,
  24414. assert: assert,
  24415. baseCompile: baseCompile,
  24416. baseParse: baseParse,
  24417. buildDirectiveArgs: buildDirectiveArgs,
  24418. buildProps: buildProps,
  24419. buildSlots: buildSlots,
  24420. checkCompatEnabled: checkCompatEnabled,
  24421. compile: compile$1,
  24422. createArrayExpression: createArrayExpression,
  24423. createAssignmentExpression: createAssignmentExpression,
  24424. createBlockStatement: createBlockStatement,
  24425. createCacheExpression: createCacheExpression,
  24426. createCallExpression: createCallExpression,
  24427. createCompilerError: createCompilerError,
  24428. createCompoundExpression: createCompoundExpression,
  24429. createConditionalExpression: createConditionalExpression,
  24430. createDOMCompilerError: createDOMCompilerError,
  24431. createForLoopParams: createForLoopParams,
  24432. createFunctionExpression: createFunctionExpression,
  24433. createIfStatement: createIfStatement,
  24434. createInterpolation: createInterpolation,
  24435. createObjectExpression: createObjectExpression,
  24436. createObjectProperty: createObjectProperty,
  24437. createReturnStatement: createReturnStatement,
  24438. createRoot: createRoot,
  24439. createSequenceExpression: createSequenceExpression,
  24440. createSimpleExpression: createSimpleExpression,
  24441. createStructuralDirectiveTransform: createStructuralDirectiveTransform,
  24442. createTemplateLiteral: createTemplateLiteral,
  24443. createTransformContext: createTransformContext,
  24444. createVNodeCall: createVNodeCall,
  24445. extractIdentifiers: extractIdentifiers,
  24446. findDir: findDir,
  24447. findProp: findProp,
  24448. generate: generate,
  24449. generateCodeFrame: generateCodeFrame,
  24450. getBaseTransformPreset: getBaseTransformPreset,
  24451. getConstantType: getConstantType,
  24452. getInnerRange: getInnerRange,
  24453. getMemoedVNodeCall: getMemoedVNodeCall,
  24454. getVNodeBlockHelper: getVNodeBlockHelper,
  24455. getVNodeHelper: getVNodeHelper,
  24456. hasDynamicKeyVBind: hasDynamicKeyVBind,
  24457. hasScopeRef: hasScopeRef,
  24458. helperNameMap: helperNameMap,
  24459. injectProp: injectProp,
  24460. isBuiltInType: isBuiltInType,
  24461. isCoreComponent: isCoreComponent,
  24462. isFunctionType: isFunctionType,
  24463. isInDestructureAssignment: isInDestructureAssignment,
  24464. isMemberExpression: isMemberExpression,
  24465. isMemberExpressionBrowser: isMemberExpressionBrowser,
  24466. isMemberExpressionNode: isMemberExpressionNode,
  24467. isReferencedIdentifier: isReferencedIdentifier,
  24468. isSimpleIdentifier: isSimpleIdentifier,
  24469. isSlotOutlet: isSlotOutlet,
  24470. isStaticArgOf: isStaticArgOf,
  24471. isStaticExp: isStaticExp,
  24472. isStaticProperty: isStaticProperty,
  24473. isStaticPropertyKey: isStaticPropertyKey,
  24474. isTemplateNode: isTemplateNode,
  24475. isText: isText$1,
  24476. isVSlot: isVSlot,
  24477. locStub: locStub,
  24478. makeBlock: makeBlock,
  24479. noopDirectiveTransform: noopDirectiveTransform,
  24480. parse: parse$8,
  24481. parserOptions: parserOptions,
  24482. processExpression: processExpression,
  24483. processFor: processFor,
  24484. processIf: processIf,
  24485. processSlotOutlet: processSlotOutlet,
  24486. registerRuntimeHelpers: registerRuntimeHelpers,
  24487. resolveComponentType: resolveComponentType,
  24488. stringifyExpression: stringifyExpression,
  24489. toValidAssetId: toValidAssetId,
  24490. trackSlotScopes: trackSlotScopes,
  24491. trackVForSlotScopes: trackVForSlotScopes,
  24492. transform: transform$1,
  24493. transformBind: transformBind,
  24494. transformElement: transformElement,
  24495. transformExpression: transformExpression,
  24496. transformModel: transformModel$1,
  24497. transformOn: transformOn$1,
  24498. transformStyle: transformStyle,
  24499. traverseNode: traverseNode,
  24500. walkBlockDeclarations: walkBlockDeclarations,
  24501. walkFunctionParams: walkFunctionParams,
  24502. walkIdentifiers: walkIdentifiers,
  24503. warnDeprecation: warnDeprecation
  24504. });
  24505. function pad$1 (hash, len) {
  24506. while (hash.length < len) {
  24507. hash = '0' + hash;
  24508. }
  24509. return hash;
  24510. }
  24511. function fold (hash, text) {
  24512. var i;
  24513. var chr;
  24514. var len;
  24515. if (text.length === 0) {
  24516. return hash;
  24517. }
  24518. for (i = 0, len = text.length; i < len; i++) {
  24519. chr = text.charCodeAt(i);
  24520. hash = ((hash << 5) - hash) + chr;
  24521. hash |= 0;
  24522. }
  24523. return hash < 0 ? hash * -2 : hash;
  24524. }
  24525. function foldObject (hash, o, seen) {
  24526. return Object.keys(o).sort().reduce(foldKey, hash);
  24527. function foldKey (hash, key) {
  24528. return foldValue(hash, o[key], key, seen);
  24529. }
  24530. }
  24531. function foldValue (input, value, key, seen) {
  24532. var hash = fold(fold(fold(input, key), toString$2(value)), typeof value);
  24533. if (value === null) {
  24534. return fold(hash, 'null');
  24535. }
  24536. if (value === undefined) {
  24537. return fold(hash, 'undefined');
  24538. }
  24539. if (typeof value === 'object' || typeof value === 'function') {
  24540. if (seen.indexOf(value) !== -1) {
  24541. return fold(hash, '[Circular]' + key);
  24542. }
  24543. seen.push(value);
  24544. var objHash = foldObject(hash, value, seen);
  24545. if (!('valueOf' in value) || typeof value.valueOf !== 'function') {
  24546. return objHash;
  24547. }
  24548. try {
  24549. return fold(objHash, String(value.valueOf()))
  24550. } catch (err) {
  24551. return fold(objHash, '[valueOf exception]' + (err.stack || err.message))
  24552. }
  24553. }
  24554. return fold(hash, value.toString());
  24555. }
  24556. function toString$2 (o) {
  24557. return Object.prototype.toString.call(o);
  24558. }
  24559. function sum (o) {
  24560. return pad$1(foldValue(0, o, '', []).toString(16), 8);
  24561. }
  24562. var hashSum = sum;
  24563. var hash = hashSum;
  24564. const CSS_VARS_HELPER = `useCssVars`;
  24565. function genCssVarsFromList(vars, id, isProd, isSSR = false) {
  24566. return `{\n ${vars
  24567. .map(key => `"${isSSR ? `--` : ``}${genVarName(id, key, isProd)}": (${key})`)
  24568. .join(',\n ')}\n}`;
  24569. }
  24570. function genVarName(id, raw, isProd) {
  24571. if (isProd) {
  24572. return hash(id + raw);
  24573. }
  24574. else {
  24575. // escape ASCII Punctuation & Symbols
  24576. return `${id}-${raw.replace(/[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/g, s => `\\${s}`)}`;
  24577. }
  24578. }
  24579. function normalizeExpression(exp) {
  24580. exp = exp.trim();
  24581. if ((exp[0] === `'` && exp[exp.length - 1] === `'`) ||
  24582. (exp[0] === `"` && exp[exp.length - 1] === `"`)) {
  24583. return exp.slice(1, -1);
  24584. }
  24585. return exp;
  24586. }
  24587. const vBindRE = /v-bind\s*\(/g;
  24588. function parseCssVars(sfc) {
  24589. const vars = [];
  24590. sfc.styles.forEach(style => {
  24591. let match;
  24592. // ignore v-bind() in comments /* ... */
  24593. const content = style.content.replace(/\/\*([\s\S]*?)\*\//g, '');
  24594. while ((match = vBindRE.exec(content))) {
  24595. const start = match.index + match[0].length;
  24596. const end = lexBinding(content, start);
  24597. if (end !== null) {
  24598. const variable = normalizeExpression(content.slice(start, end));
  24599. if (!vars.includes(variable)) {
  24600. vars.push(variable);
  24601. }
  24602. }
  24603. }
  24604. });
  24605. return vars;
  24606. }
  24607. function lexBinding(content, start) {
  24608. let state = 0 /* LexerState.inParens */;
  24609. let parenDepth = 0;
  24610. for (let i = start; i < content.length; i++) {
  24611. const char = content.charAt(i);
  24612. switch (state) {
  24613. case 0 /* LexerState.inParens */:
  24614. if (char === `'`) {
  24615. state = 1 /* LexerState.inSingleQuoteString */;
  24616. }
  24617. else if (char === `"`) {
  24618. state = 2 /* LexerState.inDoubleQuoteString */;
  24619. }
  24620. else if (char === `(`) {
  24621. parenDepth++;
  24622. }
  24623. else if (char === `)`) {
  24624. if (parenDepth > 0) {
  24625. parenDepth--;
  24626. }
  24627. else {
  24628. return i;
  24629. }
  24630. }
  24631. break;
  24632. case 1 /* LexerState.inSingleQuoteString */:
  24633. if (char === `'`) {
  24634. state = 0 /* LexerState.inParens */;
  24635. }
  24636. break;
  24637. case 2 /* LexerState.inDoubleQuoteString */:
  24638. if (char === `"`) {
  24639. state = 0 /* LexerState.inParens */;
  24640. }
  24641. break;
  24642. }
  24643. }
  24644. return null;
  24645. }
  24646. const cssVarsPlugin = opts => {
  24647. const { id, isProd } = opts;
  24648. return {
  24649. postcssPlugin: 'vue-sfc-vars',
  24650. Declaration(decl) {
  24651. // rewrite CSS variables
  24652. const value = decl.value;
  24653. if (vBindRE.test(value)) {
  24654. vBindRE.lastIndex = 0;
  24655. let transformed = '';
  24656. let lastIndex = 0;
  24657. let match;
  24658. while ((match = vBindRE.exec(value))) {
  24659. const start = match.index + match[0].length;
  24660. const end = lexBinding(value, start);
  24661. if (end !== null) {
  24662. const variable = normalizeExpression(value.slice(start, end));
  24663. transformed +=
  24664. value.slice(lastIndex, match.index) +
  24665. `var(--${genVarName(id, variable, isProd)})`;
  24666. lastIndex = end + 1;
  24667. }
  24668. }
  24669. decl.value = transformed + value.slice(lastIndex);
  24670. }
  24671. }
  24672. };
  24673. };
  24674. cssVarsPlugin.postcss = true;
  24675. function genCssVarsCode(vars, bindings, id, isProd) {
  24676. const varsExp = genCssVarsFromList(vars, id, isProd);
  24677. const exp = createSimpleExpression(varsExp, false);
  24678. const context = createTransformContext(createRoot([]), {
  24679. prefixIdentifiers: true,
  24680. inline: true,
  24681. bindingMetadata: bindings.__isScriptSetup === false ? undefined : bindings
  24682. });
  24683. const transformed = processExpression(exp, context);
  24684. const transformedString = transformed.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */
  24685. ? transformed.content
  24686. : transformed.children
  24687. .map(c => {
  24688. return typeof c === 'string'
  24689. ? c
  24690. : c.content;
  24691. })
  24692. .join('');
  24693. return `_${CSS_VARS_HELPER}(_ctx => (${transformedString}))`;
  24694. }
  24695. // <script setup> already gets the calls injected as part of the transform
  24696. // this is only for single normal <script>
  24697. function genNormalScriptCssVarsCode(cssVars, bindings, id, isProd) {
  24698. return (`\nimport { ${CSS_VARS_HELPER} as _${CSS_VARS_HELPER} } from 'vue'\n` +
  24699. `const __injectCSSVars__ = () => {\n${genCssVarsCode(cssVars, bindings, id, isProd)}}\n` +
  24700. `const __setup__ = __default__.setup\n` +
  24701. `__default__.setup = __setup__\n` +
  24702. ` ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) }\n` +
  24703. ` : __injectCSSVars__\n`);
  24704. }
  24705. function createCache(size = 500) {
  24706. return new Map()
  24707. ;
  24708. }
  24709. var global$1 = (typeof global !== "undefined" ? global :
  24710. typeof self !== "undefined" ? self :
  24711. typeof window !== "undefined" ? window : {});
  24712. var lookup = [];
  24713. var revLookup = [];
  24714. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
  24715. var inited = false;
  24716. function init () {
  24717. inited = true;
  24718. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  24719. for (var i = 0, len = code.length; i < len; ++i) {
  24720. lookup[i] = code[i];
  24721. revLookup[code.charCodeAt(i)] = i;
  24722. }
  24723. revLookup['-'.charCodeAt(0)] = 62;
  24724. revLookup['_'.charCodeAt(0)] = 63;
  24725. }
  24726. function toByteArray (b64) {
  24727. if (!inited) {
  24728. init();
  24729. }
  24730. var i, j, l, tmp, placeHolders, arr;
  24731. var len = b64.length;
  24732. if (len % 4 > 0) {
  24733. throw new Error('Invalid string. Length must be a multiple of 4')
  24734. }
  24735. // the number of equal signs (place holders)
  24736. // if there are two placeholders, than the two characters before it
  24737. // represent one byte
  24738. // if there is only one, then the three characters before it represent 2 bytes
  24739. // this is just a cheap hack to not do indexOf twice
  24740. placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;
  24741. // base64 is 4/3 + up to two characters of the original data
  24742. arr = new Arr(len * 3 / 4 - placeHolders);
  24743. // if there are placeholders, only get up to the last complete 4 chars
  24744. l = placeHolders > 0 ? len - 4 : len;
  24745. var L = 0;
  24746. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  24747. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)];
  24748. arr[L++] = (tmp >> 16) & 0xFF;
  24749. arr[L++] = (tmp >> 8) & 0xFF;
  24750. arr[L++] = tmp & 0xFF;
  24751. }
  24752. if (placeHolders === 2) {
  24753. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);
  24754. arr[L++] = tmp & 0xFF;
  24755. } else if (placeHolders === 1) {
  24756. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2);
  24757. arr[L++] = (tmp >> 8) & 0xFF;
  24758. arr[L++] = tmp & 0xFF;
  24759. }
  24760. return arr
  24761. }
  24762. function tripletToBase64 (num) {
  24763. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  24764. }
  24765. function encodeChunk (uint8, start, end) {
  24766. var tmp;
  24767. var output = [];
  24768. for (var i = start; i < end; i += 3) {
  24769. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
  24770. output.push(tripletToBase64(tmp));
  24771. }
  24772. return output.join('')
  24773. }
  24774. function fromByteArray (uint8) {
  24775. if (!inited) {
  24776. init();
  24777. }
  24778. var tmp;
  24779. var len = uint8.length;
  24780. var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
  24781. var output = '';
  24782. var parts = [];
  24783. var maxChunkLength = 16383; // must be multiple of 3
  24784. // go through the array every three bytes, we'll deal with trailing stuff later
  24785. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  24786. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));
  24787. }
  24788. // pad the end with zeros, but make sure to not forget the extra bytes
  24789. if (extraBytes === 1) {
  24790. tmp = uint8[len - 1];
  24791. output += lookup[tmp >> 2];
  24792. output += lookup[(tmp << 4) & 0x3F];
  24793. output += '==';
  24794. } else if (extraBytes === 2) {
  24795. tmp = (uint8[len - 2] << 8) + (uint8[len - 1]);
  24796. output += lookup[tmp >> 10];
  24797. output += lookup[(tmp >> 4) & 0x3F];
  24798. output += lookup[(tmp << 2) & 0x3F];
  24799. output += '=';
  24800. }
  24801. parts.push(output);
  24802. return parts.join('')
  24803. }
  24804. function read (buffer, offset, isLE, mLen, nBytes) {
  24805. var e, m;
  24806. var eLen = nBytes * 8 - mLen - 1;
  24807. var eMax = (1 << eLen) - 1;
  24808. var eBias = eMax >> 1;
  24809. var nBits = -7;
  24810. var i = isLE ? (nBytes - 1) : 0;
  24811. var d = isLE ? -1 : 1;
  24812. var s = buffer[offset + i];
  24813. i += d;
  24814. e = s & ((1 << (-nBits)) - 1);
  24815. s >>= (-nBits);
  24816. nBits += eLen;
  24817. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  24818. m = e & ((1 << (-nBits)) - 1);
  24819. e >>= (-nBits);
  24820. nBits += mLen;
  24821. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  24822. if (e === 0) {
  24823. e = 1 - eBias;
  24824. } else if (e === eMax) {
  24825. return m ? NaN : ((s ? -1 : 1) * Infinity)
  24826. } else {
  24827. m = m + Math.pow(2, mLen);
  24828. e = e - eBias;
  24829. }
  24830. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  24831. }
  24832. function write (buffer, value, offset, isLE, mLen, nBytes) {
  24833. var e, m, c;
  24834. var eLen = nBytes * 8 - mLen - 1;
  24835. var eMax = (1 << eLen) - 1;
  24836. var eBias = eMax >> 1;
  24837. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);
  24838. var i = isLE ? 0 : (nBytes - 1);
  24839. var d = isLE ? 1 : -1;
  24840. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
  24841. value = Math.abs(value);
  24842. if (isNaN(value) || value === Infinity) {
  24843. m = isNaN(value) ? 1 : 0;
  24844. e = eMax;
  24845. } else {
  24846. e = Math.floor(Math.log(value) / Math.LN2);
  24847. if (value * (c = Math.pow(2, -e)) < 1) {
  24848. e--;
  24849. c *= 2;
  24850. }
  24851. if (e + eBias >= 1) {
  24852. value += rt / c;
  24853. } else {
  24854. value += rt * Math.pow(2, 1 - eBias);
  24855. }
  24856. if (value * c >= 2) {
  24857. e++;
  24858. c /= 2;
  24859. }
  24860. if (e + eBias >= eMax) {
  24861. m = 0;
  24862. e = eMax;
  24863. } else if (e + eBias >= 1) {
  24864. m = (value * c - 1) * Math.pow(2, mLen);
  24865. e = e + eBias;
  24866. } else {
  24867. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  24868. e = 0;
  24869. }
  24870. }
  24871. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  24872. e = (e << mLen) | m;
  24873. eLen += mLen;
  24874. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  24875. buffer[offset + i - d] |= s * 128;
  24876. }
  24877. var toString$1 = {}.toString;
  24878. var isArray$2 = Array.isArray || function (arr) {
  24879. return toString$1.call(arr) == '[object Array]';
  24880. };
  24881. /*!
  24882. * The buffer module from node.js, for the browser.
  24883. *
  24884. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  24885. * @license MIT
  24886. */
  24887. var INSPECT_MAX_BYTES = 50;
  24888. /**
  24889. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  24890. * === true Use Uint8Array implementation (fastest)
  24891. * === false Use Object implementation (most compatible, even IE6)
  24892. *
  24893. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  24894. * Opera 11.6+, iOS 4.2+.
  24895. *
  24896. * Due to various browser bugs, sometimes the Object implementation will be used even
  24897. * when the browser supports typed arrays.
  24898. *
  24899. * Note:
  24900. *
  24901. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  24902. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  24903. *
  24904. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  24905. *
  24906. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  24907. * incorrect length in some situations.
  24908. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  24909. * get the Object implementation, which is slower but behaves correctly.
  24910. */
  24911. Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined
  24912. ? global$1.TYPED_ARRAY_SUPPORT
  24913. : true;
  24914. /*
  24915. * Export kMaxLength after typed array support is determined.
  24916. */
  24917. kMaxLength();
  24918. function kMaxLength () {
  24919. return Buffer.TYPED_ARRAY_SUPPORT
  24920. ? 0x7fffffff
  24921. : 0x3fffffff
  24922. }
  24923. function createBuffer (that, length) {
  24924. if (kMaxLength() < length) {
  24925. throw new RangeError('Invalid typed array length')
  24926. }
  24927. if (Buffer.TYPED_ARRAY_SUPPORT) {
  24928. // Return an augmented `Uint8Array` instance, for best performance
  24929. that = new Uint8Array(length);
  24930. that.__proto__ = Buffer.prototype;
  24931. } else {
  24932. // Fallback: Return an object instance of the Buffer class
  24933. if (that === null) {
  24934. that = new Buffer(length);
  24935. }
  24936. that.length = length;
  24937. }
  24938. return that
  24939. }
  24940. /**
  24941. * The Buffer constructor returns instances of `Uint8Array` that have their
  24942. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  24943. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  24944. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  24945. * returns a single octet.
  24946. *
  24947. * The `Uint8Array` prototype remains unmodified.
  24948. */
  24949. function Buffer (arg, encodingOrOffset, length) {
  24950. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  24951. return new Buffer(arg, encodingOrOffset, length)
  24952. }
  24953. // Common case.
  24954. if (typeof arg === 'number') {
  24955. if (typeof encodingOrOffset === 'string') {
  24956. throw new Error(
  24957. 'If encoding is specified then the first argument must be a string'
  24958. )
  24959. }
  24960. return allocUnsafe(this, arg)
  24961. }
  24962. return from(this, arg, encodingOrOffset, length)
  24963. }
  24964. Buffer.poolSize = 8192; // not used by this implementation
  24965. // TODO: Legacy, not needed anymore. Remove in next major version.
  24966. Buffer._augment = function (arr) {
  24967. arr.__proto__ = Buffer.prototype;
  24968. return arr
  24969. };
  24970. function from (that, value, encodingOrOffset, length) {
  24971. if (typeof value === 'number') {
  24972. throw new TypeError('"value" argument must not be a number')
  24973. }
  24974. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  24975. return fromArrayBuffer(that, value, encodingOrOffset, length)
  24976. }
  24977. if (typeof value === 'string') {
  24978. return fromString(that, value, encodingOrOffset)
  24979. }
  24980. return fromObject(that, value)
  24981. }
  24982. /**
  24983. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  24984. * if value is a number.
  24985. * Buffer.from(str[, encoding])
  24986. * Buffer.from(array)
  24987. * Buffer.from(buffer)
  24988. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  24989. **/
  24990. Buffer.from = function (value, encodingOrOffset, length) {
  24991. return from(null, value, encodingOrOffset, length)
  24992. };
  24993. if (Buffer.TYPED_ARRAY_SUPPORT) {
  24994. Buffer.prototype.__proto__ = Uint8Array.prototype;
  24995. Buffer.__proto__ = Uint8Array;
  24996. if (typeof Symbol !== 'undefined' && Symbol.species &&
  24997. Buffer[Symbol.species] === Buffer) ;
  24998. }
  24999. function assertSize (size) {
  25000. if (typeof size !== 'number') {
  25001. throw new TypeError('"size" argument must be a number')
  25002. } else if (size < 0) {
  25003. throw new RangeError('"size" argument must not be negative')
  25004. }
  25005. }
  25006. function alloc (that, size, fill, encoding) {
  25007. assertSize(size);
  25008. if (size <= 0) {
  25009. return createBuffer(that, size)
  25010. }
  25011. if (fill !== undefined) {
  25012. // Only pay attention to encoding if it's a string. This
  25013. // prevents accidentally sending in a number that would
  25014. // be interpretted as a start offset.
  25015. return typeof encoding === 'string'
  25016. ? createBuffer(that, size).fill(fill, encoding)
  25017. : createBuffer(that, size).fill(fill)
  25018. }
  25019. return createBuffer(that, size)
  25020. }
  25021. /**
  25022. * Creates a new filled Buffer instance.
  25023. * alloc(size[, fill[, encoding]])
  25024. **/
  25025. Buffer.alloc = function (size, fill, encoding) {
  25026. return alloc(null, size, fill, encoding)
  25027. };
  25028. function allocUnsafe (that, size) {
  25029. assertSize(size);
  25030. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
  25031. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  25032. for (var i = 0; i < size; ++i) {
  25033. that[i] = 0;
  25034. }
  25035. }
  25036. return that
  25037. }
  25038. /**
  25039. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  25040. * */
  25041. Buffer.allocUnsafe = function (size) {
  25042. return allocUnsafe(null, size)
  25043. };
  25044. /**
  25045. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  25046. */
  25047. Buffer.allocUnsafeSlow = function (size) {
  25048. return allocUnsafe(null, size)
  25049. };
  25050. function fromString (that, string, encoding) {
  25051. if (typeof encoding !== 'string' || encoding === '') {
  25052. encoding = 'utf8';
  25053. }
  25054. if (!Buffer.isEncoding(encoding)) {
  25055. throw new TypeError('"encoding" must be a valid string encoding')
  25056. }
  25057. var length = byteLength(string, encoding) | 0;
  25058. that = createBuffer(that, length);
  25059. var actual = that.write(string, encoding);
  25060. if (actual !== length) {
  25061. // Writing a hex string, for example, that contains invalid characters will
  25062. // cause everything after the first invalid character to be ignored. (e.g.
  25063. // 'abxxcd' will be treated as 'ab')
  25064. that = that.slice(0, actual);
  25065. }
  25066. return that
  25067. }
  25068. function fromArrayLike (that, array) {
  25069. var length = array.length < 0 ? 0 : checked(array.length) | 0;
  25070. that = createBuffer(that, length);
  25071. for (var i = 0; i < length; i += 1) {
  25072. that[i] = array[i] & 255;
  25073. }
  25074. return that
  25075. }
  25076. function fromArrayBuffer (that, array, byteOffset, length) {
  25077. array.byteLength; // this throws if `array` is not a valid ArrayBuffer
  25078. if (byteOffset < 0 || array.byteLength < byteOffset) {
  25079. throw new RangeError('\'offset\' is out of bounds')
  25080. }
  25081. if (array.byteLength < byteOffset + (length || 0)) {
  25082. throw new RangeError('\'length\' is out of bounds')
  25083. }
  25084. if (byteOffset === undefined && length === undefined) {
  25085. array = new Uint8Array(array);
  25086. } else if (length === undefined) {
  25087. array = new Uint8Array(array, byteOffset);
  25088. } else {
  25089. array = new Uint8Array(array, byteOffset, length);
  25090. }
  25091. if (Buffer.TYPED_ARRAY_SUPPORT) {
  25092. // Return an augmented `Uint8Array` instance, for best performance
  25093. that = array;
  25094. that.__proto__ = Buffer.prototype;
  25095. } else {
  25096. // Fallback: Return an object instance of the Buffer class
  25097. that = fromArrayLike(that, array);
  25098. }
  25099. return that
  25100. }
  25101. function fromObject (that, obj) {
  25102. if (internalIsBuffer(obj)) {
  25103. var len = checked(obj.length) | 0;
  25104. that = createBuffer(that, len);
  25105. if (that.length === 0) {
  25106. return that
  25107. }
  25108. obj.copy(that, 0, 0, len);
  25109. return that
  25110. }
  25111. if (obj) {
  25112. if ((typeof ArrayBuffer !== 'undefined' &&
  25113. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  25114. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  25115. return createBuffer(that, 0)
  25116. }
  25117. return fromArrayLike(that, obj)
  25118. }
  25119. if (obj.type === 'Buffer' && isArray$2(obj.data)) {
  25120. return fromArrayLike(that, obj.data)
  25121. }
  25122. }
  25123. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  25124. }
  25125. function checked (length) {
  25126. // Note: cannot use `length < kMaxLength()` here because that fails when
  25127. // length is NaN (which is otherwise coerced to zero.)
  25128. if (length >= kMaxLength()) {
  25129. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  25130. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  25131. }
  25132. return length | 0
  25133. }
  25134. Buffer.isBuffer = isBuffer$1;
  25135. function internalIsBuffer (b) {
  25136. return !!(b != null && b._isBuffer)
  25137. }
  25138. Buffer.compare = function compare (a, b) {
  25139. if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
  25140. throw new TypeError('Arguments must be Buffers')
  25141. }
  25142. if (a === b) return 0
  25143. var x = a.length;
  25144. var y = b.length;
  25145. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  25146. if (a[i] !== b[i]) {
  25147. x = a[i];
  25148. y = b[i];
  25149. break
  25150. }
  25151. }
  25152. if (x < y) return -1
  25153. if (y < x) return 1
  25154. return 0
  25155. };
  25156. Buffer.isEncoding = function isEncoding (encoding) {
  25157. switch (String(encoding).toLowerCase()) {
  25158. case 'hex':
  25159. case 'utf8':
  25160. case 'utf-8':
  25161. case 'ascii':
  25162. case 'latin1':
  25163. case 'binary':
  25164. case 'base64':
  25165. case 'ucs2':
  25166. case 'ucs-2':
  25167. case 'utf16le':
  25168. case 'utf-16le':
  25169. return true
  25170. default:
  25171. return false
  25172. }
  25173. };
  25174. Buffer.concat = function concat (list, length) {
  25175. if (!isArray$2(list)) {
  25176. throw new TypeError('"list" argument must be an Array of Buffers')
  25177. }
  25178. if (list.length === 0) {
  25179. return Buffer.alloc(0)
  25180. }
  25181. var i;
  25182. if (length === undefined) {
  25183. length = 0;
  25184. for (i = 0; i < list.length; ++i) {
  25185. length += list[i].length;
  25186. }
  25187. }
  25188. var buffer = Buffer.allocUnsafe(length);
  25189. var pos = 0;
  25190. for (i = 0; i < list.length; ++i) {
  25191. var buf = list[i];
  25192. if (!internalIsBuffer(buf)) {
  25193. throw new TypeError('"list" argument must be an Array of Buffers')
  25194. }
  25195. buf.copy(buffer, pos);
  25196. pos += buf.length;
  25197. }
  25198. return buffer
  25199. };
  25200. function byteLength (string, encoding) {
  25201. if (internalIsBuffer(string)) {
  25202. return string.length
  25203. }
  25204. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  25205. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  25206. return string.byteLength
  25207. }
  25208. if (typeof string !== 'string') {
  25209. string = '' + string;
  25210. }
  25211. var len = string.length;
  25212. if (len === 0) return 0
  25213. // Use a for loop to avoid recursion
  25214. var loweredCase = false;
  25215. for (;;) {
  25216. switch (encoding) {
  25217. case 'ascii':
  25218. case 'latin1':
  25219. case 'binary':
  25220. return len
  25221. case 'utf8':
  25222. case 'utf-8':
  25223. case undefined:
  25224. return utf8ToBytes(string).length
  25225. case 'ucs2':
  25226. case 'ucs-2':
  25227. case 'utf16le':
  25228. case 'utf-16le':
  25229. return len * 2
  25230. case 'hex':
  25231. return len >>> 1
  25232. case 'base64':
  25233. return base64ToBytes(string).length
  25234. default:
  25235. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  25236. encoding = ('' + encoding).toLowerCase();
  25237. loweredCase = true;
  25238. }
  25239. }
  25240. }
  25241. Buffer.byteLength = byteLength;
  25242. function slowToString (encoding, start, end) {
  25243. var loweredCase = false;
  25244. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  25245. // property of a typed array.
  25246. // This behaves neither like String nor Uint8Array in that we set start/end
  25247. // to their upper/lower bounds if the value passed is out of range.
  25248. // undefined is handled specially as per ECMA-262 6th Edition,
  25249. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  25250. if (start === undefined || start < 0) {
  25251. start = 0;
  25252. }
  25253. // Return early if start > this.length. Done here to prevent potential uint32
  25254. // coercion fail below.
  25255. if (start > this.length) {
  25256. return ''
  25257. }
  25258. if (end === undefined || end > this.length) {
  25259. end = this.length;
  25260. }
  25261. if (end <= 0) {
  25262. return ''
  25263. }
  25264. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  25265. end >>>= 0;
  25266. start >>>= 0;
  25267. if (end <= start) {
  25268. return ''
  25269. }
  25270. if (!encoding) encoding = 'utf8';
  25271. while (true) {
  25272. switch (encoding) {
  25273. case 'hex':
  25274. return hexSlice(this, start, end)
  25275. case 'utf8':
  25276. case 'utf-8':
  25277. return utf8Slice(this, start, end)
  25278. case 'ascii':
  25279. return asciiSlice(this, start, end)
  25280. case 'latin1':
  25281. case 'binary':
  25282. return latin1Slice(this, start, end)
  25283. case 'base64':
  25284. return base64Slice(this, start, end)
  25285. case 'ucs2':
  25286. case 'ucs-2':
  25287. case 'utf16le':
  25288. case 'utf-16le':
  25289. return utf16leSlice(this, start, end)
  25290. default:
  25291. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  25292. encoding = (encoding + '').toLowerCase();
  25293. loweredCase = true;
  25294. }
  25295. }
  25296. }
  25297. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  25298. // Buffer instances.
  25299. Buffer.prototype._isBuffer = true;
  25300. function swap (b, n, m) {
  25301. var i = b[n];
  25302. b[n] = b[m];
  25303. b[m] = i;
  25304. }
  25305. Buffer.prototype.swap16 = function swap16 () {
  25306. var len = this.length;
  25307. if (len % 2 !== 0) {
  25308. throw new RangeError('Buffer size must be a multiple of 16-bits')
  25309. }
  25310. for (var i = 0; i < len; i += 2) {
  25311. swap(this, i, i + 1);
  25312. }
  25313. return this
  25314. };
  25315. Buffer.prototype.swap32 = function swap32 () {
  25316. var len = this.length;
  25317. if (len % 4 !== 0) {
  25318. throw new RangeError('Buffer size must be a multiple of 32-bits')
  25319. }
  25320. for (var i = 0; i < len; i += 4) {
  25321. swap(this, i, i + 3);
  25322. swap(this, i + 1, i + 2);
  25323. }
  25324. return this
  25325. };
  25326. Buffer.prototype.swap64 = function swap64 () {
  25327. var len = this.length;
  25328. if (len % 8 !== 0) {
  25329. throw new RangeError('Buffer size must be a multiple of 64-bits')
  25330. }
  25331. for (var i = 0; i < len; i += 8) {
  25332. swap(this, i, i + 7);
  25333. swap(this, i + 1, i + 6);
  25334. swap(this, i + 2, i + 5);
  25335. swap(this, i + 3, i + 4);
  25336. }
  25337. return this
  25338. };
  25339. Buffer.prototype.toString = function toString () {
  25340. var length = this.length | 0;
  25341. if (length === 0) return ''
  25342. if (arguments.length === 0) return utf8Slice(this, 0, length)
  25343. return slowToString.apply(this, arguments)
  25344. };
  25345. Buffer.prototype.equals = function equals (b) {
  25346. if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')
  25347. if (this === b) return true
  25348. return Buffer.compare(this, b) === 0
  25349. };
  25350. Buffer.prototype.inspect = function inspect () {
  25351. var str = '';
  25352. var max = INSPECT_MAX_BYTES;
  25353. if (this.length > 0) {
  25354. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
  25355. if (this.length > max) str += ' ... ';
  25356. }
  25357. return '<Buffer ' + str + '>'
  25358. };
  25359. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  25360. if (!internalIsBuffer(target)) {
  25361. throw new TypeError('Argument must be a Buffer')
  25362. }
  25363. if (start === undefined) {
  25364. start = 0;
  25365. }
  25366. if (end === undefined) {
  25367. end = target ? target.length : 0;
  25368. }
  25369. if (thisStart === undefined) {
  25370. thisStart = 0;
  25371. }
  25372. if (thisEnd === undefined) {
  25373. thisEnd = this.length;
  25374. }
  25375. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  25376. throw new RangeError('out of range index')
  25377. }
  25378. if (thisStart >= thisEnd && start >= end) {
  25379. return 0
  25380. }
  25381. if (thisStart >= thisEnd) {
  25382. return -1
  25383. }
  25384. if (start >= end) {
  25385. return 1
  25386. }
  25387. start >>>= 0;
  25388. end >>>= 0;
  25389. thisStart >>>= 0;
  25390. thisEnd >>>= 0;
  25391. if (this === target) return 0
  25392. var x = thisEnd - thisStart;
  25393. var y = end - start;
  25394. var len = Math.min(x, y);
  25395. var thisCopy = this.slice(thisStart, thisEnd);
  25396. var targetCopy = target.slice(start, end);
  25397. for (var i = 0; i < len; ++i) {
  25398. if (thisCopy[i] !== targetCopy[i]) {
  25399. x = thisCopy[i];
  25400. y = targetCopy[i];
  25401. break
  25402. }
  25403. }
  25404. if (x < y) return -1
  25405. if (y < x) return 1
  25406. return 0
  25407. };
  25408. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  25409. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  25410. //
  25411. // Arguments:
  25412. // - buffer - a Buffer to search
  25413. // - val - a string, Buffer, or number
  25414. // - byteOffset - an index into `buffer`; will be clamped to an int32
  25415. // - encoding - an optional encoding, relevant is val is a string
  25416. // - dir - true for indexOf, false for lastIndexOf
  25417. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  25418. // Empty buffer means no match
  25419. if (buffer.length === 0) return -1
  25420. // Normalize byteOffset
  25421. if (typeof byteOffset === 'string') {
  25422. encoding = byteOffset;
  25423. byteOffset = 0;
  25424. } else if (byteOffset > 0x7fffffff) {
  25425. byteOffset = 0x7fffffff;
  25426. } else if (byteOffset < -0x80000000) {
  25427. byteOffset = -0x80000000;
  25428. }
  25429. byteOffset = +byteOffset; // Coerce to Number.
  25430. if (isNaN(byteOffset)) {
  25431. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  25432. byteOffset = dir ? 0 : (buffer.length - 1);
  25433. }
  25434. // Normalize byteOffset: negative offsets start from the end of the buffer
  25435. if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
  25436. if (byteOffset >= buffer.length) {
  25437. if (dir) return -1
  25438. else byteOffset = buffer.length - 1;
  25439. } else if (byteOffset < 0) {
  25440. if (dir) byteOffset = 0;
  25441. else return -1
  25442. }
  25443. // Normalize val
  25444. if (typeof val === 'string') {
  25445. val = Buffer.from(val, encoding);
  25446. }
  25447. // Finally, search either indexOf (if dir is true) or lastIndexOf
  25448. if (internalIsBuffer(val)) {
  25449. // Special case: looking for empty string/buffer always fails
  25450. if (val.length === 0) {
  25451. return -1
  25452. }
  25453. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  25454. } else if (typeof val === 'number') {
  25455. val = val & 0xFF; // Search for a byte value [0-255]
  25456. if (Buffer.TYPED_ARRAY_SUPPORT &&
  25457. typeof Uint8Array.prototype.indexOf === 'function') {
  25458. if (dir) {
  25459. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  25460. } else {
  25461. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  25462. }
  25463. }
  25464. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  25465. }
  25466. throw new TypeError('val must be string, number or Buffer')
  25467. }
  25468. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  25469. var indexSize = 1;
  25470. var arrLength = arr.length;
  25471. var valLength = val.length;
  25472. if (encoding !== undefined) {
  25473. encoding = String(encoding).toLowerCase();
  25474. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  25475. encoding === 'utf16le' || encoding === 'utf-16le') {
  25476. if (arr.length < 2 || val.length < 2) {
  25477. return -1
  25478. }
  25479. indexSize = 2;
  25480. arrLength /= 2;
  25481. valLength /= 2;
  25482. byteOffset /= 2;
  25483. }
  25484. }
  25485. function read (buf, i) {
  25486. if (indexSize === 1) {
  25487. return buf[i]
  25488. } else {
  25489. return buf.readUInt16BE(i * indexSize)
  25490. }
  25491. }
  25492. var i;
  25493. if (dir) {
  25494. var foundIndex = -1;
  25495. for (i = byteOffset; i < arrLength; i++) {
  25496. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  25497. if (foundIndex === -1) foundIndex = i;
  25498. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  25499. } else {
  25500. if (foundIndex !== -1) i -= i - foundIndex;
  25501. foundIndex = -1;
  25502. }
  25503. }
  25504. } else {
  25505. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
  25506. for (i = byteOffset; i >= 0; i--) {
  25507. var found = true;
  25508. for (var j = 0; j < valLength; j++) {
  25509. if (read(arr, i + j) !== read(val, j)) {
  25510. found = false;
  25511. break
  25512. }
  25513. }
  25514. if (found) return i
  25515. }
  25516. }
  25517. return -1
  25518. }
  25519. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  25520. return this.indexOf(val, byteOffset, encoding) !== -1
  25521. };
  25522. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  25523. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  25524. };
  25525. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  25526. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  25527. };
  25528. function hexWrite (buf, string, offset, length) {
  25529. offset = Number(offset) || 0;
  25530. var remaining = buf.length - offset;
  25531. if (!length) {
  25532. length = remaining;
  25533. } else {
  25534. length = Number(length);
  25535. if (length > remaining) {
  25536. length = remaining;
  25537. }
  25538. }
  25539. // must be an even number of digits
  25540. var strLen = string.length;
  25541. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  25542. if (length > strLen / 2) {
  25543. length = strLen / 2;
  25544. }
  25545. for (var i = 0; i < length; ++i) {
  25546. var parsed = parseInt(string.substr(i * 2, 2), 16);
  25547. if (isNaN(parsed)) return i
  25548. buf[offset + i] = parsed;
  25549. }
  25550. return i
  25551. }
  25552. function utf8Write (buf, string, offset, length) {
  25553. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  25554. }
  25555. function asciiWrite (buf, string, offset, length) {
  25556. return blitBuffer(asciiToBytes(string), buf, offset, length)
  25557. }
  25558. function latin1Write (buf, string, offset, length) {
  25559. return asciiWrite(buf, string, offset, length)
  25560. }
  25561. function base64Write (buf, string, offset, length) {
  25562. return blitBuffer(base64ToBytes(string), buf, offset, length)
  25563. }
  25564. function ucs2Write (buf, string, offset, length) {
  25565. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  25566. }
  25567. Buffer.prototype.write = function write (string, offset, length, encoding) {
  25568. // Buffer#write(string)
  25569. if (offset === undefined) {
  25570. encoding = 'utf8';
  25571. length = this.length;
  25572. offset = 0;
  25573. // Buffer#write(string, encoding)
  25574. } else if (length === undefined && typeof offset === 'string') {
  25575. encoding = offset;
  25576. length = this.length;
  25577. offset = 0;
  25578. // Buffer#write(string, offset[, length][, encoding])
  25579. } else if (isFinite(offset)) {
  25580. offset = offset | 0;
  25581. if (isFinite(length)) {
  25582. length = length | 0;
  25583. if (encoding === undefined) encoding = 'utf8';
  25584. } else {
  25585. encoding = length;
  25586. length = undefined;
  25587. }
  25588. // legacy write(string, encoding, offset, length) - remove in v0.13
  25589. } else {
  25590. throw new Error(
  25591. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  25592. )
  25593. }
  25594. var remaining = this.length - offset;
  25595. if (length === undefined || length > remaining) length = remaining;
  25596. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  25597. throw new RangeError('Attempt to write outside buffer bounds')
  25598. }
  25599. if (!encoding) encoding = 'utf8';
  25600. var loweredCase = false;
  25601. for (;;) {
  25602. switch (encoding) {
  25603. case 'hex':
  25604. return hexWrite(this, string, offset, length)
  25605. case 'utf8':
  25606. case 'utf-8':
  25607. return utf8Write(this, string, offset, length)
  25608. case 'ascii':
  25609. return asciiWrite(this, string, offset, length)
  25610. case 'latin1':
  25611. case 'binary':
  25612. return latin1Write(this, string, offset, length)
  25613. case 'base64':
  25614. // Warning: maxLength not taken into account in base64Write
  25615. return base64Write(this, string, offset, length)
  25616. case 'ucs2':
  25617. case 'ucs-2':
  25618. case 'utf16le':
  25619. case 'utf-16le':
  25620. return ucs2Write(this, string, offset, length)
  25621. default:
  25622. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  25623. encoding = ('' + encoding).toLowerCase();
  25624. loweredCase = true;
  25625. }
  25626. }
  25627. };
  25628. Buffer.prototype.toJSON = function toJSON () {
  25629. return {
  25630. type: 'Buffer',
  25631. data: Array.prototype.slice.call(this._arr || this, 0)
  25632. }
  25633. };
  25634. function base64Slice (buf, start, end) {
  25635. if (start === 0 && end === buf.length) {
  25636. return fromByteArray(buf)
  25637. } else {
  25638. return fromByteArray(buf.slice(start, end))
  25639. }
  25640. }
  25641. function utf8Slice (buf, start, end) {
  25642. end = Math.min(buf.length, end);
  25643. var res = [];
  25644. var i = start;
  25645. while (i < end) {
  25646. var firstByte = buf[i];
  25647. var codePoint = null;
  25648. var bytesPerSequence = (firstByte > 0xEF) ? 4
  25649. : (firstByte > 0xDF) ? 3
  25650. : (firstByte > 0xBF) ? 2
  25651. : 1;
  25652. if (i + bytesPerSequence <= end) {
  25653. var secondByte, thirdByte, fourthByte, tempCodePoint;
  25654. switch (bytesPerSequence) {
  25655. case 1:
  25656. if (firstByte < 0x80) {
  25657. codePoint = firstByte;
  25658. }
  25659. break
  25660. case 2:
  25661. secondByte = buf[i + 1];
  25662. if ((secondByte & 0xC0) === 0x80) {
  25663. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
  25664. if (tempCodePoint > 0x7F) {
  25665. codePoint = tempCodePoint;
  25666. }
  25667. }
  25668. break
  25669. case 3:
  25670. secondByte = buf[i + 1];
  25671. thirdByte = buf[i + 2];
  25672. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  25673. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
  25674. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  25675. codePoint = tempCodePoint;
  25676. }
  25677. }
  25678. break
  25679. case 4:
  25680. secondByte = buf[i + 1];
  25681. thirdByte = buf[i + 2];
  25682. fourthByte = buf[i + 3];
  25683. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  25684. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
  25685. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  25686. codePoint = tempCodePoint;
  25687. }
  25688. }
  25689. }
  25690. }
  25691. if (codePoint === null) {
  25692. // we did not generate a valid codePoint so insert a
  25693. // replacement char (U+FFFD) and advance only 1 byte
  25694. codePoint = 0xFFFD;
  25695. bytesPerSequence = 1;
  25696. } else if (codePoint > 0xFFFF) {
  25697. // encode to utf16 (surrogate pair dance)
  25698. codePoint -= 0x10000;
  25699. res.push(codePoint >>> 10 & 0x3FF | 0xD800);
  25700. codePoint = 0xDC00 | codePoint & 0x3FF;
  25701. }
  25702. res.push(codePoint);
  25703. i += bytesPerSequence;
  25704. }
  25705. return decodeCodePointsArray(res)
  25706. }
  25707. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  25708. // the lowest limit is Chrome, with 0x10000 args.
  25709. // We go 1 magnitude less, for safety
  25710. var MAX_ARGUMENTS_LENGTH = 0x1000;
  25711. function decodeCodePointsArray (codePoints) {
  25712. var len = codePoints.length;
  25713. if (len <= MAX_ARGUMENTS_LENGTH) {
  25714. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  25715. }
  25716. // Decode in chunks to avoid "call stack size exceeded".
  25717. var res = '';
  25718. var i = 0;
  25719. while (i < len) {
  25720. res += String.fromCharCode.apply(
  25721. String,
  25722. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  25723. );
  25724. }
  25725. return res
  25726. }
  25727. function asciiSlice (buf, start, end) {
  25728. var ret = '';
  25729. end = Math.min(buf.length, end);
  25730. for (var i = start; i < end; ++i) {
  25731. ret += String.fromCharCode(buf[i] & 0x7F);
  25732. }
  25733. return ret
  25734. }
  25735. function latin1Slice (buf, start, end) {
  25736. var ret = '';
  25737. end = Math.min(buf.length, end);
  25738. for (var i = start; i < end; ++i) {
  25739. ret += String.fromCharCode(buf[i]);
  25740. }
  25741. return ret
  25742. }
  25743. function hexSlice (buf, start, end) {
  25744. var len = buf.length;
  25745. if (!start || start < 0) start = 0;
  25746. if (!end || end < 0 || end > len) end = len;
  25747. var out = '';
  25748. for (var i = start; i < end; ++i) {
  25749. out += toHex(buf[i]);
  25750. }
  25751. return out
  25752. }
  25753. function utf16leSlice (buf, start, end) {
  25754. var bytes = buf.slice(start, end);
  25755. var res = '';
  25756. for (var i = 0; i < bytes.length; i += 2) {
  25757. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
  25758. }
  25759. return res
  25760. }
  25761. Buffer.prototype.slice = function slice (start, end) {
  25762. var len = this.length;
  25763. start = ~~start;
  25764. end = end === undefined ? len : ~~end;
  25765. if (start < 0) {
  25766. start += len;
  25767. if (start < 0) start = 0;
  25768. } else if (start > len) {
  25769. start = len;
  25770. }
  25771. if (end < 0) {
  25772. end += len;
  25773. if (end < 0) end = 0;
  25774. } else if (end > len) {
  25775. end = len;
  25776. }
  25777. if (end < start) end = start;
  25778. var newBuf;
  25779. if (Buffer.TYPED_ARRAY_SUPPORT) {
  25780. newBuf = this.subarray(start, end);
  25781. newBuf.__proto__ = Buffer.prototype;
  25782. } else {
  25783. var sliceLen = end - start;
  25784. newBuf = new Buffer(sliceLen, undefined);
  25785. for (var i = 0; i < sliceLen; ++i) {
  25786. newBuf[i] = this[i + start];
  25787. }
  25788. }
  25789. return newBuf
  25790. };
  25791. /*
  25792. * Need to make sure that buffer isn't trying to write out of bounds.
  25793. */
  25794. function checkOffset (offset, ext, length) {
  25795. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  25796. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  25797. }
  25798. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  25799. offset = offset | 0;
  25800. byteLength = byteLength | 0;
  25801. if (!noAssert) checkOffset(offset, byteLength, this.length);
  25802. var val = this[offset];
  25803. var mul = 1;
  25804. var i = 0;
  25805. while (++i < byteLength && (mul *= 0x100)) {
  25806. val += this[offset + i] * mul;
  25807. }
  25808. return val
  25809. };
  25810. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  25811. offset = offset | 0;
  25812. byteLength = byteLength | 0;
  25813. if (!noAssert) {
  25814. checkOffset(offset, byteLength, this.length);
  25815. }
  25816. var val = this[offset + --byteLength];
  25817. var mul = 1;
  25818. while (byteLength > 0 && (mul *= 0x100)) {
  25819. val += this[offset + --byteLength] * mul;
  25820. }
  25821. return val
  25822. };
  25823. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  25824. if (!noAssert) checkOffset(offset, 1, this.length);
  25825. return this[offset]
  25826. };
  25827. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  25828. if (!noAssert) checkOffset(offset, 2, this.length);
  25829. return this[offset] | (this[offset + 1] << 8)
  25830. };
  25831. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  25832. if (!noAssert) checkOffset(offset, 2, this.length);
  25833. return (this[offset] << 8) | this[offset + 1]
  25834. };
  25835. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  25836. if (!noAssert) checkOffset(offset, 4, this.length);
  25837. return ((this[offset]) |
  25838. (this[offset + 1] << 8) |
  25839. (this[offset + 2] << 16)) +
  25840. (this[offset + 3] * 0x1000000)
  25841. };
  25842. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  25843. if (!noAssert) checkOffset(offset, 4, this.length);
  25844. return (this[offset] * 0x1000000) +
  25845. ((this[offset + 1] << 16) |
  25846. (this[offset + 2] << 8) |
  25847. this[offset + 3])
  25848. };
  25849. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  25850. offset = offset | 0;
  25851. byteLength = byteLength | 0;
  25852. if (!noAssert) checkOffset(offset, byteLength, this.length);
  25853. var val = this[offset];
  25854. var mul = 1;
  25855. var i = 0;
  25856. while (++i < byteLength && (mul *= 0x100)) {
  25857. val += this[offset + i] * mul;
  25858. }
  25859. mul *= 0x80;
  25860. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  25861. return val
  25862. };
  25863. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  25864. offset = offset | 0;
  25865. byteLength = byteLength | 0;
  25866. if (!noAssert) checkOffset(offset, byteLength, this.length);
  25867. var i = byteLength;
  25868. var mul = 1;
  25869. var val = this[offset + --i];
  25870. while (i > 0 && (mul *= 0x100)) {
  25871. val += this[offset + --i] * mul;
  25872. }
  25873. mul *= 0x80;
  25874. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  25875. return val
  25876. };
  25877. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  25878. if (!noAssert) checkOffset(offset, 1, this.length);
  25879. if (!(this[offset] & 0x80)) return (this[offset])
  25880. return ((0xff - this[offset] + 1) * -1)
  25881. };
  25882. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  25883. if (!noAssert) checkOffset(offset, 2, this.length);
  25884. var val = this[offset] | (this[offset + 1] << 8);
  25885. return (val & 0x8000) ? val | 0xFFFF0000 : val
  25886. };
  25887. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  25888. if (!noAssert) checkOffset(offset, 2, this.length);
  25889. var val = this[offset + 1] | (this[offset] << 8);
  25890. return (val & 0x8000) ? val | 0xFFFF0000 : val
  25891. };
  25892. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  25893. if (!noAssert) checkOffset(offset, 4, this.length);
  25894. return (this[offset]) |
  25895. (this[offset + 1] << 8) |
  25896. (this[offset + 2] << 16) |
  25897. (this[offset + 3] << 24)
  25898. };
  25899. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  25900. if (!noAssert) checkOffset(offset, 4, this.length);
  25901. return (this[offset] << 24) |
  25902. (this[offset + 1] << 16) |
  25903. (this[offset + 2] << 8) |
  25904. (this[offset + 3])
  25905. };
  25906. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  25907. if (!noAssert) checkOffset(offset, 4, this.length);
  25908. return read(this, offset, true, 23, 4)
  25909. };
  25910. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  25911. if (!noAssert) checkOffset(offset, 4, this.length);
  25912. return read(this, offset, false, 23, 4)
  25913. };
  25914. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  25915. if (!noAssert) checkOffset(offset, 8, this.length);
  25916. return read(this, offset, true, 52, 8)
  25917. };
  25918. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  25919. if (!noAssert) checkOffset(offset, 8, this.length);
  25920. return read(this, offset, false, 52, 8)
  25921. };
  25922. function checkInt (buf, value, offset, ext, max, min) {
  25923. if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  25924. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  25925. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  25926. }
  25927. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  25928. value = +value;
  25929. offset = offset | 0;
  25930. byteLength = byteLength | 0;
  25931. if (!noAssert) {
  25932. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  25933. checkInt(this, value, offset, byteLength, maxBytes, 0);
  25934. }
  25935. var mul = 1;
  25936. var i = 0;
  25937. this[offset] = value & 0xFF;
  25938. while (++i < byteLength && (mul *= 0x100)) {
  25939. this[offset + i] = (value / mul) & 0xFF;
  25940. }
  25941. return offset + byteLength
  25942. };
  25943. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  25944. value = +value;
  25945. offset = offset | 0;
  25946. byteLength = byteLength | 0;
  25947. if (!noAssert) {
  25948. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  25949. checkInt(this, value, offset, byteLength, maxBytes, 0);
  25950. }
  25951. var i = byteLength - 1;
  25952. var mul = 1;
  25953. this[offset + i] = value & 0xFF;
  25954. while (--i >= 0 && (mul *= 0x100)) {
  25955. this[offset + i] = (value / mul) & 0xFF;
  25956. }
  25957. return offset + byteLength
  25958. };
  25959. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  25960. value = +value;
  25961. offset = offset | 0;
  25962. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
  25963. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
  25964. this[offset] = (value & 0xff);
  25965. return offset + 1
  25966. };
  25967. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  25968. if (value < 0) value = 0xffff + value + 1;
  25969. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  25970. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  25971. (littleEndian ? i : 1 - i) * 8;
  25972. }
  25973. }
  25974. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  25975. value = +value;
  25976. offset = offset | 0;
  25977. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  25978. if (Buffer.TYPED_ARRAY_SUPPORT) {
  25979. this[offset] = (value & 0xff);
  25980. this[offset + 1] = (value >>> 8);
  25981. } else {
  25982. objectWriteUInt16(this, value, offset, true);
  25983. }
  25984. return offset + 2
  25985. };
  25986. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  25987. value = +value;
  25988. offset = offset | 0;
  25989. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  25990. if (Buffer.TYPED_ARRAY_SUPPORT) {
  25991. this[offset] = (value >>> 8);
  25992. this[offset + 1] = (value & 0xff);
  25993. } else {
  25994. objectWriteUInt16(this, value, offset, false);
  25995. }
  25996. return offset + 2
  25997. };
  25998. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  25999. if (value < 0) value = 0xffffffff + value + 1;
  26000. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  26001. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff;
  26002. }
  26003. }
  26004. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  26005. value = +value;
  26006. offset = offset | 0;
  26007. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  26008. if (Buffer.TYPED_ARRAY_SUPPORT) {
  26009. this[offset + 3] = (value >>> 24);
  26010. this[offset + 2] = (value >>> 16);
  26011. this[offset + 1] = (value >>> 8);
  26012. this[offset] = (value & 0xff);
  26013. } else {
  26014. objectWriteUInt32(this, value, offset, true);
  26015. }
  26016. return offset + 4
  26017. };
  26018. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  26019. value = +value;
  26020. offset = offset | 0;
  26021. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  26022. if (Buffer.TYPED_ARRAY_SUPPORT) {
  26023. this[offset] = (value >>> 24);
  26024. this[offset + 1] = (value >>> 16);
  26025. this[offset + 2] = (value >>> 8);
  26026. this[offset + 3] = (value & 0xff);
  26027. } else {
  26028. objectWriteUInt32(this, value, offset, false);
  26029. }
  26030. return offset + 4
  26031. };
  26032. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  26033. value = +value;
  26034. offset = offset | 0;
  26035. if (!noAssert) {
  26036. var limit = Math.pow(2, 8 * byteLength - 1);
  26037. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  26038. }
  26039. var i = 0;
  26040. var mul = 1;
  26041. var sub = 0;
  26042. this[offset] = value & 0xFF;
  26043. while (++i < byteLength && (mul *= 0x100)) {
  26044. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  26045. sub = 1;
  26046. }
  26047. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  26048. }
  26049. return offset + byteLength
  26050. };
  26051. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  26052. value = +value;
  26053. offset = offset | 0;
  26054. if (!noAssert) {
  26055. var limit = Math.pow(2, 8 * byteLength - 1);
  26056. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  26057. }
  26058. var i = byteLength - 1;
  26059. var mul = 1;
  26060. var sub = 0;
  26061. this[offset + i] = value & 0xFF;
  26062. while (--i >= 0 && (mul *= 0x100)) {
  26063. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  26064. sub = 1;
  26065. }
  26066. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  26067. }
  26068. return offset + byteLength
  26069. };
  26070. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  26071. value = +value;
  26072. offset = offset | 0;
  26073. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
  26074. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
  26075. if (value < 0) value = 0xff + value + 1;
  26076. this[offset] = (value & 0xff);
  26077. return offset + 1
  26078. };
  26079. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  26080. value = +value;
  26081. offset = offset | 0;
  26082. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  26083. if (Buffer.TYPED_ARRAY_SUPPORT) {
  26084. this[offset] = (value & 0xff);
  26085. this[offset + 1] = (value >>> 8);
  26086. } else {
  26087. objectWriteUInt16(this, value, offset, true);
  26088. }
  26089. return offset + 2
  26090. };
  26091. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  26092. value = +value;
  26093. offset = offset | 0;
  26094. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  26095. if (Buffer.TYPED_ARRAY_SUPPORT) {
  26096. this[offset] = (value >>> 8);
  26097. this[offset + 1] = (value & 0xff);
  26098. } else {
  26099. objectWriteUInt16(this, value, offset, false);
  26100. }
  26101. return offset + 2
  26102. };
  26103. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  26104. value = +value;
  26105. offset = offset | 0;
  26106. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  26107. if (Buffer.TYPED_ARRAY_SUPPORT) {
  26108. this[offset] = (value & 0xff);
  26109. this[offset + 1] = (value >>> 8);
  26110. this[offset + 2] = (value >>> 16);
  26111. this[offset + 3] = (value >>> 24);
  26112. } else {
  26113. objectWriteUInt32(this, value, offset, true);
  26114. }
  26115. return offset + 4
  26116. };
  26117. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  26118. value = +value;
  26119. offset = offset | 0;
  26120. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  26121. if (value < 0) value = 0xffffffff + value + 1;
  26122. if (Buffer.TYPED_ARRAY_SUPPORT) {
  26123. this[offset] = (value >>> 24);
  26124. this[offset + 1] = (value >>> 16);
  26125. this[offset + 2] = (value >>> 8);
  26126. this[offset + 3] = (value & 0xff);
  26127. } else {
  26128. objectWriteUInt32(this, value, offset, false);
  26129. }
  26130. return offset + 4
  26131. };
  26132. function checkIEEE754 (buf, value, offset, ext, max, min) {
  26133. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  26134. if (offset < 0) throw new RangeError('Index out of range')
  26135. }
  26136. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  26137. if (!noAssert) {
  26138. checkIEEE754(buf, value, offset, 4);
  26139. }
  26140. write(buf, value, offset, littleEndian, 23, 4);
  26141. return offset + 4
  26142. }
  26143. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  26144. return writeFloat(this, value, offset, true, noAssert)
  26145. };
  26146. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  26147. return writeFloat(this, value, offset, false, noAssert)
  26148. };
  26149. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  26150. if (!noAssert) {
  26151. checkIEEE754(buf, value, offset, 8);
  26152. }
  26153. write(buf, value, offset, littleEndian, 52, 8);
  26154. return offset + 8
  26155. }
  26156. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  26157. return writeDouble(this, value, offset, true, noAssert)
  26158. };
  26159. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  26160. return writeDouble(this, value, offset, false, noAssert)
  26161. };
  26162. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  26163. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  26164. if (!start) start = 0;
  26165. if (!end && end !== 0) end = this.length;
  26166. if (targetStart >= target.length) targetStart = target.length;
  26167. if (!targetStart) targetStart = 0;
  26168. if (end > 0 && end < start) end = start;
  26169. // Copy 0 bytes; we're done
  26170. if (end === start) return 0
  26171. if (target.length === 0 || this.length === 0) return 0
  26172. // Fatal error conditions
  26173. if (targetStart < 0) {
  26174. throw new RangeError('targetStart out of bounds')
  26175. }
  26176. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  26177. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  26178. // Are we oob?
  26179. if (end > this.length) end = this.length;
  26180. if (target.length - targetStart < end - start) {
  26181. end = target.length - targetStart + start;
  26182. }
  26183. var len = end - start;
  26184. var i;
  26185. if (this === target && start < targetStart && targetStart < end) {
  26186. // descending copy from end
  26187. for (i = len - 1; i >= 0; --i) {
  26188. target[i + targetStart] = this[i + start];
  26189. }
  26190. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  26191. // ascending copy from start
  26192. for (i = 0; i < len; ++i) {
  26193. target[i + targetStart] = this[i + start];
  26194. }
  26195. } else {
  26196. Uint8Array.prototype.set.call(
  26197. target,
  26198. this.subarray(start, start + len),
  26199. targetStart
  26200. );
  26201. }
  26202. return len
  26203. };
  26204. // Usage:
  26205. // buffer.fill(number[, offset[, end]])
  26206. // buffer.fill(buffer[, offset[, end]])
  26207. // buffer.fill(string[, offset[, end]][, encoding])
  26208. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  26209. // Handle string cases:
  26210. if (typeof val === 'string') {
  26211. if (typeof start === 'string') {
  26212. encoding = start;
  26213. start = 0;
  26214. end = this.length;
  26215. } else if (typeof end === 'string') {
  26216. encoding = end;
  26217. end = this.length;
  26218. }
  26219. if (val.length === 1) {
  26220. var code = val.charCodeAt(0);
  26221. if (code < 256) {
  26222. val = code;
  26223. }
  26224. }
  26225. if (encoding !== undefined && typeof encoding !== 'string') {
  26226. throw new TypeError('encoding must be a string')
  26227. }
  26228. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  26229. throw new TypeError('Unknown encoding: ' + encoding)
  26230. }
  26231. } else if (typeof val === 'number') {
  26232. val = val & 255;
  26233. }
  26234. // Invalid ranges are not set to a default, so can range check early.
  26235. if (start < 0 || this.length < start || this.length < end) {
  26236. throw new RangeError('Out of range index')
  26237. }
  26238. if (end <= start) {
  26239. return this
  26240. }
  26241. start = start >>> 0;
  26242. end = end === undefined ? this.length : end >>> 0;
  26243. if (!val) val = 0;
  26244. var i;
  26245. if (typeof val === 'number') {
  26246. for (i = start; i < end; ++i) {
  26247. this[i] = val;
  26248. }
  26249. } else {
  26250. var bytes = internalIsBuffer(val)
  26251. ? val
  26252. : utf8ToBytes(new Buffer(val, encoding).toString());
  26253. var len = bytes.length;
  26254. for (i = 0; i < end - start; ++i) {
  26255. this[i + start] = bytes[i % len];
  26256. }
  26257. }
  26258. return this
  26259. };
  26260. // HELPER FUNCTIONS
  26261. // ================
  26262. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
  26263. function base64clean (str) {
  26264. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  26265. str = stringtrim(str).replace(INVALID_BASE64_RE, '');
  26266. // Node converts strings with length < 2 to ''
  26267. if (str.length < 2) return ''
  26268. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  26269. while (str.length % 4 !== 0) {
  26270. str = str + '=';
  26271. }
  26272. return str
  26273. }
  26274. function stringtrim (str) {
  26275. if (str.trim) return str.trim()
  26276. return str.replace(/^\s+|\s+$/g, '')
  26277. }
  26278. function toHex (n) {
  26279. if (n < 16) return '0' + n.toString(16)
  26280. return n.toString(16)
  26281. }
  26282. function utf8ToBytes (string, units) {
  26283. units = units || Infinity;
  26284. var codePoint;
  26285. var length = string.length;
  26286. var leadSurrogate = null;
  26287. var bytes = [];
  26288. for (var i = 0; i < length; ++i) {
  26289. codePoint = string.charCodeAt(i);
  26290. // is surrogate component
  26291. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  26292. // last char was a lead
  26293. if (!leadSurrogate) {
  26294. // no lead yet
  26295. if (codePoint > 0xDBFF) {
  26296. // unexpected trail
  26297. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  26298. continue
  26299. } else if (i + 1 === length) {
  26300. // unpaired lead
  26301. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  26302. continue
  26303. }
  26304. // valid lead
  26305. leadSurrogate = codePoint;
  26306. continue
  26307. }
  26308. // 2 leads in a row
  26309. if (codePoint < 0xDC00) {
  26310. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  26311. leadSurrogate = codePoint;
  26312. continue
  26313. }
  26314. // valid surrogate pair
  26315. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
  26316. } else if (leadSurrogate) {
  26317. // valid bmp char, but last char was a lead
  26318. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  26319. }
  26320. leadSurrogate = null;
  26321. // encode utf8
  26322. if (codePoint < 0x80) {
  26323. if ((units -= 1) < 0) break
  26324. bytes.push(codePoint);
  26325. } else if (codePoint < 0x800) {
  26326. if ((units -= 2) < 0) break
  26327. bytes.push(
  26328. codePoint >> 0x6 | 0xC0,
  26329. codePoint & 0x3F | 0x80
  26330. );
  26331. } else if (codePoint < 0x10000) {
  26332. if ((units -= 3) < 0) break
  26333. bytes.push(
  26334. codePoint >> 0xC | 0xE0,
  26335. codePoint >> 0x6 & 0x3F | 0x80,
  26336. codePoint & 0x3F | 0x80
  26337. );
  26338. } else if (codePoint < 0x110000) {
  26339. if ((units -= 4) < 0) break
  26340. bytes.push(
  26341. codePoint >> 0x12 | 0xF0,
  26342. codePoint >> 0xC & 0x3F | 0x80,
  26343. codePoint >> 0x6 & 0x3F | 0x80,
  26344. codePoint & 0x3F | 0x80
  26345. );
  26346. } else {
  26347. throw new Error('Invalid code point')
  26348. }
  26349. }
  26350. return bytes
  26351. }
  26352. function asciiToBytes (str) {
  26353. var byteArray = [];
  26354. for (var i = 0; i < str.length; ++i) {
  26355. // Node's code seems to be doing this and not & 0x7F..
  26356. byteArray.push(str.charCodeAt(i) & 0xFF);
  26357. }
  26358. return byteArray
  26359. }
  26360. function utf16leToBytes (str, units) {
  26361. var c, hi, lo;
  26362. var byteArray = [];
  26363. for (var i = 0; i < str.length; ++i) {
  26364. if ((units -= 2) < 0) break
  26365. c = str.charCodeAt(i);
  26366. hi = c >> 8;
  26367. lo = c % 256;
  26368. byteArray.push(lo);
  26369. byteArray.push(hi);
  26370. }
  26371. return byteArray
  26372. }
  26373. function base64ToBytes (str) {
  26374. return toByteArray(base64clean(str))
  26375. }
  26376. function blitBuffer (src, dst, offset, length) {
  26377. for (var i = 0; i < length; ++i) {
  26378. if ((i + offset >= dst.length) || (i >= src.length)) break
  26379. dst[i + offset] = src[i];
  26380. }
  26381. return i
  26382. }
  26383. function isnan (val) {
  26384. return val !== val // eslint-disable-line no-self-compare
  26385. }
  26386. // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
  26387. // The _isBuffer check is for Safari 5-7 support, because it's missing
  26388. // Object.prototype.constructor. Remove this eventually
  26389. function isBuffer$1(obj) {
  26390. return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))
  26391. }
  26392. function isFastBuffer (obj) {
  26393. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  26394. }
  26395. // For Node v0.10 support. Remove this eventually.
  26396. function isSlowBuffer (obj) {
  26397. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))
  26398. }
  26399. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  26400. function encode$1(decoded) {
  26401. var sourceFileIndex = 0; // second field
  26402. var sourceCodeLine = 0; // third field
  26403. var sourceCodeColumn = 0; // fourth field
  26404. var nameIndex = 0; // fifth field
  26405. var mappings = '';
  26406. for (var i = 0; i < decoded.length; i++) {
  26407. var line = decoded[i];
  26408. if (i > 0)
  26409. mappings += ';';
  26410. if (line.length === 0)
  26411. continue;
  26412. var generatedCodeColumn = 0; // first field
  26413. var lineMappings = [];
  26414. for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
  26415. var segment = line_1[_i];
  26416. var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
  26417. generatedCodeColumn = segment[0];
  26418. if (segment.length > 1) {
  26419. segmentMappings +=
  26420. encodeInteger(segment[1] - sourceFileIndex) +
  26421. encodeInteger(segment[2] - sourceCodeLine) +
  26422. encodeInteger(segment[3] - sourceCodeColumn);
  26423. sourceFileIndex = segment[1];
  26424. sourceCodeLine = segment[2];
  26425. sourceCodeColumn = segment[3];
  26426. }
  26427. if (segment.length === 5) {
  26428. segmentMappings += encodeInteger(segment[4] - nameIndex);
  26429. nameIndex = segment[4];
  26430. }
  26431. lineMappings.push(segmentMappings);
  26432. }
  26433. mappings += lineMappings.join(',');
  26434. }
  26435. return mappings;
  26436. }
  26437. function encodeInteger(num) {
  26438. var result = '';
  26439. num = num < 0 ? (-num << 1) | 1 : num << 1;
  26440. do {
  26441. var clamped = num & 31;
  26442. num >>>= 5;
  26443. if (num > 0) {
  26444. clamped |= 32;
  26445. }
  26446. result += chars[clamped];
  26447. } while (num > 0);
  26448. return result;
  26449. }
  26450. var BitSet = function BitSet(arg) {
  26451. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  26452. };
  26453. BitSet.prototype.add = function add (n) {
  26454. this.bits[n >> 5] |= 1 << (n & 31);
  26455. };
  26456. BitSet.prototype.has = function has (n) {
  26457. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  26458. };
  26459. var Chunk = function Chunk(start, end, content) {
  26460. this.start = start;
  26461. this.end = end;
  26462. this.original = content;
  26463. this.intro = '';
  26464. this.outro = '';
  26465. this.content = content;
  26466. this.storeName = false;
  26467. this.edited = false;
  26468. // we make these non-enumerable, for sanity while debugging
  26469. Object.defineProperties(this, {
  26470. previous: { writable: true, value: null },
  26471. next: { writable: true, value: null }
  26472. });
  26473. };
  26474. Chunk.prototype.appendLeft = function appendLeft (content) {
  26475. this.outro += content;
  26476. };
  26477. Chunk.prototype.appendRight = function appendRight (content) {
  26478. this.intro = this.intro + content;
  26479. };
  26480. Chunk.prototype.clone = function clone () {
  26481. var chunk = new Chunk(this.start, this.end, this.original);
  26482. chunk.intro = this.intro;
  26483. chunk.outro = this.outro;
  26484. chunk.content = this.content;
  26485. chunk.storeName = this.storeName;
  26486. chunk.edited = this.edited;
  26487. return chunk;
  26488. };
  26489. Chunk.prototype.contains = function contains (index) {
  26490. return this.start < index && index < this.end;
  26491. };
  26492. Chunk.prototype.eachNext = function eachNext (fn) {
  26493. var chunk = this;
  26494. while (chunk) {
  26495. fn(chunk);
  26496. chunk = chunk.next;
  26497. }
  26498. };
  26499. Chunk.prototype.eachPrevious = function eachPrevious (fn) {
  26500. var chunk = this;
  26501. while (chunk) {
  26502. fn(chunk);
  26503. chunk = chunk.previous;
  26504. }
  26505. };
  26506. Chunk.prototype.edit = function edit (content, storeName, contentOnly) {
  26507. this.content = content;
  26508. if (!contentOnly) {
  26509. this.intro = '';
  26510. this.outro = '';
  26511. }
  26512. this.storeName = storeName;
  26513. this.edited = true;
  26514. return this;
  26515. };
  26516. Chunk.prototype.prependLeft = function prependLeft (content) {
  26517. this.outro = content + this.outro;
  26518. };
  26519. Chunk.prototype.prependRight = function prependRight (content) {
  26520. this.intro = content + this.intro;
  26521. };
  26522. Chunk.prototype.split = function split (index) {
  26523. var sliceIndex = index - this.start;
  26524. var originalBefore = this.original.slice(0, sliceIndex);
  26525. var originalAfter = this.original.slice(sliceIndex);
  26526. this.original = originalBefore;
  26527. var newChunk = new Chunk(index, this.end, originalAfter);
  26528. newChunk.outro = this.outro;
  26529. this.outro = '';
  26530. this.end = index;
  26531. if (this.edited) {
  26532. // TODO is this block necessary?...
  26533. newChunk.edit('', false);
  26534. this.content = '';
  26535. } else {
  26536. this.content = originalBefore;
  26537. }
  26538. newChunk.next = this.next;
  26539. if (newChunk.next) { newChunk.next.previous = newChunk; }
  26540. newChunk.previous = this;
  26541. this.next = newChunk;
  26542. return newChunk;
  26543. };
  26544. Chunk.prototype.toString = function toString () {
  26545. return this.intro + this.content + this.outro;
  26546. };
  26547. Chunk.prototype.trimEnd = function trimEnd (rx) {
  26548. this.outro = this.outro.replace(rx, '');
  26549. if (this.outro.length) { return true; }
  26550. var trimmed = this.content.replace(rx, '');
  26551. if (trimmed.length) {
  26552. if (trimmed !== this.content) {
  26553. this.split(this.start + trimmed.length).edit('', undefined, true);
  26554. }
  26555. return true;
  26556. } else {
  26557. this.edit('', undefined, true);
  26558. this.intro = this.intro.replace(rx, '');
  26559. if (this.intro.length) { return true; }
  26560. }
  26561. };
  26562. Chunk.prototype.trimStart = function trimStart (rx) {
  26563. this.intro = this.intro.replace(rx, '');
  26564. if (this.intro.length) { return true; }
  26565. var trimmed = this.content.replace(rx, '');
  26566. if (trimmed.length) {
  26567. if (trimmed !== this.content) {
  26568. this.split(this.end - trimmed.length);
  26569. this.edit('', undefined, true);
  26570. }
  26571. return true;
  26572. } else {
  26573. this.edit('', undefined, true);
  26574. this.outro = this.outro.replace(rx, '');
  26575. if (this.outro.length) { return true; }
  26576. }
  26577. };
  26578. var btoa = function () {
  26579. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  26580. };
  26581. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  26582. btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
  26583. } else if (typeof Buffer === 'function') {
  26584. btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
  26585. }
  26586. var SourceMap = function SourceMap(properties) {
  26587. this.version = 3;
  26588. this.file = properties.file;
  26589. this.sources = properties.sources;
  26590. this.sourcesContent = properties.sourcesContent;
  26591. this.names = properties.names;
  26592. this.mappings = encode$1(properties.mappings);
  26593. };
  26594. SourceMap.prototype.toString = function toString () {
  26595. return JSON.stringify(this);
  26596. };
  26597. SourceMap.prototype.toUrl = function toUrl () {
  26598. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  26599. };
  26600. function guessIndent(code) {
  26601. var lines = code.split('\n');
  26602. var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
  26603. var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
  26604. if (tabbed.length === 0 && spaced.length === 0) {
  26605. return null;
  26606. }
  26607. // More lines tabbed than spaced? Assume tabs, and
  26608. // default to tabs in the case of a tie (or nothing
  26609. // to go on)
  26610. if (tabbed.length >= spaced.length) {
  26611. return '\t';
  26612. }
  26613. // Otherwise, we need to guess the multiple
  26614. var min = spaced.reduce(function (previous, current) {
  26615. var numSpaces = /^ +/.exec(current)[0].length;
  26616. return Math.min(numSpaces, previous);
  26617. }, Infinity);
  26618. return new Array(min + 1).join(' ');
  26619. }
  26620. function getRelativePath(from, to) {
  26621. var fromParts = from.split(/[/\\]/);
  26622. var toParts = to.split(/[/\\]/);
  26623. fromParts.pop(); // get dirname
  26624. while (fromParts[0] === toParts[0]) {
  26625. fromParts.shift();
  26626. toParts.shift();
  26627. }
  26628. if (fromParts.length) {
  26629. var i = fromParts.length;
  26630. while (i--) { fromParts[i] = '..'; }
  26631. }
  26632. return fromParts.concat(toParts).join('/');
  26633. }
  26634. var toString = Object.prototype.toString;
  26635. function isObject$1(thing) {
  26636. return toString.call(thing) === '[object Object]';
  26637. }
  26638. function getLocator(source) {
  26639. var originalLines = source.split('\n');
  26640. var lineOffsets = [];
  26641. for (var i = 0, pos = 0; i < originalLines.length; i++) {
  26642. lineOffsets.push(pos);
  26643. pos += originalLines[i].length + 1;
  26644. }
  26645. return function locate(index) {
  26646. var i = 0;
  26647. var j = lineOffsets.length;
  26648. while (i < j) {
  26649. var m = (i + j) >> 1;
  26650. if (index < lineOffsets[m]) {
  26651. j = m;
  26652. } else {
  26653. i = m + 1;
  26654. }
  26655. }
  26656. var line = i - 1;
  26657. var column = index - lineOffsets[line];
  26658. return { line: line, column: column };
  26659. };
  26660. }
  26661. var Mappings = function Mappings(hires) {
  26662. this.hires = hires;
  26663. this.generatedCodeLine = 0;
  26664. this.generatedCodeColumn = 0;
  26665. this.raw = [];
  26666. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  26667. this.pending = null;
  26668. };
  26669. Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) {
  26670. if (content.length) {
  26671. var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  26672. if (nameIndex >= 0) {
  26673. segment.push(nameIndex);
  26674. }
  26675. this.rawSegments.push(segment);
  26676. } else if (this.pending) {
  26677. this.rawSegments.push(this.pending);
  26678. }
  26679. this.advance(content);
  26680. this.pending = null;
  26681. };
  26682. Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) {
  26683. var originalCharIndex = chunk.start;
  26684. var first = true;
  26685. while (originalCharIndex < chunk.end) {
  26686. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  26687. this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
  26688. }
  26689. if (original[originalCharIndex] === '\n') {
  26690. loc.line += 1;
  26691. loc.column = 0;
  26692. this.generatedCodeLine += 1;
  26693. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  26694. this.generatedCodeColumn = 0;
  26695. first = true;
  26696. } else {
  26697. loc.column += 1;
  26698. this.generatedCodeColumn += 1;
  26699. first = false;
  26700. }
  26701. originalCharIndex += 1;
  26702. }
  26703. this.pending = null;
  26704. };
  26705. Mappings.prototype.advance = function advance (str) {
  26706. if (!str) { return; }
  26707. var lines = str.split('\n');
  26708. if (lines.length > 1) {
  26709. for (var i = 0; i < lines.length - 1; i++) {
  26710. this.generatedCodeLine++;
  26711. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  26712. }
  26713. this.generatedCodeColumn = 0;
  26714. }
  26715. this.generatedCodeColumn += lines[lines.length - 1].length;
  26716. };
  26717. var n = '\n';
  26718. var warned = {
  26719. insertLeft: false,
  26720. insertRight: false,
  26721. storeName: false
  26722. };
  26723. var MagicString = function MagicString(string, options) {
  26724. if ( options === void 0 ) options = {};
  26725. var chunk = new Chunk(0, string.length, string);
  26726. Object.defineProperties(this, {
  26727. original: { writable: true, value: string },
  26728. outro: { writable: true, value: '' },
  26729. intro: { writable: true, value: '' },
  26730. firstChunk: { writable: true, value: chunk },
  26731. lastChunk: { writable: true, value: chunk },
  26732. lastSearchedChunk: { writable: true, value: chunk },
  26733. byStart: { writable: true, value: {} },
  26734. byEnd: { writable: true, value: {} },
  26735. filename: { writable: true, value: options.filename },
  26736. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  26737. sourcemapLocations: { writable: true, value: new BitSet() },
  26738. storedNames: { writable: true, value: {} },
  26739. indentStr: { writable: true, value: guessIndent(string) }
  26740. });
  26741. this.byStart[0] = chunk;
  26742. this.byEnd[string.length] = chunk;
  26743. };
  26744. MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) {
  26745. this.sourcemapLocations.add(char);
  26746. };
  26747. MagicString.prototype.append = function append (content) {
  26748. if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
  26749. this.outro += content;
  26750. return this;
  26751. };
  26752. MagicString.prototype.appendLeft = function appendLeft (index, content) {
  26753. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  26754. this._split(index);
  26755. var chunk = this.byEnd[index];
  26756. if (chunk) {
  26757. chunk.appendLeft(content);
  26758. } else {
  26759. this.intro += content;
  26760. }
  26761. return this;
  26762. };
  26763. MagicString.prototype.appendRight = function appendRight (index, content) {
  26764. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  26765. this._split(index);
  26766. var chunk = this.byStart[index];
  26767. if (chunk) {
  26768. chunk.appendRight(content);
  26769. } else {
  26770. this.outro += content;
  26771. }
  26772. return this;
  26773. };
  26774. MagicString.prototype.clone = function clone () {
  26775. var cloned = new MagicString(this.original, { filename: this.filename });
  26776. var originalChunk = this.firstChunk;
  26777. var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  26778. while (originalChunk) {
  26779. cloned.byStart[clonedChunk.start] = clonedChunk;
  26780. cloned.byEnd[clonedChunk.end] = clonedChunk;
  26781. var nextOriginalChunk = originalChunk.next;
  26782. var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  26783. if (nextClonedChunk) {
  26784. clonedChunk.next = nextClonedChunk;
  26785. nextClonedChunk.previous = clonedChunk;
  26786. clonedChunk = nextClonedChunk;
  26787. }
  26788. originalChunk = nextOriginalChunk;
  26789. }
  26790. cloned.lastChunk = clonedChunk;
  26791. if (this.indentExclusionRanges) {
  26792. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  26793. }
  26794. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  26795. cloned.intro = this.intro;
  26796. cloned.outro = this.outro;
  26797. return cloned;
  26798. };
  26799. MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) {
  26800. var this$1$1 = this;
  26801. options = options || {};
  26802. var sourceIndex = 0;
  26803. var names = Object.keys(this.storedNames);
  26804. var mappings = new Mappings(options.hires);
  26805. var locate = getLocator(this.original);
  26806. if (this.intro) {
  26807. mappings.advance(this.intro);
  26808. }
  26809. this.firstChunk.eachNext(function (chunk) {
  26810. var loc = locate(chunk.start);
  26811. if (chunk.intro.length) { mappings.advance(chunk.intro); }
  26812. if (chunk.edited) {
  26813. mappings.addEdit(
  26814. sourceIndex,
  26815. chunk.content,
  26816. loc,
  26817. chunk.storeName ? names.indexOf(chunk.original) : -1
  26818. );
  26819. } else {
  26820. mappings.addUneditedChunk(sourceIndex, chunk, this$1$1.original, loc, this$1$1.sourcemapLocations);
  26821. }
  26822. if (chunk.outro.length) { mappings.advance(chunk.outro); }
  26823. });
  26824. return {
  26825. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  26826. sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
  26827. sourcesContent: options.includeContent ? [this.original] : [null],
  26828. names: names,
  26829. mappings: mappings.raw
  26830. };
  26831. };
  26832. MagicString.prototype.generateMap = function generateMap (options) {
  26833. return new SourceMap(this.generateDecodedMap(options));
  26834. };
  26835. MagicString.prototype.getIndentString = function getIndentString () {
  26836. return this.indentStr === null ? '\t' : this.indentStr;
  26837. };
  26838. MagicString.prototype.indent = function indent (indentStr, options) {
  26839. var pattern = /^[^\r\n]/gm;
  26840. if (isObject$1(indentStr)) {
  26841. options = indentStr;
  26842. indentStr = undefined;
  26843. }
  26844. indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
  26845. if (indentStr === '') { return this; } // noop
  26846. options = options || {};
  26847. // Process exclusion ranges
  26848. var isExcluded = {};
  26849. if (options.exclude) {
  26850. var exclusions =
  26851. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  26852. exclusions.forEach(function (exclusion) {
  26853. for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
  26854. isExcluded[i] = true;
  26855. }
  26856. });
  26857. }
  26858. var shouldIndentNextCharacter = options.indentStart !== false;
  26859. var replacer = function (match) {
  26860. if (shouldIndentNextCharacter) { return ("" + indentStr + match); }
  26861. shouldIndentNextCharacter = true;
  26862. return match;
  26863. };
  26864. this.intro = this.intro.replace(pattern, replacer);
  26865. var charIndex = 0;
  26866. var chunk = this.firstChunk;
  26867. while (chunk) {
  26868. var end = chunk.end;
  26869. if (chunk.edited) {
  26870. if (!isExcluded[charIndex]) {
  26871. chunk.content = chunk.content.replace(pattern, replacer);
  26872. if (chunk.content.length) {
  26873. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  26874. }
  26875. }
  26876. } else {
  26877. charIndex = chunk.start;
  26878. while (charIndex < end) {
  26879. if (!isExcluded[charIndex]) {
  26880. var char = this.original[charIndex];
  26881. if (char === '\n') {
  26882. shouldIndentNextCharacter = true;
  26883. } else if (char !== '\r' && shouldIndentNextCharacter) {
  26884. shouldIndentNextCharacter = false;
  26885. if (charIndex === chunk.start) {
  26886. chunk.prependRight(indentStr);
  26887. } else {
  26888. this._splitChunk(chunk, charIndex);
  26889. chunk = chunk.next;
  26890. chunk.prependRight(indentStr);
  26891. }
  26892. }
  26893. }
  26894. charIndex += 1;
  26895. }
  26896. }
  26897. charIndex = chunk.end;
  26898. chunk = chunk.next;
  26899. }
  26900. this.outro = this.outro.replace(pattern, replacer);
  26901. return this;
  26902. };
  26903. MagicString.prototype.insert = function insert () {
  26904. throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
  26905. };
  26906. MagicString.prototype.insertLeft = function insertLeft (index, content) {
  26907. if (!warned.insertLeft) {
  26908. console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console
  26909. warned.insertLeft = true;
  26910. }
  26911. return this.appendLeft(index, content);
  26912. };
  26913. MagicString.prototype.insertRight = function insertRight (index, content) {
  26914. if (!warned.insertRight) {
  26915. console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console
  26916. warned.insertRight = true;
  26917. }
  26918. return this.prependRight(index, content);
  26919. };
  26920. MagicString.prototype.move = function move (start, end, index) {
  26921. if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); }
  26922. this._split(start);
  26923. this._split(end);
  26924. this._split(index);
  26925. var first = this.byStart[start];
  26926. var last = this.byEnd[end];
  26927. var oldLeft = first.previous;
  26928. var oldRight = last.next;
  26929. var newRight = this.byStart[index];
  26930. if (!newRight && last === this.lastChunk) { return this; }
  26931. var newLeft = newRight ? newRight.previous : this.lastChunk;
  26932. if (oldLeft) { oldLeft.next = oldRight; }
  26933. if (oldRight) { oldRight.previous = oldLeft; }
  26934. if (newLeft) { newLeft.next = first; }
  26935. if (newRight) { newRight.previous = last; }
  26936. if (!first.previous) { this.firstChunk = last.next; }
  26937. if (!last.next) {
  26938. this.lastChunk = first.previous;
  26939. this.lastChunk.next = null;
  26940. }
  26941. first.previous = newLeft;
  26942. last.next = newRight || null;
  26943. if (!newLeft) { this.firstChunk = first; }
  26944. if (!newRight) { this.lastChunk = last; }
  26945. return this;
  26946. };
  26947. MagicString.prototype.overwrite = function overwrite (start, end, content, options) {
  26948. if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); }
  26949. while (start < 0) { start += this.original.length; }
  26950. while (end < 0) { end += this.original.length; }
  26951. if (end > this.original.length) { throw new Error('end is out of bounds'); }
  26952. if (start === end)
  26953. { throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead'); }
  26954. this._split(start);
  26955. this._split(end);
  26956. if (options === true) {
  26957. if (!warned.storeName) {
  26958. 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
  26959. warned.storeName = true;
  26960. }
  26961. options = { storeName: true };
  26962. }
  26963. var storeName = options !== undefined ? options.storeName : false;
  26964. var contentOnly = options !== undefined ? options.contentOnly : false;
  26965. if (storeName) {
  26966. var original = this.original.slice(start, end);
  26967. this.storedNames[original] = true;
  26968. }
  26969. var first = this.byStart[start];
  26970. var last = this.byEnd[end];
  26971. if (first) {
  26972. if (end > first.end && first.next !== this.byStart[first.end]) {
  26973. throw new Error('Cannot overwrite across a split point');
  26974. }
  26975. first.edit(content, storeName, contentOnly);
  26976. if (first !== last) {
  26977. var chunk = first.next;
  26978. while (chunk !== last) {
  26979. chunk.edit('', false);
  26980. chunk = chunk.next;
  26981. }
  26982. chunk.edit('', false);
  26983. }
  26984. } else {
  26985. // must be inserting at the end
  26986. var newChunk = new Chunk(start, end, '').edit(content, storeName);
  26987. // TODO last chunk in the array may not be the last chunk, if it's moved...
  26988. last.next = newChunk;
  26989. newChunk.previous = last;
  26990. }
  26991. return this;
  26992. };
  26993. MagicString.prototype.prepend = function prepend (content) {
  26994. if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
  26995. this.intro = content + this.intro;
  26996. return this;
  26997. };
  26998. MagicString.prototype.prependLeft = function prependLeft (index, content) {
  26999. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  27000. this._split(index);
  27001. var chunk = this.byEnd[index];
  27002. if (chunk) {
  27003. chunk.prependLeft(content);
  27004. } else {
  27005. this.intro = content + this.intro;
  27006. }
  27007. return this;
  27008. };
  27009. MagicString.prototype.prependRight = function prependRight (index, content) {
  27010. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  27011. this._split(index);
  27012. var chunk = this.byStart[index];
  27013. if (chunk) {
  27014. chunk.prependRight(content);
  27015. } else {
  27016. this.outro = content + this.outro;
  27017. }
  27018. return this;
  27019. };
  27020. MagicString.prototype.remove = function remove (start, end) {
  27021. while (start < 0) { start += this.original.length; }
  27022. while (end < 0) { end += this.original.length; }
  27023. if (start === end) { return this; }
  27024. if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); }
  27025. if (start > end) { throw new Error('end must be greater than start'); }
  27026. this._split(start);
  27027. this._split(end);
  27028. var chunk = this.byStart[start];
  27029. while (chunk) {
  27030. chunk.intro = '';
  27031. chunk.outro = '';
  27032. chunk.edit('');
  27033. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  27034. }
  27035. return this;
  27036. };
  27037. MagicString.prototype.lastChar = function lastChar () {
  27038. if (this.outro.length)
  27039. { return this.outro[this.outro.length - 1]; }
  27040. var chunk = this.lastChunk;
  27041. do {
  27042. if (chunk.outro.length)
  27043. { return chunk.outro[chunk.outro.length - 1]; }
  27044. if (chunk.content.length)
  27045. { return chunk.content[chunk.content.length - 1]; }
  27046. if (chunk.intro.length)
  27047. { return chunk.intro[chunk.intro.length - 1]; }
  27048. } while (chunk = chunk.previous);
  27049. if (this.intro.length)
  27050. { return this.intro[this.intro.length - 1]; }
  27051. return '';
  27052. };
  27053. MagicString.prototype.lastLine = function lastLine () {
  27054. var lineIndex = this.outro.lastIndexOf(n);
  27055. if (lineIndex !== -1)
  27056. { return this.outro.substr(lineIndex + 1); }
  27057. var lineStr = this.outro;
  27058. var chunk = this.lastChunk;
  27059. do {
  27060. if (chunk.outro.length > 0) {
  27061. lineIndex = chunk.outro.lastIndexOf(n);
  27062. if (lineIndex !== -1)
  27063. { return chunk.outro.substr(lineIndex + 1) + lineStr; }
  27064. lineStr = chunk.outro + lineStr;
  27065. }
  27066. if (chunk.content.length > 0) {
  27067. lineIndex = chunk.content.lastIndexOf(n);
  27068. if (lineIndex !== -1)
  27069. { return chunk.content.substr(lineIndex + 1) + lineStr; }
  27070. lineStr = chunk.content + lineStr;
  27071. }
  27072. if (chunk.intro.length > 0) {
  27073. lineIndex = chunk.intro.lastIndexOf(n);
  27074. if (lineIndex !== -1)
  27075. { return chunk.intro.substr(lineIndex + 1) + lineStr; }
  27076. lineStr = chunk.intro + lineStr;
  27077. }
  27078. } while (chunk = chunk.previous);
  27079. lineIndex = this.intro.lastIndexOf(n);
  27080. if (lineIndex !== -1)
  27081. { return this.intro.substr(lineIndex + 1) + lineStr; }
  27082. return this.intro + lineStr;
  27083. };
  27084. MagicString.prototype.slice = function slice (start, end) {
  27085. if ( start === void 0 ) start = 0;
  27086. if ( end === void 0 ) end = this.original.length;
  27087. while (start < 0) { start += this.original.length; }
  27088. while (end < 0) { end += this.original.length; }
  27089. var result = '';
  27090. // find start chunk
  27091. var chunk = this.firstChunk;
  27092. while (chunk && (chunk.start > start || chunk.end <= start)) {
  27093. // found end chunk before start
  27094. if (chunk.start < end && chunk.end >= end) {
  27095. return result;
  27096. }
  27097. chunk = chunk.next;
  27098. }
  27099. if (chunk && chunk.edited && chunk.start !== start)
  27100. { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
  27101. var startChunk = chunk;
  27102. while (chunk) {
  27103. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  27104. result += chunk.intro;
  27105. }
  27106. var containsEnd = chunk.start < end && chunk.end >= end;
  27107. if (containsEnd && chunk.edited && chunk.end !== end)
  27108. { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
  27109. var sliceStart = startChunk === chunk ? start - chunk.start : 0;
  27110. var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  27111. result += chunk.content.slice(sliceStart, sliceEnd);
  27112. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  27113. result += chunk.outro;
  27114. }
  27115. if (containsEnd) {
  27116. break;
  27117. }
  27118. chunk = chunk.next;
  27119. }
  27120. return result;
  27121. };
  27122. // TODO deprecate this? not really very useful
  27123. MagicString.prototype.snip = function snip (start, end) {
  27124. var clone = this.clone();
  27125. clone.remove(0, start);
  27126. clone.remove(end, clone.original.length);
  27127. return clone;
  27128. };
  27129. MagicString.prototype._split = function _split (index) {
  27130. if (this.byStart[index] || this.byEnd[index]) { return; }
  27131. var chunk = this.lastSearchedChunk;
  27132. var searchForward = index > chunk.end;
  27133. while (chunk) {
  27134. if (chunk.contains(index)) { return this._splitChunk(chunk, index); }
  27135. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  27136. }
  27137. };
  27138. MagicString.prototype._splitChunk = function _splitChunk (chunk, index) {
  27139. if (chunk.edited && chunk.content.length) {
  27140. // zero-length edited chunks are a special case (overlapping replacements)
  27141. var loc = getLocator(this.original)(index);
  27142. throw new Error(
  27143. ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")")
  27144. );
  27145. }
  27146. var newChunk = chunk.split(index);
  27147. this.byEnd[index] = chunk;
  27148. this.byStart[index] = newChunk;
  27149. this.byEnd[newChunk.end] = newChunk;
  27150. if (chunk === this.lastChunk) { this.lastChunk = newChunk; }
  27151. this.lastSearchedChunk = chunk;
  27152. return true;
  27153. };
  27154. MagicString.prototype.toString = function toString () {
  27155. var str = this.intro;
  27156. var chunk = this.firstChunk;
  27157. while (chunk) {
  27158. str += chunk.toString();
  27159. chunk = chunk.next;
  27160. }
  27161. return str + this.outro;
  27162. };
  27163. MagicString.prototype.isEmpty = function isEmpty () {
  27164. var chunk = this.firstChunk;
  27165. do {
  27166. if (chunk.intro.length && chunk.intro.trim() ||
  27167. chunk.content.length && chunk.content.trim() ||
  27168. chunk.outro.length && chunk.outro.trim())
  27169. { return false; }
  27170. } while (chunk = chunk.next);
  27171. return true;
  27172. };
  27173. MagicString.prototype.length = function length () {
  27174. var chunk = this.firstChunk;
  27175. var length = 0;
  27176. do {
  27177. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  27178. } while (chunk = chunk.next);
  27179. return length;
  27180. };
  27181. MagicString.prototype.trimLines = function trimLines () {
  27182. return this.trim('[\\r\\n]');
  27183. };
  27184. MagicString.prototype.trim = function trim (charType) {
  27185. return this.trimStart(charType).trimEnd(charType);
  27186. };
  27187. MagicString.prototype.trimEndAborted = function trimEndAborted (charType) {
  27188. var rx = new RegExp((charType || '\\s') + '+$');
  27189. this.outro = this.outro.replace(rx, '');
  27190. if (this.outro.length) { return true; }
  27191. var chunk = this.lastChunk;
  27192. do {
  27193. var end = chunk.end;
  27194. var aborted = chunk.trimEnd(rx);
  27195. // if chunk was trimmed, we have a new lastChunk
  27196. if (chunk.end !== end) {
  27197. if (this.lastChunk === chunk) {
  27198. this.lastChunk = chunk.next;
  27199. }
  27200. this.byEnd[chunk.end] = chunk;
  27201. this.byStart[chunk.next.start] = chunk.next;
  27202. this.byEnd[chunk.next.end] = chunk.next;
  27203. }
  27204. if (aborted) { return true; }
  27205. chunk = chunk.previous;
  27206. } while (chunk);
  27207. return false;
  27208. };
  27209. MagicString.prototype.trimEnd = function trimEnd (charType) {
  27210. this.trimEndAborted(charType);
  27211. return this;
  27212. };
  27213. MagicString.prototype.trimStartAborted = function trimStartAborted (charType) {
  27214. var rx = new RegExp('^' + (charType || '\\s') + '+');
  27215. this.intro = this.intro.replace(rx, '');
  27216. if (this.intro.length) { return true; }
  27217. var chunk = this.firstChunk;
  27218. do {
  27219. var end = chunk.end;
  27220. var aborted = chunk.trimStart(rx);
  27221. if (chunk.end !== end) {
  27222. // special case...
  27223. if (chunk === this.lastChunk) { this.lastChunk = chunk.next; }
  27224. this.byEnd[chunk.end] = chunk;
  27225. this.byStart[chunk.next.start] = chunk.next;
  27226. this.byEnd[chunk.next.end] = chunk.next;
  27227. }
  27228. if (aborted) { return true; }
  27229. chunk = chunk.next;
  27230. } while (chunk);
  27231. return false;
  27232. };
  27233. MagicString.prototype.trimStart = function trimStart (charType) {
  27234. this.trimStartAborted(charType);
  27235. return this;
  27236. };
  27237. var MagicString$1 = MagicString;
  27238. // Copyright Joyent, Inc. and other Node contributors.
  27239. //
  27240. // Permission is hereby granted, free of charge, to any person obtaining a
  27241. // copy of this software and associated documentation files (the
  27242. // "Software"), to deal in the Software without restriction, including
  27243. // without limitation the rights to use, copy, modify, merge, publish,
  27244. // distribute, sublicense, and/or sell copies of the Software, and to permit
  27245. // persons to whom the Software is furnished to do so, subject to the
  27246. // following conditions:
  27247. //
  27248. // The above copyright notice and this permission notice shall be included
  27249. // in all copies or substantial portions of the Software.
  27250. //
  27251. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  27252. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27253. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  27254. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  27255. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  27256. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  27257. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  27258. // resolves . and .. elements in a path array with directory names there
  27259. // must be no slashes, empty elements, or device names (c:\) in the array
  27260. // (so also no leading and trailing slashes - it does not distinguish
  27261. // relative and absolute paths)
  27262. function normalizeArray(parts, allowAboveRoot) {
  27263. // if the path tries to go above the root, `up` ends up > 0
  27264. var up = 0;
  27265. for (var i = parts.length - 1; i >= 0; i--) {
  27266. var last = parts[i];
  27267. if (last === '.') {
  27268. parts.splice(i, 1);
  27269. } else if (last === '..') {
  27270. parts.splice(i, 1);
  27271. up++;
  27272. } else if (up) {
  27273. parts.splice(i, 1);
  27274. up--;
  27275. }
  27276. }
  27277. // if the path is allowed to go above the root, restore leading ..s
  27278. if (allowAboveRoot) {
  27279. for (; up--; up) {
  27280. parts.unshift('..');
  27281. }
  27282. }
  27283. return parts;
  27284. }
  27285. // Split a filename into [root, dir, basename, ext], unix version
  27286. // 'root' is just a slash, or nothing.
  27287. var splitPathRe =
  27288. /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
  27289. var splitPath = function(filename) {
  27290. return splitPathRe.exec(filename).slice(1);
  27291. };
  27292. // path.resolve([from ...], to)
  27293. // posix version
  27294. function resolve$2() {
  27295. var resolvedPath = '',
  27296. resolvedAbsolute = false;
  27297. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  27298. var path = (i >= 0) ? arguments[i] : '/';
  27299. // Skip empty and invalid entries
  27300. if (typeof path !== 'string') {
  27301. throw new TypeError('Arguments to path.resolve must be strings');
  27302. } else if (!path) {
  27303. continue;
  27304. }
  27305. resolvedPath = path + '/' + resolvedPath;
  27306. resolvedAbsolute = path.charAt(0) === '/';
  27307. }
  27308. // At this point the path should be resolved to a full absolute path, but
  27309. // handle relative paths to be safe (might happen when process.cwd() fails)
  27310. // Normalize the path
  27311. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  27312. return !!p;
  27313. }), !resolvedAbsolute).join('/');
  27314. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  27315. }
  27316. // path.normalize(path)
  27317. // posix version
  27318. function normalize(path) {
  27319. var isPathAbsolute = isAbsolute$1(path),
  27320. trailingSlash = substr(path, -1) === '/';
  27321. // Normalize the path
  27322. path = normalizeArray(filter(path.split('/'), function(p) {
  27323. return !!p;
  27324. }), !isPathAbsolute).join('/');
  27325. if (!path && !isPathAbsolute) {
  27326. path = '.';
  27327. }
  27328. if (path && trailingSlash) {
  27329. path += '/';
  27330. }
  27331. return (isPathAbsolute ? '/' : '') + path;
  27332. }
  27333. // posix version
  27334. function isAbsolute$1(path) {
  27335. return path.charAt(0) === '/';
  27336. }
  27337. // posix version
  27338. function join$1() {
  27339. var paths = Array.prototype.slice.call(arguments, 0);
  27340. return normalize(filter(paths, function(p, index) {
  27341. if (typeof p !== 'string') {
  27342. throw new TypeError('Arguments to path.join must be strings');
  27343. }
  27344. return p;
  27345. }).join('/'));
  27346. }
  27347. // path.relative(from, to)
  27348. // posix version
  27349. function relative$1(from, to) {
  27350. from = resolve$2(from).substr(1);
  27351. to = resolve$2(to).substr(1);
  27352. function trim(arr) {
  27353. var start = 0;
  27354. for (; start < arr.length; start++) {
  27355. if (arr[start] !== '') break;
  27356. }
  27357. var end = arr.length - 1;
  27358. for (; end >= 0; end--) {
  27359. if (arr[end] !== '') break;
  27360. }
  27361. if (start > end) return [];
  27362. return arr.slice(start, end - start + 1);
  27363. }
  27364. var fromParts = trim(from.split('/'));
  27365. var toParts = trim(to.split('/'));
  27366. var length = Math.min(fromParts.length, toParts.length);
  27367. var samePartsLength = length;
  27368. for (var i = 0; i < length; i++) {
  27369. if (fromParts[i] !== toParts[i]) {
  27370. samePartsLength = i;
  27371. break;
  27372. }
  27373. }
  27374. var outputParts = [];
  27375. for (var i = samePartsLength; i < fromParts.length; i++) {
  27376. outputParts.push('..');
  27377. }
  27378. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  27379. return outputParts.join('/');
  27380. }
  27381. var sep$1 = '/';
  27382. var delimiter$1 = ':';
  27383. function dirname$2(path) {
  27384. var result = splitPath(path),
  27385. root = result[0],
  27386. dir = result[1];
  27387. if (!root && !dir) {
  27388. // No dirname whatsoever
  27389. return '.';
  27390. }
  27391. if (dir) {
  27392. // It has a dirname, strip trailing slash
  27393. dir = dir.substr(0, dir.length - 1);
  27394. }
  27395. return root + dir;
  27396. }
  27397. function basename(path, ext) {
  27398. var f = splitPath(path)[2];
  27399. // TODO: make this comparison case-insensitive on windows?
  27400. if (ext && f.substr(-1 * ext.length) === ext) {
  27401. f = f.substr(0, f.length - ext.length);
  27402. }
  27403. return f;
  27404. }
  27405. function extname(path) {
  27406. return splitPath(path)[3];
  27407. }
  27408. var path = {
  27409. extname: extname,
  27410. basename: basename,
  27411. dirname: dirname$2,
  27412. sep: sep$1,
  27413. delimiter: delimiter$1,
  27414. relative: relative$1,
  27415. join: join$1,
  27416. isAbsolute: isAbsolute$1,
  27417. normalize: normalize,
  27418. resolve: resolve$2
  27419. };
  27420. function filter (xs, f) {
  27421. if (xs.filter) return xs.filter(f);
  27422. var res = [];
  27423. for (var i = 0; i < xs.length; i++) {
  27424. if (f(xs[i], i, xs)) res.push(xs[i]);
  27425. }
  27426. return res;
  27427. }
  27428. // String.prototype.substr - negative index don't work in IE8
  27429. var substr = 'ab'.substr(-1) === 'b' ?
  27430. function (str, start, len) { return str.substr(start, len) } :
  27431. function (str, start, len) {
  27432. if (start < 0) start = str.length + start;
  27433. return str.substr(start, len);
  27434. }
  27435. ;
  27436. var _polyfillNode_path = /*#__PURE__*/Object.freeze({
  27437. __proto__: null,
  27438. basename: basename,
  27439. default: path,
  27440. delimiter: delimiter$1,
  27441. dirname: dirname$2,
  27442. extname: extname,
  27443. isAbsolute: isAbsolute$1,
  27444. join: join$1,
  27445. normalize: normalize,
  27446. relative: relative$1,
  27447. resolve: resolve$2,
  27448. sep: sep$1
  27449. });
  27450. /*! https://mths.be/punycode v1.4.1 by @mathias */
  27451. /** Highest positive signed 32-bit float value */
  27452. var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
  27453. /** Bootstring parameters */
  27454. var base = 36;
  27455. var tMin = 1;
  27456. var tMax = 26;
  27457. var skew = 38;
  27458. var damp = 700;
  27459. var initialBias = 72;
  27460. var initialN = 128; // 0x80
  27461. var delimiter = '-'; // '\x2D'
  27462. var regexNonASCII = /[^\x20-\x7E]/; // unprintable ASCII chars + non-ASCII chars
  27463. var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
  27464. /** Error messages */
  27465. var errors = {
  27466. 'overflow': 'Overflow: input needs wider integers to process',
  27467. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  27468. 'invalid-input': 'Invalid input'
  27469. };
  27470. /** Convenience shortcuts */
  27471. var baseMinusTMin = base - tMin;
  27472. var floor = Math.floor;
  27473. var stringFromCharCode = String.fromCharCode;
  27474. /*--------------------------------------------------------------------------*/
  27475. /**
  27476. * A generic error utility function.
  27477. * @private
  27478. * @param {String} type The error type.
  27479. * @returns {Error} Throws a `RangeError` with the applicable error message.
  27480. */
  27481. function error(type) {
  27482. throw new RangeError(errors[type]);
  27483. }
  27484. /**
  27485. * A generic `Array#map` utility function.
  27486. * @private
  27487. * @param {Array} array The array to iterate over.
  27488. * @param {Function} callback The function that gets called for every array
  27489. * item.
  27490. * @returns {Array} A new array of values returned by the callback function.
  27491. */
  27492. function map$1(array, fn) {
  27493. var length = array.length;
  27494. var result = [];
  27495. while (length--) {
  27496. result[length] = fn(array[length]);
  27497. }
  27498. return result;
  27499. }
  27500. /**
  27501. * A simple `Array#map`-like wrapper to work with domain name strings or email
  27502. * addresses.
  27503. * @private
  27504. * @param {String} domain The domain name or email address.
  27505. * @param {Function} callback The function that gets called for every
  27506. * character.
  27507. * @returns {Array} A new string of characters returned by the callback
  27508. * function.
  27509. */
  27510. function mapDomain(string, fn) {
  27511. var parts = string.split('@');
  27512. var result = '';
  27513. if (parts.length > 1) {
  27514. // In email addresses, only the domain name should be punycoded. Leave
  27515. // the local part (i.e. everything up to `@`) intact.
  27516. result = parts[0] + '@';
  27517. string = parts[1];
  27518. }
  27519. // Avoid `split(regex)` for IE8 compatibility. See #17.
  27520. string = string.replace(regexSeparators, '\x2E');
  27521. var labels = string.split('.');
  27522. var encoded = map$1(labels, fn).join('.');
  27523. return result + encoded;
  27524. }
  27525. /**
  27526. * Creates an array containing the numeric code points of each Unicode
  27527. * character in the string. While JavaScript uses UCS-2 internally,
  27528. * this function will convert a pair of surrogate halves (each of which
  27529. * UCS-2 exposes as separate characters) into a single code point,
  27530. * matching UTF-16.
  27531. * @see `punycode.ucs2.encode`
  27532. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  27533. * @memberOf punycode.ucs2
  27534. * @name decode
  27535. * @param {String} string The Unicode input string (UCS-2).
  27536. * @returns {Array} The new array of code points.
  27537. */
  27538. function ucs2decode(string) {
  27539. var output = [],
  27540. counter = 0,
  27541. length = string.length,
  27542. value,
  27543. extra;
  27544. while (counter < length) {
  27545. value = string.charCodeAt(counter++);
  27546. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  27547. // high surrogate, and there is a next character
  27548. extra = string.charCodeAt(counter++);
  27549. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  27550. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  27551. } else {
  27552. // unmatched surrogate; only append this code unit, in case the next
  27553. // code unit is the high surrogate of a surrogate pair
  27554. output.push(value);
  27555. counter--;
  27556. }
  27557. } else {
  27558. output.push(value);
  27559. }
  27560. }
  27561. return output;
  27562. }
  27563. /**
  27564. * Converts a digit/integer into a basic code point.
  27565. * @see `basicToDigit()`
  27566. * @private
  27567. * @param {Number} digit The numeric value of a basic code point.
  27568. * @returns {Number} The basic code point whose value (when used for
  27569. * representing integers) is `digit`, which needs to be in the range
  27570. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  27571. * used; else, the lowercase form is used. The behavior is undefined
  27572. * if `flag` is non-zero and `digit` has no uppercase form.
  27573. */
  27574. function digitToBasic(digit, flag) {
  27575. // 0..25 map to ASCII a..z or A..Z
  27576. // 26..35 map to ASCII 0..9
  27577. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  27578. }
  27579. /**
  27580. * Bias adaptation function as per section 3.4 of RFC 3492.
  27581. * https://tools.ietf.org/html/rfc3492#section-3.4
  27582. * @private
  27583. */
  27584. function adapt(delta, numPoints, firstTime) {
  27585. var k = 0;
  27586. delta = firstTime ? floor(delta / damp) : delta >> 1;
  27587. delta += floor(delta / numPoints);
  27588. for ( /* no initialization */ ; delta > baseMinusTMin * tMax >> 1; k += base) {
  27589. delta = floor(delta / baseMinusTMin);
  27590. }
  27591. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  27592. }
  27593. /**
  27594. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  27595. * Punycode string of ASCII-only symbols.
  27596. * @memberOf punycode
  27597. * @param {String} input The string of Unicode symbols.
  27598. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  27599. */
  27600. function encode(input) {
  27601. var n,
  27602. delta,
  27603. handledCPCount,
  27604. basicLength,
  27605. bias,
  27606. j,
  27607. m,
  27608. q,
  27609. k,
  27610. t,
  27611. currentValue,
  27612. output = [],
  27613. /** `inputLength` will hold the number of code points in `input`. */
  27614. inputLength,
  27615. /** Cached calculation results */
  27616. handledCPCountPlusOne,
  27617. baseMinusT,
  27618. qMinusT;
  27619. // Convert the input in UCS-2 to Unicode
  27620. input = ucs2decode(input);
  27621. // Cache the length
  27622. inputLength = input.length;
  27623. // Initialize the state
  27624. n = initialN;
  27625. delta = 0;
  27626. bias = initialBias;
  27627. // Handle the basic code points
  27628. for (j = 0; j < inputLength; ++j) {
  27629. currentValue = input[j];
  27630. if (currentValue < 0x80) {
  27631. output.push(stringFromCharCode(currentValue));
  27632. }
  27633. }
  27634. handledCPCount = basicLength = output.length;
  27635. // `handledCPCount` is the number of code points that have been handled;
  27636. // `basicLength` is the number of basic code points.
  27637. // Finish the basic string - if it is not empty - with a delimiter
  27638. if (basicLength) {
  27639. output.push(delimiter);
  27640. }
  27641. // Main encoding loop:
  27642. while (handledCPCount < inputLength) {
  27643. // All non-basic code points < n have been handled already. Find the next
  27644. // larger one:
  27645. for (m = maxInt, j = 0; j < inputLength; ++j) {
  27646. currentValue = input[j];
  27647. if (currentValue >= n && currentValue < m) {
  27648. m = currentValue;
  27649. }
  27650. }
  27651. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  27652. // but guard against overflow
  27653. handledCPCountPlusOne = handledCPCount + 1;
  27654. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  27655. error('overflow');
  27656. }
  27657. delta += (m - n) * handledCPCountPlusOne;
  27658. n = m;
  27659. for (j = 0; j < inputLength; ++j) {
  27660. currentValue = input[j];
  27661. if (currentValue < n && ++delta > maxInt) {
  27662. error('overflow');
  27663. }
  27664. if (currentValue == n) {
  27665. // Represent delta as a generalized variable-length integer
  27666. for (q = delta, k = base; /* no condition */ ; k += base) {
  27667. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  27668. if (q < t) {
  27669. break;
  27670. }
  27671. qMinusT = q - t;
  27672. baseMinusT = base - t;
  27673. output.push(
  27674. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  27675. );
  27676. q = floor(qMinusT / baseMinusT);
  27677. }
  27678. output.push(stringFromCharCode(digitToBasic(q, 0)));
  27679. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  27680. delta = 0;
  27681. ++handledCPCount;
  27682. }
  27683. }
  27684. ++delta;
  27685. ++n;
  27686. }
  27687. return output.join('');
  27688. }
  27689. /**
  27690. * Converts a Unicode string representing a domain name or an email address to
  27691. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  27692. * i.e. it doesn't matter if you call it with a domain that's already in
  27693. * ASCII.
  27694. * @memberOf punycode
  27695. * @param {String} input The domain name or email address to convert, as a
  27696. * Unicode string.
  27697. * @returns {String} The Punycode representation of the given domain name or
  27698. * email address.
  27699. */
  27700. function toASCII(input) {
  27701. return mapDomain(input, function(string) {
  27702. return regexNonASCII.test(string) ?
  27703. 'xn--' + encode(string) :
  27704. string;
  27705. });
  27706. }
  27707. // shim for using process in browser
  27708. // based off https://github.com/defunctzombie/node-process/blob/master/browser.js
  27709. function defaultSetTimout() {
  27710. throw new Error('setTimeout has not been defined');
  27711. }
  27712. function defaultClearTimeout () {
  27713. throw new Error('clearTimeout has not been defined');
  27714. }
  27715. var cachedSetTimeout = defaultSetTimout;
  27716. var cachedClearTimeout = defaultClearTimeout;
  27717. if (typeof global$1.setTimeout === 'function') {
  27718. cachedSetTimeout = setTimeout;
  27719. }
  27720. if (typeof global$1.clearTimeout === 'function') {
  27721. cachedClearTimeout = clearTimeout;
  27722. }
  27723. function runTimeout(fun) {
  27724. if (cachedSetTimeout === setTimeout) {
  27725. //normal enviroments in sane situations
  27726. return setTimeout(fun, 0);
  27727. }
  27728. // if setTimeout wasn't available but was latter defined
  27729. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  27730. cachedSetTimeout = setTimeout;
  27731. return setTimeout(fun, 0);
  27732. }
  27733. try {
  27734. // when when somebody has screwed with setTimeout but no I.E. maddness
  27735. return cachedSetTimeout(fun, 0);
  27736. } catch(e){
  27737. try {
  27738. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  27739. return cachedSetTimeout.call(null, fun, 0);
  27740. } catch(e){
  27741. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  27742. return cachedSetTimeout.call(this, fun, 0);
  27743. }
  27744. }
  27745. }
  27746. function runClearTimeout(marker) {
  27747. if (cachedClearTimeout === clearTimeout) {
  27748. //normal enviroments in sane situations
  27749. return clearTimeout(marker);
  27750. }
  27751. // if clearTimeout wasn't available but was latter defined
  27752. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  27753. cachedClearTimeout = clearTimeout;
  27754. return clearTimeout(marker);
  27755. }
  27756. try {
  27757. // when when somebody has screwed with setTimeout but no I.E. maddness
  27758. return cachedClearTimeout(marker);
  27759. } catch (e){
  27760. try {
  27761. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  27762. return cachedClearTimeout.call(null, marker);
  27763. } catch (e){
  27764. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  27765. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  27766. return cachedClearTimeout.call(this, marker);
  27767. }
  27768. }
  27769. }
  27770. var queue = [];
  27771. var draining = false;
  27772. var currentQueue;
  27773. var queueIndex = -1;
  27774. function cleanUpNextTick() {
  27775. if (!draining || !currentQueue) {
  27776. return;
  27777. }
  27778. draining = false;
  27779. if (currentQueue.length) {
  27780. queue = currentQueue.concat(queue);
  27781. } else {
  27782. queueIndex = -1;
  27783. }
  27784. if (queue.length) {
  27785. drainQueue();
  27786. }
  27787. }
  27788. function drainQueue() {
  27789. if (draining) {
  27790. return;
  27791. }
  27792. var timeout = runTimeout(cleanUpNextTick);
  27793. draining = true;
  27794. var len = queue.length;
  27795. while(len) {
  27796. currentQueue = queue;
  27797. queue = [];
  27798. while (++queueIndex < len) {
  27799. if (currentQueue) {
  27800. currentQueue[queueIndex].run();
  27801. }
  27802. }
  27803. queueIndex = -1;
  27804. len = queue.length;
  27805. }
  27806. currentQueue = null;
  27807. draining = false;
  27808. runClearTimeout(timeout);
  27809. }
  27810. function nextTick(fun) {
  27811. var args = new Array(arguments.length - 1);
  27812. if (arguments.length > 1) {
  27813. for (var i = 1; i < arguments.length; i++) {
  27814. args[i - 1] = arguments[i];
  27815. }
  27816. }
  27817. queue.push(new Item(fun, args));
  27818. if (queue.length === 1 && !draining) {
  27819. runTimeout(drainQueue);
  27820. }
  27821. }
  27822. // v8 likes predictible objects
  27823. function Item(fun, array) {
  27824. this.fun = fun;
  27825. this.array = array;
  27826. }
  27827. Item.prototype.run = function () {
  27828. this.fun.apply(null, this.array);
  27829. };
  27830. var title = 'browser';
  27831. var platform = 'browser';
  27832. var browser = true;
  27833. var env = {};
  27834. var argv = [];
  27835. var version = ''; // empty string to avoid regexp issues
  27836. var versions = {};
  27837. var release = {};
  27838. var config = {};
  27839. function noop() {}
  27840. var on = noop;
  27841. var addListener = noop;
  27842. var once = noop;
  27843. var off = noop;
  27844. var removeListener = noop;
  27845. var removeAllListeners = noop;
  27846. var emit = noop;
  27847. function binding(name) {
  27848. throw new Error('process.binding is not supported');
  27849. }
  27850. function cwd () { return '/' }
  27851. function chdir (dir) {
  27852. throw new Error('process.chdir is not supported');
  27853. }function umask() { return 0; }
  27854. // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
  27855. var performance = global$1.performance || {};
  27856. var performanceNow =
  27857. performance.now ||
  27858. performance.mozNow ||
  27859. performance.msNow ||
  27860. performance.oNow ||
  27861. performance.webkitNow ||
  27862. function(){ return (new Date()).getTime() };
  27863. // generate timestamp or delta
  27864. // see http://nodejs.org/api/process.html#process_process_hrtime
  27865. function hrtime(previousTimestamp){
  27866. var clocktime = performanceNow.call(performance)*1e-3;
  27867. var seconds = Math.floor(clocktime);
  27868. var nanoseconds = Math.floor((clocktime%1)*1e9);
  27869. if (previousTimestamp) {
  27870. seconds = seconds - previousTimestamp[0];
  27871. nanoseconds = nanoseconds - previousTimestamp[1];
  27872. if (nanoseconds<0) {
  27873. seconds--;
  27874. nanoseconds += 1e9;
  27875. }
  27876. }
  27877. return [seconds,nanoseconds]
  27878. }
  27879. var startTime = new Date();
  27880. function uptime() {
  27881. var currentTime = new Date();
  27882. var dif = currentTime - startTime;
  27883. return dif / 1000;
  27884. }
  27885. var browser$1 = {
  27886. nextTick: nextTick,
  27887. title: title,
  27888. browser: browser,
  27889. env: env,
  27890. argv: argv,
  27891. version: version,
  27892. versions: versions,
  27893. on: on,
  27894. addListener: addListener,
  27895. once: once,
  27896. off: off,
  27897. removeListener: removeListener,
  27898. removeAllListeners: removeAllListeners,
  27899. emit: emit,
  27900. binding: binding,
  27901. cwd: cwd,
  27902. chdir: chdir,
  27903. umask: umask,
  27904. hrtime: hrtime,
  27905. platform: platform,
  27906. release: release,
  27907. config: config,
  27908. uptime: uptime
  27909. };
  27910. var inherits;
  27911. if (typeof Object.create === 'function'){
  27912. inherits = function inherits(ctor, superCtor) {
  27913. // implementation from standard node.js 'util' module
  27914. ctor.super_ = superCtor;
  27915. ctor.prototype = Object.create(superCtor.prototype, {
  27916. constructor: {
  27917. value: ctor,
  27918. enumerable: false,
  27919. writable: true,
  27920. configurable: true
  27921. }
  27922. });
  27923. };
  27924. } else {
  27925. inherits = function inherits(ctor, superCtor) {
  27926. ctor.super_ = superCtor;
  27927. var TempCtor = function () {};
  27928. TempCtor.prototype = superCtor.prototype;
  27929. ctor.prototype = new TempCtor();
  27930. ctor.prototype.constructor = ctor;
  27931. };
  27932. }
  27933. var inherits$1 = inherits;
  27934. var formatRegExp = /%[sdj%]/g;
  27935. function format$1(f) {
  27936. if (!isString$1(f)) {
  27937. var objects = [];
  27938. for (var i = 0; i < arguments.length; i++) {
  27939. objects.push(inspect(arguments[i]));
  27940. }
  27941. return objects.join(' ');
  27942. }
  27943. var i = 1;
  27944. var args = arguments;
  27945. var len = args.length;
  27946. var str = String(f).replace(formatRegExp, function(x) {
  27947. if (x === '%%') return '%';
  27948. if (i >= len) return x;
  27949. switch (x) {
  27950. case '%s': return String(args[i++]);
  27951. case '%d': return Number(args[i++]);
  27952. case '%j':
  27953. try {
  27954. return JSON.stringify(args[i++]);
  27955. } catch (_) {
  27956. return '[Circular]';
  27957. }
  27958. default:
  27959. return x;
  27960. }
  27961. });
  27962. for (var x = args[i]; i < len; x = args[++i]) {
  27963. if (isNull(x) || !isObject(x)) {
  27964. str += ' ' + x;
  27965. } else {
  27966. str += ' ' + inspect(x);
  27967. }
  27968. }
  27969. return str;
  27970. }
  27971. // Mark that a method should not be used.
  27972. // Returns a modified function which warns once by default.
  27973. // If --no-deprecation is set, then it is a no-op.
  27974. function deprecate(fn, msg) {
  27975. // Allow for deprecating things in the process of starting up.
  27976. if (isUndefined(global$1.process)) {
  27977. return function() {
  27978. return deprecate(fn, msg).apply(this, arguments);
  27979. };
  27980. }
  27981. if (browser$1.noDeprecation === true) {
  27982. return fn;
  27983. }
  27984. var warned = false;
  27985. function deprecated() {
  27986. if (!warned) {
  27987. if (browser$1.throwDeprecation) {
  27988. throw new Error(msg);
  27989. } else if (browser$1.traceDeprecation) {
  27990. console.trace(msg);
  27991. } else {
  27992. console.error(msg);
  27993. }
  27994. warned = true;
  27995. }
  27996. return fn.apply(this, arguments);
  27997. }
  27998. return deprecated;
  27999. }
  28000. var debugs = {};
  28001. var debugEnviron;
  28002. function debuglog(set) {
  28003. if (isUndefined(debugEnviron))
  28004. debugEnviron = browser$1.env.NODE_DEBUG || '';
  28005. set = set.toUpperCase();
  28006. if (!debugs[set]) {
  28007. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  28008. var pid = 0;
  28009. debugs[set] = function() {
  28010. var msg = format$1.apply(null, arguments);
  28011. console.error('%s %d: %s', set, pid, msg);
  28012. };
  28013. } else {
  28014. debugs[set] = function() {};
  28015. }
  28016. }
  28017. return debugs[set];
  28018. }
  28019. /**
  28020. * Echos the value of a value. Trys to print the value out
  28021. * in the best way possible given the different types.
  28022. *
  28023. * @param {Object} obj The object to print out.
  28024. * @param {Object} opts Optional options object that alters the output.
  28025. */
  28026. /* legacy: obj, showHidden, depth, colors*/
  28027. function inspect(obj, opts) {
  28028. // default options
  28029. var ctx = {
  28030. seen: [],
  28031. stylize: stylizeNoColor
  28032. };
  28033. // legacy...
  28034. if (arguments.length >= 3) ctx.depth = arguments[2];
  28035. if (arguments.length >= 4) ctx.colors = arguments[3];
  28036. if (isBoolean(opts)) {
  28037. // legacy...
  28038. ctx.showHidden = opts;
  28039. } else if (opts) {
  28040. // got an "options" object
  28041. _extend(ctx, opts);
  28042. }
  28043. // set default options
  28044. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  28045. if (isUndefined(ctx.depth)) ctx.depth = 2;
  28046. if (isUndefined(ctx.colors)) ctx.colors = false;
  28047. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  28048. if (ctx.colors) ctx.stylize = stylizeWithColor;
  28049. return formatValue(ctx, obj, ctx.depth);
  28050. }
  28051. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  28052. inspect.colors = {
  28053. 'bold' : [1, 22],
  28054. 'italic' : [3, 23],
  28055. 'underline' : [4, 24],
  28056. 'inverse' : [7, 27],
  28057. 'white' : [37, 39],
  28058. 'grey' : [90, 39],
  28059. 'black' : [30, 39],
  28060. 'blue' : [34, 39],
  28061. 'cyan' : [36, 39],
  28062. 'green' : [32, 39],
  28063. 'magenta' : [35, 39],
  28064. 'red' : [31, 39],
  28065. 'yellow' : [33, 39]
  28066. };
  28067. // Don't use 'blue' not visible on cmd.exe
  28068. inspect.styles = {
  28069. 'special': 'cyan',
  28070. 'number': 'yellow',
  28071. 'boolean': 'yellow',
  28072. 'undefined': 'grey',
  28073. 'null': 'bold',
  28074. 'string': 'green',
  28075. 'date': 'magenta',
  28076. // "name": intentionally not styling
  28077. 'regexp': 'red'
  28078. };
  28079. function stylizeWithColor(str, styleType) {
  28080. var style = inspect.styles[styleType];
  28081. if (style) {
  28082. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  28083. '\u001b[' + inspect.colors[style][1] + 'm';
  28084. } else {
  28085. return str;
  28086. }
  28087. }
  28088. function stylizeNoColor(str, styleType) {
  28089. return str;
  28090. }
  28091. function arrayToHash(array) {
  28092. var hash = {};
  28093. array.forEach(function(val, idx) {
  28094. hash[val] = true;
  28095. });
  28096. return hash;
  28097. }
  28098. function formatValue(ctx, value, recurseTimes) {
  28099. // Provide a hook for user-specified inspect functions.
  28100. // Check that value is an object with an inspect function on it
  28101. if (ctx.customInspect &&
  28102. value &&
  28103. isFunction(value.inspect) &&
  28104. // Filter out the util module, it's inspect function is special
  28105. value.inspect !== inspect &&
  28106. // Also filter out any prototype objects using the circular check.
  28107. !(value.constructor && value.constructor.prototype === value)) {
  28108. var ret = value.inspect(recurseTimes, ctx);
  28109. if (!isString$1(ret)) {
  28110. ret = formatValue(ctx, ret, recurseTimes);
  28111. }
  28112. return ret;
  28113. }
  28114. // Primitive types cannot have properties
  28115. var primitive = formatPrimitive(ctx, value);
  28116. if (primitive) {
  28117. return primitive;
  28118. }
  28119. // Look up the keys of the object.
  28120. var keys = Object.keys(value);
  28121. var visibleKeys = arrayToHash(keys);
  28122. if (ctx.showHidden) {
  28123. keys = Object.getOwnPropertyNames(value);
  28124. }
  28125. // IE doesn't make error fields non-enumerable
  28126. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  28127. if (isError(value)
  28128. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  28129. return formatError(value);
  28130. }
  28131. // Some type of object without properties can be shortcutted.
  28132. if (keys.length === 0) {
  28133. if (isFunction(value)) {
  28134. var name = value.name ? ': ' + value.name : '';
  28135. return ctx.stylize('[Function' + name + ']', 'special');
  28136. }
  28137. if (isRegExp(value)) {
  28138. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  28139. }
  28140. if (isDate(value)) {
  28141. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  28142. }
  28143. if (isError(value)) {
  28144. return formatError(value);
  28145. }
  28146. }
  28147. var base = '', array = false, braces = ['{', '}'];
  28148. // Make Array say that they are Array
  28149. if (isArray$1(value)) {
  28150. array = true;
  28151. braces = ['[', ']'];
  28152. }
  28153. // Make functions say that they are functions
  28154. if (isFunction(value)) {
  28155. var n = value.name ? ': ' + value.name : '';
  28156. base = ' [Function' + n + ']';
  28157. }
  28158. // Make RegExps say that they are RegExps
  28159. if (isRegExp(value)) {
  28160. base = ' ' + RegExp.prototype.toString.call(value);
  28161. }
  28162. // Make dates with properties first say the date
  28163. if (isDate(value)) {
  28164. base = ' ' + Date.prototype.toUTCString.call(value);
  28165. }
  28166. // Make error with message first say the error
  28167. if (isError(value)) {
  28168. base = ' ' + formatError(value);
  28169. }
  28170. if (keys.length === 0 && (!array || value.length == 0)) {
  28171. return braces[0] + base + braces[1];
  28172. }
  28173. if (recurseTimes < 0) {
  28174. if (isRegExp(value)) {
  28175. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  28176. } else {
  28177. return ctx.stylize('[Object]', 'special');
  28178. }
  28179. }
  28180. ctx.seen.push(value);
  28181. var output;
  28182. if (array) {
  28183. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  28184. } else {
  28185. output = keys.map(function(key) {
  28186. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  28187. });
  28188. }
  28189. ctx.seen.pop();
  28190. return reduceToSingleString(output, base, braces);
  28191. }
  28192. function formatPrimitive(ctx, value) {
  28193. if (isUndefined(value))
  28194. return ctx.stylize('undefined', 'undefined');
  28195. if (isString$1(value)) {
  28196. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  28197. .replace(/'/g, "\\'")
  28198. .replace(/\\"/g, '"') + '\'';
  28199. return ctx.stylize(simple, 'string');
  28200. }
  28201. if (isNumber(value))
  28202. return ctx.stylize('' + value, 'number');
  28203. if (isBoolean(value))
  28204. return ctx.stylize('' + value, 'boolean');
  28205. // For some reason typeof null is "object", so special case here.
  28206. if (isNull(value))
  28207. return ctx.stylize('null', 'null');
  28208. }
  28209. function formatError(value) {
  28210. return '[' + Error.prototype.toString.call(value) + ']';
  28211. }
  28212. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  28213. var output = [];
  28214. for (var i = 0, l = value.length; i < l; ++i) {
  28215. if (hasOwnProperty$2(value, String(i))) {
  28216. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  28217. String(i), true));
  28218. } else {
  28219. output.push('');
  28220. }
  28221. }
  28222. keys.forEach(function(key) {
  28223. if (!key.match(/^\d+$/)) {
  28224. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  28225. key, true));
  28226. }
  28227. });
  28228. return output;
  28229. }
  28230. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  28231. var name, str, desc;
  28232. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  28233. if (desc.get) {
  28234. if (desc.set) {
  28235. str = ctx.stylize('[Getter/Setter]', 'special');
  28236. } else {
  28237. str = ctx.stylize('[Getter]', 'special');
  28238. }
  28239. } else {
  28240. if (desc.set) {
  28241. str = ctx.stylize('[Setter]', 'special');
  28242. }
  28243. }
  28244. if (!hasOwnProperty$2(visibleKeys, key)) {
  28245. name = '[' + key + ']';
  28246. }
  28247. if (!str) {
  28248. if (ctx.seen.indexOf(desc.value) < 0) {
  28249. if (isNull(recurseTimes)) {
  28250. str = formatValue(ctx, desc.value, null);
  28251. } else {
  28252. str = formatValue(ctx, desc.value, recurseTimes - 1);
  28253. }
  28254. if (str.indexOf('\n') > -1) {
  28255. if (array) {
  28256. str = str.split('\n').map(function(line) {
  28257. return ' ' + line;
  28258. }).join('\n').substr(2);
  28259. } else {
  28260. str = '\n' + str.split('\n').map(function(line) {
  28261. return ' ' + line;
  28262. }).join('\n');
  28263. }
  28264. }
  28265. } else {
  28266. str = ctx.stylize('[Circular]', 'special');
  28267. }
  28268. }
  28269. if (isUndefined(name)) {
  28270. if (array && key.match(/^\d+$/)) {
  28271. return str;
  28272. }
  28273. name = JSON.stringify('' + key);
  28274. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  28275. name = name.substr(1, name.length - 2);
  28276. name = ctx.stylize(name, 'name');
  28277. } else {
  28278. name = name.replace(/'/g, "\\'")
  28279. .replace(/\\"/g, '"')
  28280. .replace(/(^"|"$)/g, "'");
  28281. name = ctx.stylize(name, 'string');
  28282. }
  28283. }
  28284. return name + ': ' + str;
  28285. }
  28286. function reduceToSingleString(output, base, braces) {
  28287. var length = output.reduce(function(prev, cur) {
  28288. if (cur.indexOf('\n') >= 0) ;
  28289. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  28290. }, 0);
  28291. if (length > 60) {
  28292. return braces[0] +
  28293. (base === '' ? '' : base + '\n ') +
  28294. ' ' +
  28295. output.join(',\n ') +
  28296. ' ' +
  28297. braces[1];
  28298. }
  28299. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  28300. }
  28301. // NOTE: These type checking functions intentionally don't use `instanceof`
  28302. // because it is fragile and can be easily faked with `Object.create()`.
  28303. function isArray$1(ar) {
  28304. return Array.isArray(ar);
  28305. }
  28306. function isBoolean(arg) {
  28307. return typeof arg === 'boolean';
  28308. }
  28309. function isNull(arg) {
  28310. return arg === null;
  28311. }
  28312. function isNullOrUndefined(arg) {
  28313. return arg == null;
  28314. }
  28315. function isNumber(arg) {
  28316. return typeof arg === 'number';
  28317. }
  28318. function isString$1(arg) {
  28319. return typeof arg === 'string';
  28320. }
  28321. function isSymbol(arg) {
  28322. return typeof arg === 'symbol';
  28323. }
  28324. function isUndefined(arg) {
  28325. return arg === void 0;
  28326. }
  28327. function isRegExp(re) {
  28328. return isObject(re) && objectToString(re) === '[object RegExp]';
  28329. }
  28330. function isObject(arg) {
  28331. return typeof arg === 'object' && arg !== null;
  28332. }
  28333. function isDate(d) {
  28334. return isObject(d) && objectToString(d) === '[object Date]';
  28335. }
  28336. function isError(e) {
  28337. return isObject(e) &&
  28338. (objectToString(e) === '[object Error]' || e instanceof Error);
  28339. }
  28340. function isFunction(arg) {
  28341. return typeof arg === 'function';
  28342. }
  28343. function isPrimitive(arg) {
  28344. return arg === null ||
  28345. typeof arg === 'boolean' ||
  28346. typeof arg === 'number' ||
  28347. typeof arg === 'string' ||
  28348. typeof arg === 'symbol' || // ES6 symbol
  28349. typeof arg === 'undefined';
  28350. }
  28351. function isBuffer(maybeBuf) {
  28352. return Buffer.isBuffer(maybeBuf);
  28353. }
  28354. function objectToString(o) {
  28355. return Object.prototype.toString.call(o);
  28356. }
  28357. function pad(n) {
  28358. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  28359. }
  28360. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  28361. 'Oct', 'Nov', 'Dec'];
  28362. // 26 Feb 16:19:34
  28363. function timestamp() {
  28364. var d = new Date();
  28365. var time = [pad(d.getHours()),
  28366. pad(d.getMinutes()),
  28367. pad(d.getSeconds())].join(':');
  28368. return [d.getDate(), months[d.getMonth()], time].join(' ');
  28369. }
  28370. // log is just a thin wrapper to console.log that prepends a timestamp
  28371. function log() {
  28372. console.log('%s - %s', timestamp(), format$1.apply(null, arguments));
  28373. }
  28374. function _extend(origin, add) {
  28375. // Don't do anything if add isn't an object
  28376. if (!add || !isObject(add)) return origin;
  28377. var keys = Object.keys(add);
  28378. var i = keys.length;
  28379. while (i--) {
  28380. origin[keys[i]] = add[keys[i]];
  28381. }
  28382. return origin;
  28383. }
  28384. function hasOwnProperty$2(obj, prop) {
  28385. return Object.prototype.hasOwnProperty.call(obj, prop);
  28386. }
  28387. var _polyfillNode_util = {
  28388. inherits: inherits$1,
  28389. _extend: _extend,
  28390. log: log,
  28391. isBuffer: isBuffer,
  28392. isPrimitive: isPrimitive,
  28393. isFunction: isFunction,
  28394. isError: isError,
  28395. isDate: isDate,
  28396. isObject: isObject,
  28397. isRegExp: isRegExp,
  28398. isUndefined: isUndefined,
  28399. isSymbol: isSymbol,
  28400. isString: isString$1,
  28401. isNumber: isNumber,
  28402. isNullOrUndefined: isNullOrUndefined,
  28403. isNull: isNull,
  28404. isBoolean: isBoolean,
  28405. isArray: isArray$1,
  28406. inspect: inspect,
  28407. deprecate: deprecate,
  28408. format: format$1,
  28409. debuglog: debuglog
  28410. };
  28411. var _polyfillNode_util$1 = /*#__PURE__*/Object.freeze({
  28412. __proto__: null,
  28413. _extend: _extend,
  28414. debuglog: debuglog,
  28415. default: _polyfillNode_util,
  28416. deprecate: deprecate,
  28417. format: format$1,
  28418. inherits: inherits$1,
  28419. inspect: inspect,
  28420. isArray: isArray$1,
  28421. isBoolean: isBoolean,
  28422. isBuffer: isBuffer,
  28423. isDate: isDate,
  28424. isError: isError,
  28425. isFunction: isFunction,
  28426. isNull: isNull,
  28427. isNullOrUndefined: isNullOrUndefined,
  28428. isNumber: isNumber,
  28429. isObject: isObject,
  28430. isPrimitive: isPrimitive,
  28431. isRegExp: isRegExp,
  28432. isString: isString$1,
  28433. isSymbol: isSymbol,
  28434. isUndefined: isUndefined,
  28435. log: log
  28436. });
  28437. // Copyright Joyent, Inc. and other Node contributors.
  28438. //
  28439. // Permission is hereby granted, free of charge, to any person obtaining a
  28440. // copy of this software and associated documentation files (the
  28441. // "Software"), to deal in the Software without restriction, including
  28442. // without limitation the rights to use, copy, modify, merge, publish,
  28443. // distribute, sublicense, and/or sell copies of the Software, and to permit
  28444. // persons to whom the Software is furnished to do so, subject to the
  28445. // following conditions:
  28446. //
  28447. // The above copyright notice and this permission notice shall be included
  28448. // in all copies or substantial portions of the Software.
  28449. //
  28450. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  28451. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  28452. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  28453. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  28454. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  28455. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  28456. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  28457. // If obj.hasOwnProperty has been overridden, then calling
  28458. // obj.hasOwnProperty(prop) will break.
  28459. // See: https://github.com/joyent/node/issues/1707
  28460. function hasOwnProperty$1(obj, prop) {
  28461. return Object.prototype.hasOwnProperty.call(obj, prop);
  28462. }
  28463. var isArray = Array.isArray || function (xs) {
  28464. return Object.prototype.toString.call(xs) === '[object Array]';
  28465. };
  28466. function stringifyPrimitive(v) {
  28467. switch (typeof v) {
  28468. case 'string':
  28469. return v;
  28470. case 'boolean':
  28471. return v ? 'true' : 'false';
  28472. case 'number':
  28473. return isFinite(v) ? v : '';
  28474. default:
  28475. return '';
  28476. }
  28477. }
  28478. function stringify$5 (obj, sep, eq, name) {
  28479. sep = sep || '&';
  28480. eq = eq || '=';
  28481. if (obj === null) {
  28482. obj = undefined;
  28483. }
  28484. if (typeof obj === 'object') {
  28485. return map(objectKeys(obj), function(k) {
  28486. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  28487. if (isArray(obj[k])) {
  28488. return map(obj[k], function(v) {
  28489. return ks + encodeURIComponent(stringifyPrimitive(v));
  28490. }).join(sep);
  28491. } else {
  28492. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  28493. }
  28494. }).join(sep);
  28495. }
  28496. if (!name) return '';
  28497. return encodeURIComponent(stringifyPrimitive(name)) + eq +
  28498. encodeURIComponent(stringifyPrimitive(obj));
  28499. }
  28500. function map (xs, f) {
  28501. if (xs.map) return xs.map(f);
  28502. var res = [];
  28503. for (var i = 0; i < xs.length; i++) {
  28504. res.push(f(xs[i], i));
  28505. }
  28506. return res;
  28507. }
  28508. var objectKeys = Object.keys || function (obj) {
  28509. var res = [];
  28510. for (var key in obj) {
  28511. if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
  28512. }
  28513. return res;
  28514. };
  28515. function parse$7(qs, sep, eq, options) {
  28516. sep = sep || '&';
  28517. eq = eq || '=';
  28518. var obj = {};
  28519. if (typeof qs !== 'string' || qs.length === 0) {
  28520. return obj;
  28521. }
  28522. var regexp = /\+/g;
  28523. qs = qs.split(sep);
  28524. var maxKeys = 1000;
  28525. if (options && typeof options.maxKeys === 'number') {
  28526. maxKeys = options.maxKeys;
  28527. }
  28528. var len = qs.length;
  28529. // maxKeys <= 0 means that we should not limit keys count
  28530. if (maxKeys > 0 && len > maxKeys) {
  28531. len = maxKeys;
  28532. }
  28533. for (var i = 0; i < len; ++i) {
  28534. var x = qs[i].replace(regexp, '%20'),
  28535. idx = x.indexOf(eq),
  28536. kstr, vstr, k, v;
  28537. if (idx >= 0) {
  28538. kstr = x.substr(0, idx);
  28539. vstr = x.substr(idx + 1);
  28540. } else {
  28541. kstr = x;
  28542. vstr = '';
  28543. }
  28544. k = decodeURIComponent(kstr);
  28545. v = decodeURIComponent(vstr);
  28546. if (!hasOwnProperty$1(obj, k)) {
  28547. obj[k] = v;
  28548. } else if (isArray(obj[k])) {
  28549. obj[k].push(v);
  28550. } else {
  28551. obj[k] = [obj[k], v];
  28552. }
  28553. }
  28554. return obj;
  28555. }
  28556. // WHATWG API
  28557. const URL$1 = global$1.URL;
  28558. const URLSearchParams = global$1.URLSearchParams;
  28559. var _polyfillNode_url = {
  28560. parse: urlParse,
  28561. resolve: urlResolve,
  28562. resolveObject: urlResolveObject,
  28563. fileURLToPath: urlFileURLToPath,
  28564. format: urlFormat,
  28565. Url: Url,
  28566. // WHATWG API
  28567. URL: URL$1,
  28568. URLSearchParams,
  28569. };
  28570. function Url() {
  28571. this.protocol = null;
  28572. this.slashes = null;
  28573. this.auth = null;
  28574. this.host = null;
  28575. this.port = null;
  28576. this.hostname = null;
  28577. this.hash = null;
  28578. this.search = null;
  28579. this.query = null;
  28580. this.pathname = null;
  28581. this.path = null;
  28582. this.href = null;
  28583. }
  28584. // Reference: RFC 3986, RFC 1808, RFC 2396
  28585. // define these here so at least they only have to be
  28586. // compiled once on the first module load.
  28587. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  28588. portPattern = /:[0-9]*$/,
  28589. // Special case for a simple path URL
  28590. simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
  28591. // RFC 2396: characters reserved for delimiting URLs.
  28592. // We actually just auto-escape these.
  28593. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  28594. // RFC 2396: characters not allowed for various reasons.
  28595. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  28596. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  28597. autoEscape = ['\''].concat(unwise),
  28598. // Characters that are never ever allowed in a hostname.
  28599. // Note that any invalid chars are also handled, but these
  28600. // are the ones that are *expected* to be seen, so we fast-path
  28601. // them.
  28602. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  28603. hostEndingChars = ['/', '?', '#'],
  28604. hostnameMaxLen = 255,
  28605. hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
  28606. hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
  28607. // protocols that can allow "unsafe" and "unwise" chars.
  28608. unsafeProtocol = {
  28609. 'javascript': true,
  28610. 'javascript:': true
  28611. },
  28612. // protocols that never have a hostname.
  28613. hostlessProtocol = {
  28614. 'javascript': true,
  28615. 'javascript:': true
  28616. },
  28617. // protocols that always contain a // bit.
  28618. slashedProtocol = {
  28619. 'http': true,
  28620. 'https': true,
  28621. 'ftp': true,
  28622. 'gopher': true,
  28623. 'file': true,
  28624. 'http:': true,
  28625. 'https:': true,
  28626. 'ftp:': true,
  28627. 'gopher:': true,
  28628. 'file:': true
  28629. };
  28630. function urlParse(url, parseQueryString, slashesDenoteHost) {
  28631. if (url && isObject(url) && url instanceof Url) return url;
  28632. var u = new Url;
  28633. u.parse(url, parseQueryString, slashesDenoteHost);
  28634. return u;
  28635. }
  28636. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  28637. return parse$6(this, url, parseQueryString, slashesDenoteHost);
  28638. };
  28639. function parse$6(self, url, parseQueryString, slashesDenoteHost) {
  28640. if (!isString$1(url)) {
  28641. throw new TypeError('Parameter \'url\' must be a string, not ' + typeof url);
  28642. }
  28643. // Copy chrome, IE, opera backslash-handling behavior.
  28644. // Back slashes before the query string get converted to forward slashes
  28645. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  28646. var queryIndex = url.indexOf('?'),
  28647. splitter =
  28648. (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
  28649. uSplit = url.split(splitter),
  28650. slashRegex = /\\/g;
  28651. uSplit[0] = uSplit[0].replace(slashRegex, '/');
  28652. url = uSplit.join(splitter);
  28653. var rest = url;
  28654. // trim before proceeding.
  28655. // This is to support parse stuff like " http://foo.com \n"
  28656. rest = rest.trim();
  28657. if (!slashesDenoteHost && url.split('#').length === 1) {
  28658. // Try fast path regexp
  28659. var simplePath = simplePathPattern.exec(rest);
  28660. if (simplePath) {
  28661. self.path = rest;
  28662. self.href = rest;
  28663. self.pathname = simplePath[1];
  28664. if (simplePath[2]) {
  28665. self.search = simplePath[2];
  28666. if (parseQueryString) {
  28667. self.query = parse$7(self.search.substr(1));
  28668. } else {
  28669. self.query = self.search.substr(1);
  28670. }
  28671. } else if (parseQueryString) {
  28672. self.search = '';
  28673. self.query = {};
  28674. }
  28675. return self;
  28676. }
  28677. }
  28678. var proto = protocolPattern.exec(rest);
  28679. if (proto) {
  28680. proto = proto[0];
  28681. var lowerProto = proto.toLowerCase();
  28682. self.protocol = lowerProto;
  28683. rest = rest.substr(proto.length);
  28684. }
  28685. // figure out if it's got a host
  28686. // user@server is *always* interpreted as a hostname, and url
  28687. // resolution will treat //foo/bar as host=foo,path=bar because that's
  28688. // how the browser resolves relative URLs.
  28689. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  28690. var slashes = rest.substr(0, 2) === '//';
  28691. if (slashes && !(proto && hostlessProtocol[proto])) {
  28692. rest = rest.substr(2);
  28693. self.slashes = true;
  28694. }
  28695. }
  28696. var i, hec, l, p;
  28697. if (!hostlessProtocol[proto] &&
  28698. (slashes || (proto && !slashedProtocol[proto]))) {
  28699. // there's a hostname.
  28700. // the first instance of /, ?, ;, or # ends the host.
  28701. //
  28702. // If there is an @ in the hostname, then non-host chars *are* allowed
  28703. // to the left of the last @ sign, unless some host-ending character
  28704. // comes *before* the @-sign.
  28705. // URLs are obnoxious.
  28706. //
  28707. // ex:
  28708. // http://a@b@c/ => user:a@b host:c
  28709. // http://a@b?@c => user:a host:c path:/?@c
  28710. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  28711. // Review our test case against browsers more comprehensively.
  28712. // find the first instance of any hostEndingChars
  28713. var hostEnd = -1;
  28714. for (i = 0; i < hostEndingChars.length; i++) {
  28715. hec = rest.indexOf(hostEndingChars[i]);
  28716. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  28717. hostEnd = hec;
  28718. }
  28719. // at this point, either we have an explicit point where the
  28720. // auth portion cannot go past, or the last @ char is the decider.
  28721. var auth, atSign;
  28722. if (hostEnd === -1) {
  28723. // atSign can be anywhere.
  28724. atSign = rest.lastIndexOf('@');
  28725. } else {
  28726. // atSign must be in auth portion.
  28727. // http://a@b/c@d => host:b auth:a path:/c@d
  28728. atSign = rest.lastIndexOf('@', hostEnd);
  28729. }
  28730. // Now we have a portion which is definitely the auth.
  28731. // Pull that off.
  28732. if (atSign !== -1) {
  28733. auth = rest.slice(0, atSign);
  28734. rest = rest.slice(atSign + 1);
  28735. self.auth = decodeURIComponent(auth);
  28736. }
  28737. // the host is the remaining to the left of the first non-host char
  28738. hostEnd = -1;
  28739. for (i = 0; i < nonHostChars.length; i++) {
  28740. hec = rest.indexOf(nonHostChars[i]);
  28741. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  28742. hostEnd = hec;
  28743. }
  28744. // if we still have not hit it, then the entire thing is a host.
  28745. if (hostEnd === -1)
  28746. hostEnd = rest.length;
  28747. self.host = rest.slice(0, hostEnd);
  28748. rest = rest.slice(hostEnd);
  28749. // pull out port.
  28750. parseHost(self);
  28751. // we've indicated that there is a hostname,
  28752. // so even if it's empty, it has to be present.
  28753. self.hostname = self.hostname || '';
  28754. // if hostname begins with [ and ends with ]
  28755. // assume that it's an IPv6 address.
  28756. var ipv6Hostname = self.hostname[0] === '[' &&
  28757. self.hostname[self.hostname.length - 1] === ']';
  28758. // validate a little.
  28759. if (!ipv6Hostname) {
  28760. var hostparts = self.hostname.split(/\./);
  28761. for (i = 0, l = hostparts.length; i < l; i++) {
  28762. var part = hostparts[i];
  28763. if (!part) continue;
  28764. if (!part.match(hostnamePartPattern)) {
  28765. var newpart = '';
  28766. for (var j = 0, k = part.length; j < k; j++) {
  28767. if (part.charCodeAt(j) > 127) {
  28768. // we replace non-ASCII char with a temporary placeholder
  28769. // we need this to make sure size of hostname is not
  28770. // broken by replacing non-ASCII by nothing
  28771. newpart += 'x';
  28772. } else {
  28773. newpart += part[j];
  28774. }
  28775. }
  28776. // we test again with ASCII char only
  28777. if (!newpart.match(hostnamePartPattern)) {
  28778. var validParts = hostparts.slice(0, i);
  28779. var notHost = hostparts.slice(i + 1);
  28780. var bit = part.match(hostnamePartStart);
  28781. if (bit) {
  28782. validParts.push(bit[1]);
  28783. notHost.unshift(bit[2]);
  28784. }
  28785. if (notHost.length) {
  28786. rest = '/' + notHost.join('.') + rest;
  28787. }
  28788. self.hostname = validParts.join('.');
  28789. break;
  28790. }
  28791. }
  28792. }
  28793. }
  28794. if (self.hostname.length > hostnameMaxLen) {
  28795. self.hostname = '';
  28796. } else {
  28797. // hostnames are always lower case.
  28798. self.hostname = self.hostname.toLowerCase();
  28799. }
  28800. if (!ipv6Hostname) {
  28801. // IDNA Support: Returns a punycoded representation of "domain".
  28802. // It only converts parts of the domain name that
  28803. // have non-ASCII characters, i.e. it doesn't matter if
  28804. // you call it with a domain that already is ASCII-only.
  28805. self.hostname = toASCII(self.hostname);
  28806. }
  28807. p = self.port ? ':' + self.port : '';
  28808. var h = self.hostname || '';
  28809. self.host = h + p;
  28810. self.href += self.host;
  28811. // strip [ and ] from the hostname
  28812. // the host field still retains them, though
  28813. if (ipv6Hostname) {
  28814. self.hostname = self.hostname.substr(1, self.hostname.length - 2);
  28815. if (rest[0] !== '/') {
  28816. rest = '/' + rest;
  28817. }
  28818. }
  28819. }
  28820. // now rest is set to the post-host stuff.
  28821. // chop off any delim chars.
  28822. if (!unsafeProtocol[lowerProto]) {
  28823. // First, make 100% sure that any "autoEscape" chars get
  28824. // escaped, even if encodeURIComponent doesn't think they
  28825. // need to be.
  28826. for (i = 0, l = autoEscape.length; i < l; i++) {
  28827. var ae = autoEscape[i];
  28828. if (rest.indexOf(ae) === -1)
  28829. continue;
  28830. var esc = encodeURIComponent(ae);
  28831. if (esc === ae) {
  28832. esc = escape(ae);
  28833. }
  28834. rest = rest.split(ae).join(esc);
  28835. }
  28836. }
  28837. // chop off from the tail first.
  28838. var hash = rest.indexOf('#');
  28839. if (hash !== -1) {
  28840. // got a fragment string.
  28841. self.hash = rest.substr(hash);
  28842. rest = rest.slice(0, hash);
  28843. }
  28844. var qm = rest.indexOf('?');
  28845. if (qm !== -1) {
  28846. self.search = rest.substr(qm);
  28847. self.query = rest.substr(qm + 1);
  28848. if (parseQueryString) {
  28849. self.query = parse$7(self.query);
  28850. }
  28851. rest = rest.slice(0, qm);
  28852. } else if (parseQueryString) {
  28853. // no query string, but parseQueryString still requested
  28854. self.search = '';
  28855. self.query = {};
  28856. }
  28857. if (rest) self.pathname = rest;
  28858. if (slashedProtocol[lowerProto] &&
  28859. self.hostname && !self.pathname) {
  28860. self.pathname = '/';
  28861. }
  28862. //to support http.request
  28863. if (self.pathname || self.search) {
  28864. p = self.pathname || '';
  28865. var s = self.search || '';
  28866. self.path = p + s;
  28867. }
  28868. // finally, reconstruct the href based on what has been validated.
  28869. self.href = format(self);
  28870. return self;
  28871. }
  28872. function urlFileURLToPath(path) {
  28873. if (typeof path === 'string')
  28874. path = new Url().parse(path);
  28875. else if (!(path instanceof Url))
  28876. throw new TypeError('The "path" argument must be of type string or an instance of URL. Received type ' + (typeof path) + String(path));
  28877. if (path.protocol !== 'file:')
  28878. throw new TypeError('The URL must be of scheme file');
  28879. return getPathFromURLPosix(path);
  28880. }
  28881. function getPathFromURLPosix(url) {
  28882. const pathname = url.pathname;
  28883. for (let n = 0; n < pathname.length; n++) {
  28884. if (pathname[n] === '%') {
  28885. const third = pathname.codePointAt(n + 2) | 0x20;
  28886. if (pathname[n + 1] === '2' && third === 102) {
  28887. throw new TypeError(
  28888. 'must not include encoded / characters'
  28889. );
  28890. }
  28891. }
  28892. }
  28893. return decodeURIComponent(pathname);
  28894. }
  28895. // format a parsed object into a url string
  28896. function urlFormat(obj) {
  28897. // ensure it's an object, and not a string url.
  28898. // If it's an obj, this is a no-op.
  28899. // this way, you can call url_format() on strings
  28900. // to clean up potentially wonky urls.
  28901. if (isString$1(obj)) obj = parse$6({}, obj);
  28902. return format(obj);
  28903. }
  28904. function format(self) {
  28905. var auth = self.auth || '';
  28906. if (auth) {
  28907. auth = encodeURIComponent(auth);
  28908. auth = auth.replace(/%3A/i, ':');
  28909. auth += '@';
  28910. }
  28911. var protocol = self.protocol || '',
  28912. pathname = self.pathname || '',
  28913. hash = self.hash || '',
  28914. host = false,
  28915. query = '';
  28916. if (self.host) {
  28917. host = auth + self.host;
  28918. } else if (self.hostname) {
  28919. host = auth + (self.hostname.indexOf(':') === -1 ?
  28920. self.hostname :
  28921. '[' + this.hostname + ']');
  28922. if (self.port) {
  28923. host += ':' + self.port;
  28924. }
  28925. }
  28926. if (self.query &&
  28927. isObject(self.query) &&
  28928. Object.keys(self.query).length) {
  28929. query = stringify$5(self.query);
  28930. }
  28931. var search = self.search || (query && ('?' + query)) || '';
  28932. if (protocol && protocol.substr(-1) !== ':') protocol += ':';
  28933. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  28934. // unless they had them to begin with.
  28935. if (self.slashes ||
  28936. (!protocol || slashedProtocol[protocol]) && host !== false) {
  28937. host = '//' + (host || '');
  28938. if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  28939. } else if (!host) {
  28940. host = '';
  28941. }
  28942. if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  28943. if (search && search.charAt(0) !== '?') search = '?' + search;
  28944. pathname = pathname.replace(/[?#]/g, function(match) {
  28945. return encodeURIComponent(match);
  28946. });
  28947. search = search.replace('#', '%23');
  28948. return protocol + host + pathname + search + hash;
  28949. }
  28950. Url.prototype.format = function() {
  28951. return format(this);
  28952. };
  28953. function urlResolve(source, relative) {
  28954. return urlParse(source, false, true).resolve(relative);
  28955. }
  28956. Url.prototype.resolve = function(relative) {
  28957. return this.resolveObject(urlParse(relative, false, true)).format();
  28958. };
  28959. function urlResolveObject(source, relative) {
  28960. if (!source) return relative;
  28961. return urlParse(source, false, true).resolveObject(relative);
  28962. }
  28963. Url.prototype.resolveObject = function(relative) {
  28964. if (isString$1(relative)) {
  28965. var rel = new Url();
  28966. rel.parse(relative, false, true);
  28967. relative = rel;
  28968. }
  28969. var result = new Url();
  28970. var tkeys = Object.keys(this);
  28971. for (var tk = 0; tk < tkeys.length; tk++) {
  28972. var tkey = tkeys[tk];
  28973. result[tkey] = this[tkey];
  28974. }
  28975. // hash is always overridden, no matter what.
  28976. // even href="" will remove it.
  28977. result.hash = relative.hash;
  28978. // if the relative url is empty, then there's nothing left to do here.
  28979. if (relative.href === '') {
  28980. result.href = result.format();
  28981. return result;
  28982. }
  28983. // hrefs like //foo/bar always cut to the protocol.
  28984. if (relative.slashes && !relative.protocol) {
  28985. // take everything except the protocol from relative
  28986. var rkeys = Object.keys(relative);
  28987. for (var rk = 0; rk < rkeys.length; rk++) {
  28988. var rkey = rkeys[rk];
  28989. if (rkey !== 'protocol')
  28990. result[rkey] = relative[rkey];
  28991. }
  28992. //urlParse appends trailing / to urls like http://www.example.com
  28993. if (slashedProtocol[result.protocol] &&
  28994. result.hostname && !result.pathname) {
  28995. result.path = result.pathname = '/';
  28996. }
  28997. result.href = result.format();
  28998. return result;
  28999. }
  29000. var relPath;
  29001. if (relative.protocol && relative.protocol !== result.protocol) {
  29002. // if it's a known url protocol, then changing
  29003. // the protocol does weird things
  29004. // first, if it's not file:, then we MUST have a host,
  29005. // and if there was a path
  29006. // to begin with, then we MUST have a path.
  29007. // if it is file:, then the host is dropped,
  29008. // because that's known to be hostless.
  29009. // anything else is assumed to be absolute.
  29010. if (!slashedProtocol[relative.protocol]) {
  29011. var keys = Object.keys(relative);
  29012. for (var v = 0; v < keys.length; v++) {
  29013. var k = keys[v];
  29014. result[k] = relative[k];
  29015. }
  29016. result.href = result.format();
  29017. return result;
  29018. }
  29019. result.protocol = relative.protocol;
  29020. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  29021. relPath = (relative.pathname || '').split('/');
  29022. while (relPath.length && !(relative.host = relPath.shift()));
  29023. if (!relative.host) relative.host = '';
  29024. if (!relative.hostname) relative.hostname = '';
  29025. if (relPath[0] !== '') relPath.unshift('');
  29026. if (relPath.length < 2) relPath.unshift('');
  29027. result.pathname = relPath.join('/');
  29028. } else {
  29029. result.pathname = relative.pathname;
  29030. }
  29031. result.search = relative.search;
  29032. result.query = relative.query;
  29033. result.host = relative.host || '';
  29034. result.auth = relative.auth;
  29035. result.hostname = relative.hostname || relative.host;
  29036. result.port = relative.port;
  29037. // to support http.request
  29038. if (result.pathname || result.search) {
  29039. var p = result.pathname || '';
  29040. var s = result.search || '';
  29041. result.path = p + s;
  29042. }
  29043. result.slashes = result.slashes || relative.slashes;
  29044. result.href = result.format();
  29045. return result;
  29046. }
  29047. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  29048. isRelAbs = (
  29049. relative.host ||
  29050. relative.pathname && relative.pathname.charAt(0) === '/'
  29051. ),
  29052. mustEndAbs = (isRelAbs || isSourceAbs ||
  29053. (result.host && relative.pathname)),
  29054. removeAllDots = mustEndAbs,
  29055. srcPath = result.pathname && result.pathname.split('/') || [],
  29056. psychotic = result.protocol && !slashedProtocol[result.protocol];
  29057. relPath = relative.pathname && relative.pathname.split('/') || [];
  29058. // if the url is a non-slashed url, then relative
  29059. // links like ../.. should be able
  29060. // to crawl up to the hostname, as well. This is strange.
  29061. // result.protocol has already been set by now.
  29062. // Later on, put the first path part into the host field.
  29063. if (psychotic) {
  29064. result.hostname = '';
  29065. result.port = null;
  29066. if (result.host) {
  29067. if (srcPath[0] === '') srcPath[0] = result.host;
  29068. else srcPath.unshift(result.host);
  29069. }
  29070. result.host = '';
  29071. if (relative.protocol) {
  29072. relative.hostname = null;
  29073. relative.port = null;
  29074. if (relative.host) {
  29075. if (relPath[0] === '') relPath[0] = relative.host;
  29076. else relPath.unshift(relative.host);
  29077. }
  29078. relative.host = null;
  29079. }
  29080. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  29081. }
  29082. var authInHost;
  29083. if (isRelAbs) {
  29084. // it's absolute.
  29085. result.host = (relative.host || relative.host === '') ?
  29086. relative.host : result.host;
  29087. result.hostname = (relative.hostname || relative.hostname === '') ?
  29088. relative.hostname : result.hostname;
  29089. result.search = relative.search;
  29090. result.query = relative.query;
  29091. srcPath = relPath;
  29092. // fall through to the dot-handling below.
  29093. } else if (relPath.length) {
  29094. // it's relative
  29095. // throw away the existing file, and take the new path instead.
  29096. if (!srcPath) srcPath = [];
  29097. srcPath.pop();
  29098. srcPath = srcPath.concat(relPath);
  29099. result.search = relative.search;
  29100. result.query = relative.query;
  29101. } else if (!isNullOrUndefined(relative.search)) {
  29102. // just pull out the search.
  29103. // like href='?foo'.
  29104. // Put this after the other two cases because it simplifies the booleans
  29105. if (psychotic) {
  29106. result.hostname = result.host = srcPath.shift();
  29107. //occationaly the auth can get stuck only in host
  29108. //this especially happens in cases like
  29109. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  29110. authInHost = result.host && result.host.indexOf('@') > 0 ?
  29111. result.host.split('@') : false;
  29112. if (authInHost) {
  29113. result.auth = authInHost.shift();
  29114. result.host = result.hostname = authInHost.shift();
  29115. }
  29116. }
  29117. result.search = relative.search;
  29118. result.query = relative.query;
  29119. //to support http.request
  29120. if (!isNull(result.pathname) || !isNull(result.search)) {
  29121. result.path = (result.pathname ? result.pathname : '') +
  29122. (result.search ? result.search : '');
  29123. }
  29124. result.href = result.format();
  29125. return result;
  29126. }
  29127. if (!srcPath.length) {
  29128. // no path at all. easy.
  29129. // we've already handled the other stuff above.
  29130. result.pathname = null;
  29131. //to support http.request
  29132. if (result.search) {
  29133. result.path = '/' + result.search;
  29134. } else {
  29135. result.path = null;
  29136. }
  29137. result.href = result.format();
  29138. return result;
  29139. }
  29140. // if a url ENDs in . or .., then it must get a trailing slash.
  29141. // however, if it ends in anything else non-slashy,
  29142. // then it must NOT get a trailing slash.
  29143. var last = srcPath.slice(-1)[0];
  29144. var hasTrailingSlash = (
  29145. (result.host || relative.host || srcPath.length > 1) &&
  29146. (last === '.' || last === '..') || last === '');
  29147. // strip single dots, resolve double dots to parent dir
  29148. // if the path tries to go above the root, `up` ends up > 0
  29149. var up = 0;
  29150. for (var i = srcPath.length; i >= 0; i--) {
  29151. last = srcPath[i];
  29152. if (last === '.') {
  29153. srcPath.splice(i, 1);
  29154. } else if (last === '..') {
  29155. srcPath.splice(i, 1);
  29156. up++;
  29157. } else if (up) {
  29158. srcPath.splice(i, 1);
  29159. up--;
  29160. }
  29161. }
  29162. // if the path is allowed to go above the root, restore leading ..s
  29163. if (!mustEndAbs && !removeAllDots) {
  29164. for (; up--; up) {
  29165. srcPath.unshift('..');
  29166. }
  29167. }
  29168. if (mustEndAbs && srcPath[0] !== '' &&
  29169. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  29170. srcPath.unshift('');
  29171. }
  29172. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  29173. srcPath.push('');
  29174. }
  29175. var isAbsolute = srcPath[0] === '' ||
  29176. (srcPath[0] && srcPath[0].charAt(0) === '/');
  29177. // put the host back
  29178. if (psychotic) {
  29179. result.hostname = result.host = isAbsolute ? '' :
  29180. srcPath.length ? srcPath.shift() : '';
  29181. //occationaly the auth can get stuck only in host
  29182. //this especially happens in cases like
  29183. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  29184. authInHost = result.host && result.host.indexOf('@') > 0 ?
  29185. result.host.split('@') : false;
  29186. if (authInHost) {
  29187. result.auth = authInHost.shift();
  29188. result.host = result.hostname = authInHost.shift();
  29189. }
  29190. }
  29191. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  29192. if (mustEndAbs && !isAbsolute) {
  29193. srcPath.unshift('');
  29194. }
  29195. if (!srcPath.length) {
  29196. result.pathname = null;
  29197. result.path = null;
  29198. } else {
  29199. result.pathname = srcPath.join('/');
  29200. }
  29201. //to support request.http
  29202. if (!isNull(result.pathname) || !isNull(result.search)) {
  29203. result.path = (result.pathname ? result.pathname : '') +
  29204. (result.search ? result.search : '');
  29205. }
  29206. result.auth = relative.auth || result.auth;
  29207. result.slashes = result.slashes || relative.slashes;
  29208. result.href = result.format();
  29209. return result;
  29210. };
  29211. Url.prototype.parseHost = function() {
  29212. return parseHost(this);
  29213. };
  29214. function parseHost(self) {
  29215. var host = self.host;
  29216. var port = portPattern.exec(host);
  29217. if (port) {
  29218. port = port[0];
  29219. if (port !== ':') {
  29220. self.port = port.substr(1);
  29221. }
  29222. host = host.substr(0, host.length - port.length);
  29223. }
  29224. if (host) self.hostname = host;
  29225. }
  29226. var _polyfillNode_url$1 = /*#__PURE__*/Object.freeze({
  29227. __proto__: null,
  29228. URL: URL$1,
  29229. URLSearchParams: URLSearchParams,
  29230. Url: Url,
  29231. default: _polyfillNode_url,
  29232. fileURLToPath: urlFileURLToPath,
  29233. format: urlFormat,
  29234. parse: urlParse,
  29235. resolve: urlResolve,
  29236. resolveObject: urlResolveObject
  29237. });
  29238. function isRelativeUrl(url) {
  29239. const firstChar = url.charAt(0);
  29240. return firstChar === '.' || firstChar === '~' || firstChar === '@';
  29241. }
  29242. const externalRE = /^(https?:)?\/\//;
  29243. function isExternalUrl(url) {
  29244. return externalRE.test(url);
  29245. }
  29246. const dataUrlRE = /^\s*data:/i;
  29247. function isDataUrl(url) {
  29248. return dataUrlRE.test(url);
  29249. }
  29250. /**
  29251. * Parses string url into URL object.
  29252. */
  29253. function parseUrl(url) {
  29254. const firstChar = url.charAt(0);
  29255. if (firstChar === '~') {
  29256. const secondChar = url.charAt(1);
  29257. url = url.slice(secondChar === '/' ? 2 : 1);
  29258. }
  29259. return parseUriParts(url);
  29260. }
  29261. /**
  29262. * vuejs/component-compiler-utils#22 Support uri fragment in transformed require
  29263. * @param urlString an url as a string
  29264. */
  29265. function parseUriParts(urlString) {
  29266. // A TypeError is thrown if urlString is not a string
  29267. // @see https://nodejs.org/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost
  29268. return urlParse(isString$2(urlString) ? urlString : '', false, true);
  29269. }
  29270. const defaultAssetUrlOptions = {
  29271. base: null,
  29272. includeAbsolute: false,
  29273. tags: {
  29274. video: ['src', 'poster'],
  29275. source: ['src'],
  29276. img: ['src'],
  29277. image: ['xlink:href', 'href'],
  29278. use: ['xlink:href', 'href']
  29279. }
  29280. };
  29281. const normalizeOptions = (options) => {
  29282. if (Object.keys(options).some(key => isArray$3(options[key]))) {
  29283. // legacy option format which directly passes in tags config
  29284. return Object.assign(Object.assign({}, defaultAssetUrlOptions), { tags: options });
  29285. }
  29286. return Object.assign(Object.assign({}, defaultAssetUrlOptions), options);
  29287. };
  29288. const createAssetUrlTransformWithOptions = (options) => {
  29289. return (node, context) => transformAssetUrl(node, context, options);
  29290. };
  29291. /**
  29292. * A `@vue/compiler-core` plugin that transforms relative asset urls into
  29293. * either imports or absolute urls.
  29294. *
  29295. * ``` js
  29296. * // Before
  29297. * createVNode('img', { src: './logo.png' })
  29298. *
  29299. * // After
  29300. * import _imports_0 from './logo.png'
  29301. * createVNode('img', { src: _imports_0 })
  29302. * ```
  29303. */
  29304. const transformAssetUrl = (node, context, options = defaultAssetUrlOptions) => {
  29305. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  29306. if (!node.props.length) {
  29307. return;
  29308. }
  29309. const tags = options.tags || defaultAssetUrlOptions.tags;
  29310. const attrs = tags[node.tag];
  29311. const wildCardAttrs = tags['*'];
  29312. if (!attrs && !wildCardAttrs) {
  29313. return;
  29314. }
  29315. const assetAttrs = (attrs || []).concat(wildCardAttrs || []);
  29316. node.props.forEach((attr, index) => {
  29317. if (attr.type !== 6 /* NodeTypes.ATTRIBUTE */ ||
  29318. !assetAttrs.includes(attr.name) ||
  29319. !attr.value ||
  29320. isExternalUrl(attr.value.content) ||
  29321. isDataUrl(attr.value.content) ||
  29322. attr.value.content[0] === '#' ||
  29323. (!options.includeAbsolute && !isRelativeUrl(attr.value.content))) {
  29324. return;
  29325. }
  29326. const url = parseUrl(attr.value.content);
  29327. if (options.base && attr.value.content[0] === '.') {
  29328. // explicit base - directly rewrite relative urls into absolute url
  29329. // to avoid generating extra imports
  29330. // Allow for full hostnames provided in options.base
  29331. const base = parseUrl(options.base);
  29332. const protocol = base.protocol || '';
  29333. const host = base.host ? protocol + '//' + base.host : '';
  29334. const basePath = base.path || '/';
  29335. // when packaged in the browser, path will be using the posix-
  29336. // only version provided by rollup-plugin-node-builtins.
  29337. attr.value.content =
  29338. host +
  29339. (path.posix || path).join(basePath, url.path + (url.hash || ''));
  29340. return;
  29341. }
  29342. // otherwise, transform the url into an import.
  29343. // this assumes a bundler will resolve the import into the correct
  29344. // absolute url (e.g. webpack file-loader)
  29345. const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context);
  29346. node.props[index] = {
  29347. type: 7 /* NodeTypes.DIRECTIVE */,
  29348. name: 'bind',
  29349. arg: createSimpleExpression(attr.name, true, attr.loc),
  29350. exp,
  29351. modifiers: [],
  29352. loc: attr.loc
  29353. };
  29354. });
  29355. }
  29356. };
  29357. function getImportsExpressionExp(path, hash, loc, context) {
  29358. if (path) {
  29359. let name;
  29360. let exp;
  29361. const existingIndex = context.imports.findIndex(i => i.path === path);
  29362. if (existingIndex > -1) {
  29363. name = `_imports_${existingIndex}`;
  29364. exp = context.imports[existingIndex].exp;
  29365. }
  29366. else {
  29367. name = `_imports_${context.imports.length}`;
  29368. exp = createSimpleExpression(name, false, loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  29369. context.imports.push({ exp, path });
  29370. }
  29371. if (!hash) {
  29372. return exp;
  29373. }
  29374. const hashExp = `${name} + '${hash}'`;
  29375. const finalExp = createSimpleExpression(hashExp, false, loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  29376. if (!context.hoistStatic) {
  29377. return finalExp;
  29378. }
  29379. const existingHoistIndex = context.hoists.findIndex(h => {
  29380. return (h &&
  29381. h.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  29382. !h.isStatic &&
  29383. h.content === hashExp);
  29384. });
  29385. if (existingHoistIndex > -1) {
  29386. return createSimpleExpression(`_hoisted_${existingHoistIndex + 1}`, false, loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  29387. }
  29388. return context.hoist(finalExp);
  29389. }
  29390. else {
  29391. return createSimpleExpression(`''`, false, loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  29392. }
  29393. }
  29394. const srcsetTags = ['img', 'source'];
  29395. // http://w3c.github.io/html/semantics-embedded-content.html#ref-for-image-candidate-string-5
  29396. const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
  29397. const createSrcsetTransformWithOptions = (options) => {
  29398. return (node, context) => transformSrcset(node, context, options);
  29399. };
  29400. const transformSrcset = (node, context, options = defaultAssetUrlOptions) => {
  29401. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  29402. if (srcsetTags.includes(node.tag) && node.props.length) {
  29403. node.props.forEach((attr, index) => {
  29404. if (attr.name === 'srcset' && attr.type === 6 /* NodeTypes.ATTRIBUTE */) {
  29405. if (!attr.value)
  29406. return;
  29407. const value = attr.value.content;
  29408. if (!value)
  29409. return;
  29410. const imageCandidates = value.split(',').map(s => {
  29411. // The attribute value arrives here with all whitespace, except
  29412. // normal spaces, represented by escape sequences
  29413. const [url, descriptor] = s
  29414. .replace(escapedSpaceCharacters, ' ')
  29415. .trim()
  29416. .split(' ', 2);
  29417. return { url, descriptor };
  29418. });
  29419. // data urls contains comma after the encoding so we need to re-merge
  29420. // them
  29421. for (let i = 0; i < imageCandidates.length; i++) {
  29422. const { url } = imageCandidates[i];
  29423. if (isDataUrl(url)) {
  29424. imageCandidates[i + 1].url =
  29425. url + ',' + imageCandidates[i + 1].url;
  29426. imageCandidates.splice(i, 1);
  29427. }
  29428. }
  29429. const shouldProcessUrl = (url) => {
  29430. return (!isExternalUrl(url) &&
  29431. !isDataUrl(url) &&
  29432. (options.includeAbsolute || isRelativeUrl(url)));
  29433. };
  29434. // When srcset does not contain any qualified URLs, skip transforming
  29435. if (!imageCandidates.some(({ url }) => shouldProcessUrl(url))) {
  29436. return;
  29437. }
  29438. if (options.base) {
  29439. const base = options.base;
  29440. const set = [];
  29441. let needImportTransform = false;
  29442. imageCandidates.forEach(candidate => {
  29443. let { url, descriptor } = candidate;
  29444. descriptor = descriptor ? ` ${descriptor}` : ``;
  29445. if (url[0] === '.') {
  29446. candidate.url = (path.posix || path).join(base, url);
  29447. set.push(candidate.url + descriptor);
  29448. }
  29449. else if (shouldProcessUrl(url)) {
  29450. needImportTransform = true;
  29451. }
  29452. else {
  29453. set.push(url + descriptor);
  29454. }
  29455. });
  29456. if (!needImportTransform) {
  29457. attr.value.content = set.join(', ');
  29458. return;
  29459. }
  29460. }
  29461. const compoundExpression = createCompoundExpression([], attr.loc);
  29462. imageCandidates.forEach(({ url, descriptor }, index) => {
  29463. if (shouldProcessUrl(url)) {
  29464. const { path } = parseUrl(url);
  29465. let exp;
  29466. if (path) {
  29467. const existingImportsIndex = context.imports.findIndex(i => i.path === path);
  29468. if (existingImportsIndex > -1) {
  29469. exp = createSimpleExpression(`_imports_${existingImportsIndex}`, false, attr.loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  29470. }
  29471. else {
  29472. exp = createSimpleExpression(`_imports_${context.imports.length}`, false, attr.loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  29473. context.imports.push({ exp, path });
  29474. }
  29475. compoundExpression.children.push(exp);
  29476. }
  29477. }
  29478. else {
  29479. const exp = createSimpleExpression(`"${url}"`, false, attr.loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  29480. compoundExpression.children.push(exp);
  29481. }
  29482. const isNotLast = imageCandidates.length - 1 > index;
  29483. if (descriptor && isNotLast) {
  29484. compoundExpression.children.push(` + ' ${descriptor}, ' + `);
  29485. }
  29486. else if (descriptor) {
  29487. compoundExpression.children.push(` + ' ${descriptor}'`);
  29488. }
  29489. else if (isNotLast) {
  29490. compoundExpression.children.push(` + ', ' + `);
  29491. }
  29492. });
  29493. let exp = compoundExpression;
  29494. if (context.hoistStatic) {
  29495. exp = context.hoist(compoundExpression);
  29496. exp.constType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  29497. }
  29498. node.props[index] = {
  29499. type: 7 /* NodeTypes.DIRECTIVE */,
  29500. name: 'bind',
  29501. arg: createSimpleExpression('srcset', true, attr.loc),
  29502. exp,
  29503. modifiers: [],
  29504. loc: attr.loc
  29505. };
  29506. }
  29507. });
  29508. }
  29509. }
  29510. };
  29511. const SSR_INTERPOLATE = Symbol(`ssrInterpolate`);
  29512. const SSR_RENDER_VNODE = Symbol(`ssrRenderVNode`);
  29513. const SSR_RENDER_COMPONENT = Symbol(`ssrRenderComponent`);
  29514. const SSR_RENDER_SLOT = Symbol(`ssrRenderSlot`);
  29515. const SSR_RENDER_SLOT_INNER = Symbol(`ssrRenderSlotInner`);
  29516. const SSR_RENDER_CLASS = Symbol(`ssrRenderClass`);
  29517. const SSR_RENDER_STYLE = Symbol(`ssrRenderStyle`);
  29518. const SSR_RENDER_ATTRS = Symbol(`ssrRenderAttrs`);
  29519. const SSR_RENDER_ATTR = Symbol(`ssrRenderAttr`);
  29520. const SSR_RENDER_DYNAMIC_ATTR = Symbol(`ssrRenderDynamicAttr`);
  29521. const SSR_RENDER_LIST = Symbol(`ssrRenderList`);
  29522. const SSR_INCLUDE_BOOLEAN_ATTR = Symbol(`ssrIncludeBooleanAttr`);
  29523. const SSR_LOOSE_EQUAL = Symbol(`ssrLooseEqual`);
  29524. const SSR_LOOSE_CONTAIN = Symbol(`ssrLooseContain`);
  29525. const SSR_RENDER_DYNAMIC_MODEL = Symbol(`ssrRenderDynamicModel`);
  29526. const SSR_GET_DYNAMIC_MODEL_PROPS = Symbol(`ssrGetDynamicModelProps`);
  29527. const SSR_RENDER_TELEPORT = Symbol(`ssrRenderTeleport`);
  29528. const SSR_RENDER_SUSPENSE = Symbol(`ssrRenderSuspense`);
  29529. const SSR_GET_DIRECTIVE_PROPS = Symbol(`ssrGetDirectiveProps`);
  29530. const ssrHelpers = {
  29531. [SSR_INTERPOLATE]: `ssrInterpolate`,
  29532. [SSR_RENDER_VNODE]: `ssrRenderVNode`,
  29533. [SSR_RENDER_COMPONENT]: `ssrRenderComponent`,
  29534. [SSR_RENDER_SLOT]: `ssrRenderSlot`,
  29535. [SSR_RENDER_SLOT_INNER]: `ssrRenderSlotInner`,
  29536. [SSR_RENDER_CLASS]: `ssrRenderClass`,
  29537. [SSR_RENDER_STYLE]: `ssrRenderStyle`,
  29538. [SSR_RENDER_ATTRS]: `ssrRenderAttrs`,
  29539. [SSR_RENDER_ATTR]: `ssrRenderAttr`,
  29540. [SSR_RENDER_DYNAMIC_ATTR]: `ssrRenderDynamicAttr`,
  29541. [SSR_RENDER_LIST]: `ssrRenderList`,
  29542. [SSR_INCLUDE_BOOLEAN_ATTR]: `ssrIncludeBooleanAttr`,
  29543. [SSR_LOOSE_EQUAL]: `ssrLooseEqual`,
  29544. [SSR_LOOSE_CONTAIN]: `ssrLooseContain`,
  29545. [SSR_RENDER_DYNAMIC_MODEL]: `ssrRenderDynamicModel`,
  29546. [SSR_GET_DYNAMIC_MODEL_PROPS]: `ssrGetDynamicModelProps`,
  29547. [SSR_RENDER_TELEPORT]: `ssrRenderTeleport`,
  29548. [SSR_RENDER_SUSPENSE]: `ssrRenderSuspense`,
  29549. [SSR_GET_DIRECTIVE_PROPS]: `ssrGetDirectiveProps`
  29550. };
  29551. // Note: these are helpers imported from @vue/server-renderer
  29552. // make sure the names match!
  29553. registerRuntimeHelpers(ssrHelpers);
  29554. // Plugin for the first transform pass, which simply constructs the AST node
  29555. const ssrTransformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, processIf);
  29556. // This is called during the 2nd transform pass to construct the SSR-specific
  29557. // codegen nodes.
  29558. function ssrProcessIf(node, context, disableNestedFragments = false) {
  29559. const [rootBranch] = node.branches;
  29560. const ifStatement = createIfStatement(rootBranch.condition, processIfBranch(rootBranch, context, disableNestedFragments));
  29561. context.pushStatement(ifStatement);
  29562. let currentIf = ifStatement;
  29563. for (let i = 1; i < node.branches.length; i++) {
  29564. const branch = node.branches[i];
  29565. const branchBlockStatement = processIfBranch(branch, context, disableNestedFragments);
  29566. if (branch.condition) {
  29567. // else-if
  29568. currentIf = currentIf.alternate = createIfStatement(branch.condition, branchBlockStatement);
  29569. }
  29570. else {
  29571. // else
  29572. currentIf.alternate = branchBlockStatement;
  29573. }
  29574. }
  29575. if (!currentIf.alternate) {
  29576. currentIf.alternate = createBlockStatement([
  29577. createCallExpression(`_push`, ['`<!---->`'])
  29578. ]);
  29579. }
  29580. }
  29581. function processIfBranch(branch, context, disableNestedFragments = false) {
  29582. const { children } = branch;
  29583. const needFragmentWrapper = !disableNestedFragments &&
  29584. (children.length !== 1 || children[0].type !== 1 /* NodeTypes.ELEMENT */) &&
  29585. // optimize away nested fragments when the only child is a ForNode
  29586. !(children.length === 1 && children[0].type === 11 /* NodeTypes.FOR */);
  29587. return processChildrenAsStatement(branch, context, needFragmentWrapper);
  29588. }
  29589. // Plugin for the first transform pass, which simply constructs the AST node
  29590. const ssrTransformFor = createStructuralDirectiveTransform('for', processFor);
  29591. // This is called during the 2nd transform pass to construct the SSR-specific
  29592. // codegen nodes.
  29593. function ssrProcessFor(node, context, disableNestedFragments = false) {
  29594. const needFragmentWrapper = !disableNestedFragments &&
  29595. (node.children.length !== 1 || node.children[0].type !== 1 /* NodeTypes.ELEMENT */);
  29596. const renderLoop = createFunctionExpression(createForLoopParams(node.parseResult));
  29597. renderLoop.body = processChildrenAsStatement(node, context, needFragmentWrapper);
  29598. // v-for always renders a fragment unless explicitly disabled
  29599. if (!disableNestedFragments) {
  29600. context.pushStringPart(`<!--[-->`);
  29601. }
  29602. context.pushStatement(createCallExpression(context.helper(SSR_RENDER_LIST), [
  29603. node.source,
  29604. renderLoop
  29605. ]));
  29606. if (!disableNestedFragments) {
  29607. context.pushStringPart(`<!--]-->`);
  29608. }
  29609. }
  29610. const ssrTransformSlotOutlet = (node, context) => {
  29611. if (isSlotOutlet(node)) {
  29612. const { slotName, slotProps } = processSlotOutlet(node, context);
  29613. const args = [
  29614. `_ctx.$slots`,
  29615. slotName,
  29616. slotProps || `{}`,
  29617. // fallback content placeholder. will be replaced in the process phase
  29618. `null`,
  29619. `_push`,
  29620. `_parent`
  29621. ];
  29622. // inject slot scope id if current template uses :slotted
  29623. if (context.scopeId && context.slotted !== false) {
  29624. args.push(`"${context.scopeId}-s"`);
  29625. }
  29626. let method = SSR_RENDER_SLOT;
  29627. // #3989
  29628. // check if this is a single slot inside a transition wrapper - since
  29629. // transition will unwrap the slot fragment into a single vnode at runtime,
  29630. // we need to avoid rendering the slot as a fragment.
  29631. const parent = context.parent;
  29632. if (parent &&
  29633. parent.type === 1 /* NodeTypes.ELEMENT */ &&
  29634. parent.tagType === 1 /* ElementTypes.COMPONENT */ &&
  29635. resolveComponentType(parent, context, true) === TRANSITION &&
  29636. parent.children.filter(c => c.type === 1 /* NodeTypes.ELEMENT */).length === 1) {
  29637. method = SSR_RENDER_SLOT_INNER;
  29638. if (!(context.scopeId && context.slotted !== false)) {
  29639. args.push('null');
  29640. }
  29641. args.push('true');
  29642. }
  29643. node.ssrCodegenNode = createCallExpression(context.helper(method), args);
  29644. }
  29645. };
  29646. function ssrProcessSlotOutlet(node, context) {
  29647. const renderCall = node.ssrCodegenNode;
  29648. // has fallback content
  29649. if (node.children.length) {
  29650. const fallbackRenderFn = createFunctionExpression([]);
  29651. fallbackRenderFn.body = processChildrenAsStatement(node, context);
  29652. // _renderSlot(slots, name, props, fallback, ...)
  29653. renderCall.arguments[3] = fallbackRenderFn;
  29654. }
  29655. // Forwarded <slot/>. Merge slot scope ids
  29656. if (context.withSlotScopeId) {
  29657. const slotScopeId = renderCall.arguments[6];
  29658. renderCall.arguments[6] = slotScopeId
  29659. ? `${slotScopeId} + _scopeId`
  29660. : `_scopeId`;
  29661. }
  29662. context.pushStatement(node.ssrCodegenNode);
  29663. }
  29664. function createSSRCompilerError(code, loc) {
  29665. return createCompilerError(code, loc, SSRErrorMessages);
  29666. }
  29667. const SSRErrorMessages = {
  29668. [62 /* SSRErrorCodes.X_SSR_UNSAFE_ATTR_NAME */]: `Unsafe attribute name for SSR.`,
  29669. [63 /* SSRErrorCodes.X_SSR_NO_TELEPORT_TARGET */]: `Missing the 'to' prop on teleport element.`,
  29670. [64 /* SSRErrorCodes.X_SSR_INVALID_AST_NODE */]: `Invalid AST node during SSR transform.`
  29671. };
  29672. // Note: this is a 2nd-pass codegen transform.
  29673. function ssrProcessTeleport(node, context) {
  29674. const targetProp = findProp(node, 'to');
  29675. if (!targetProp) {
  29676. context.onError(createSSRCompilerError(63 /* SSRErrorCodes.X_SSR_NO_TELEPORT_TARGET */, node.loc));
  29677. return;
  29678. }
  29679. let target;
  29680. if (targetProp.type === 6 /* NodeTypes.ATTRIBUTE */) {
  29681. target =
  29682. targetProp.value && createSimpleExpression(targetProp.value.content, true);
  29683. }
  29684. else {
  29685. target = targetProp.exp;
  29686. }
  29687. if (!target) {
  29688. context.onError(createSSRCompilerError(63 /* SSRErrorCodes.X_SSR_NO_TELEPORT_TARGET */, targetProp.loc));
  29689. return;
  29690. }
  29691. const disabledProp = findProp(node, 'disabled', false, true /* allow empty */);
  29692. const disabled = disabledProp
  29693. ? disabledProp.type === 6 /* NodeTypes.ATTRIBUTE */
  29694. ? `true`
  29695. : disabledProp.exp || `false`
  29696. : `false`;
  29697. const contentRenderFn = createFunctionExpression([`_push`], undefined, // Body is added later
  29698. true, // newline
  29699. false, // isSlot
  29700. node.loc);
  29701. contentRenderFn.body = processChildrenAsStatement(node, context);
  29702. context.pushStatement(createCallExpression(context.helper(SSR_RENDER_TELEPORT), [
  29703. `_push`,
  29704. contentRenderFn,
  29705. target,
  29706. disabled,
  29707. `_parent`
  29708. ]));
  29709. }
  29710. const wipMap$2 = new WeakMap();
  29711. // phase 1
  29712. function ssrTransformSuspense(node, context) {
  29713. return () => {
  29714. if (node.children.length) {
  29715. const wipEntry = {
  29716. slotsExp: null,
  29717. wipSlots: []
  29718. };
  29719. wipMap$2.set(node, wipEntry);
  29720. wipEntry.slotsExp = buildSlots(node, context, (_props, children, loc) => {
  29721. const fn = createFunctionExpression([], undefined, // no return, assign body later
  29722. true, // newline
  29723. false, // suspense slots are not treated as normal slots
  29724. loc);
  29725. wipEntry.wipSlots.push({
  29726. fn,
  29727. children
  29728. });
  29729. return fn;
  29730. }).slots;
  29731. }
  29732. };
  29733. }
  29734. // phase 2
  29735. function ssrProcessSuspense(node, context) {
  29736. // complete wip slots with ssr code
  29737. const wipEntry = wipMap$2.get(node);
  29738. if (!wipEntry) {
  29739. return;
  29740. }
  29741. const { slotsExp, wipSlots } = wipEntry;
  29742. for (let i = 0; i < wipSlots.length; i++) {
  29743. const slot = wipSlots[i];
  29744. slot.fn.body = processChildrenAsStatement(slot, context);
  29745. }
  29746. // _push(ssrRenderSuspense(slots))
  29747. context.pushStatement(createCallExpression(context.helper(SSR_RENDER_SUSPENSE), [
  29748. `_push`,
  29749. slotsExp
  29750. ]));
  29751. }
  29752. // for directives with children overwrite (e.g. v-html & v-text), we need to
  29753. // store the raw children so that they can be added in the 2nd pass.
  29754. const rawChildrenMap = new WeakMap();
  29755. const ssrTransformElement = (node, context) => {
  29756. if (node.type !== 1 /* NodeTypes.ELEMENT */ ||
  29757. node.tagType !== 0 /* ElementTypes.ELEMENT */) {
  29758. return;
  29759. }
  29760. return function ssrPostTransformElement() {
  29761. // element
  29762. // generate the template literal representing the open tag.
  29763. const openTag = [`<${node.tag}`];
  29764. // some tags need to be passed to runtime for special checks
  29765. const needTagForRuntime = node.tag === 'textarea' || node.tag.indexOf('-') > 0;
  29766. // v-bind="obj", v-bind:[key] and custom directives can potentially
  29767. // overwrite other static attrs and can affect final rendering result,
  29768. // so when they are present we need to bail out to full `renderAttrs`
  29769. const hasDynamicVBind = hasDynamicKeyVBind(node);
  29770. const hasCustomDir = node.props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ && !isBuiltInDirective(p.name));
  29771. const needMergeProps = hasDynamicVBind || hasCustomDir;
  29772. if (needMergeProps) {
  29773. const { props, directives } = buildProps(node, context, node.props, false /* isComponent */, false /* isDynamicComponent */, true /* ssr */);
  29774. if (props || directives.length) {
  29775. const mergedProps = buildSSRProps(props, directives, context);
  29776. const propsExp = createCallExpression(context.helper(SSR_RENDER_ATTRS), [mergedProps]);
  29777. if (node.tag === 'textarea') {
  29778. const existingText = node.children[0];
  29779. // If interpolation, this is dynamic <textarea> content, potentially
  29780. // injected by v-model and takes higher priority than v-bind value
  29781. if (!existingText || existingText.type !== 5 /* NodeTypes.INTERPOLATION */) {
  29782. // <textarea> with dynamic v-bind. We don't know if the final props
  29783. // will contain .value, so we will have to do something special:
  29784. // assign the merged props to a temp variable, and check whether
  29785. // it contains value (if yes, render is as children).
  29786. const tempId = `_temp${context.temps++}`;
  29787. propsExp.arguments = [
  29788. createAssignmentExpression(createSimpleExpression(tempId, false), mergedProps)
  29789. ];
  29790. rawChildrenMap.set(node, createCallExpression(context.helper(SSR_INTERPOLATE), [
  29791. createConditionalExpression(createSimpleExpression(`"value" in ${tempId}`, false), createSimpleExpression(`${tempId}.value`, false), createSimpleExpression(existingText ? existingText.content : ``, true), false)
  29792. ]));
  29793. }
  29794. }
  29795. else if (node.tag === 'input') {
  29796. // <input v-bind="obj" v-model>
  29797. // we need to determine the props to render for the dynamic v-model
  29798. // and merge it with the v-bind expression.
  29799. const vModel = findVModel(node);
  29800. if (vModel) {
  29801. // 1. save the props (san v-model) in a temp variable
  29802. const tempId = `_temp${context.temps++}`;
  29803. const tempExp = createSimpleExpression(tempId, false);
  29804. propsExp.arguments = [
  29805. createSequenceExpression([
  29806. createAssignmentExpression(tempExp, mergedProps),
  29807. createCallExpression(context.helper(MERGE_PROPS), [
  29808. tempExp,
  29809. createCallExpression(context.helper(SSR_GET_DYNAMIC_MODEL_PROPS), [
  29810. tempExp,
  29811. vModel.exp // model
  29812. ])
  29813. ])
  29814. ])
  29815. ];
  29816. }
  29817. }
  29818. if (needTagForRuntime) {
  29819. propsExp.arguments.push(`"${node.tag}"`);
  29820. }
  29821. openTag.push(propsExp);
  29822. }
  29823. }
  29824. // book keeping static/dynamic class merging.
  29825. let dynamicClassBinding = undefined;
  29826. let staticClassBinding = undefined;
  29827. // all style bindings are converted to dynamic by transformStyle.
  29828. // but we need to make sure to merge them.
  29829. let dynamicStyleBinding = undefined;
  29830. for (let i = 0; i < node.props.length; i++) {
  29831. const prop = node.props[i];
  29832. // ignore true-value/false-value on input
  29833. if (node.tag === 'input' && isTrueFalseValue(prop)) {
  29834. continue;
  29835. }
  29836. // special cases with children override
  29837. if (prop.type === 7 /* NodeTypes.DIRECTIVE */) {
  29838. if (prop.name === 'html' && prop.exp) {
  29839. rawChildrenMap.set(node, prop.exp);
  29840. }
  29841. else if (prop.name === 'text' && prop.exp) {
  29842. node.children = [createInterpolation(prop.exp, prop.loc)];
  29843. }
  29844. else if (prop.name === 'slot') {
  29845. context.onError(createCompilerError(40 /* ErrorCodes.X_V_SLOT_MISPLACED */, prop.loc));
  29846. }
  29847. else if (isTextareaWithValue(node, prop) && prop.exp) {
  29848. if (!needMergeProps) {
  29849. node.children = [createInterpolation(prop.exp, prop.loc)];
  29850. }
  29851. }
  29852. else if (!needMergeProps && prop.name !== 'on') {
  29853. // Directive transforms.
  29854. const directiveTransform = context.directiveTransforms[prop.name];
  29855. if (directiveTransform) {
  29856. const { props, ssrTagParts } = directiveTransform(prop, node, context);
  29857. if (ssrTagParts) {
  29858. openTag.push(...ssrTagParts);
  29859. }
  29860. for (let j = 0; j < props.length; j++) {
  29861. const { key, value } = props[j];
  29862. if (isStaticExp(key)) {
  29863. let attrName = key.content;
  29864. // static key attr
  29865. if (attrName === 'key' || attrName === 'ref') {
  29866. continue;
  29867. }
  29868. if (attrName === 'class') {
  29869. openTag.push(` class="`, (dynamicClassBinding = createCallExpression(context.helper(SSR_RENDER_CLASS), [value])), `"`);
  29870. }
  29871. else if (attrName === 'style') {
  29872. if (dynamicStyleBinding) {
  29873. // already has style binding, merge into it.
  29874. mergeCall(dynamicStyleBinding, value);
  29875. }
  29876. else {
  29877. openTag.push(` style="`, (dynamicStyleBinding = createCallExpression(context.helper(SSR_RENDER_STYLE), [value])), `"`);
  29878. }
  29879. }
  29880. else {
  29881. attrName =
  29882. node.tag.indexOf('-') > 0
  29883. ? attrName // preserve raw name on custom elements
  29884. : propsToAttrMap[attrName] || attrName.toLowerCase();
  29885. if (isBooleanAttr(attrName)) {
  29886. openTag.push(createConditionalExpression(createCallExpression(context.helper(SSR_INCLUDE_BOOLEAN_ATTR), [value]), createSimpleExpression(' ' + attrName, true), createSimpleExpression('', true), false /* no newline */));
  29887. }
  29888. else if (isSSRSafeAttrName(attrName)) {
  29889. openTag.push(createCallExpression(context.helper(SSR_RENDER_ATTR), [
  29890. key,
  29891. value
  29892. ]));
  29893. }
  29894. else {
  29895. context.onError(createSSRCompilerError(62 /* SSRErrorCodes.X_SSR_UNSAFE_ATTR_NAME */, key.loc));
  29896. }
  29897. }
  29898. }
  29899. else {
  29900. // dynamic key attr
  29901. // this branch is only encountered for custom directive
  29902. // transforms that returns properties with dynamic keys
  29903. const args = [key, value];
  29904. if (needTagForRuntime) {
  29905. args.push(`"${node.tag}"`);
  29906. }
  29907. openTag.push(createCallExpression(context.helper(SSR_RENDER_DYNAMIC_ATTR), args));
  29908. }
  29909. }
  29910. }
  29911. }
  29912. }
  29913. else {
  29914. // special case: value on <textarea>
  29915. if (node.tag === 'textarea' && prop.name === 'value' && prop.value) {
  29916. rawChildrenMap.set(node, escapeHtml(prop.value.content));
  29917. }
  29918. else if (!needMergeProps) {
  29919. if (prop.name === 'key' || prop.name === 'ref') {
  29920. continue;
  29921. }
  29922. // static prop
  29923. if (prop.name === 'class' && prop.value) {
  29924. staticClassBinding = JSON.stringify(prop.value.content);
  29925. }
  29926. openTag.push(` ${prop.name}` +
  29927. (prop.value ? `="${escapeHtml(prop.value.content)}"` : ``));
  29928. }
  29929. }
  29930. }
  29931. // handle co-existence of dynamic + static class bindings
  29932. if (dynamicClassBinding && staticClassBinding) {
  29933. mergeCall(dynamicClassBinding, staticClassBinding);
  29934. removeStaticBinding(openTag, 'class');
  29935. }
  29936. if (context.scopeId) {
  29937. openTag.push(` ${context.scopeId}`);
  29938. }
  29939. node.ssrCodegenNode = createTemplateLiteral(openTag);
  29940. };
  29941. };
  29942. function buildSSRProps(props, directives, context) {
  29943. let mergePropsArgs = [];
  29944. if (props) {
  29945. if (props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  29946. // already a mergeProps call
  29947. mergePropsArgs = props.arguments;
  29948. }
  29949. else {
  29950. mergePropsArgs.push(props);
  29951. }
  29952. }
  29953. if (directives.length) {
  29954. for (const dir of directives) {
  29955. mergePropsArgs.push(createCallExpression(context.helper(SSR_GET_DIRECTIVE_PROPS), [
  29956. `_ctx`,
  29957. ...buildDirectiveArgs(dir, context).elements
  29958. ]));
  29959. }
  29960. }
  29961. return mergePropsArgs.length > 1
  29962. ? createCallExpression(context.helper(MERGE_PROPS), mergePropsArgs)
  29963. : mergePropsArgs[0];
  29964. }
  29965. function isTrueFalseValue(prop) {
  29966. if (prop.type === 7 /* NodeTypes.DIRECTIVE */) {
  29967. return (prop.name === 'bind' &&
  29968. prop.arg &&
  29969. isStaticExp(prop.arg) &&
  29970. (prop.arg.content === 'true-value' || prop.arg.content === 'false-value'));
  29971. }
  29972. else {
  29973. return prop.name === 'true-value' || prop.name === 'false-value';
  29974. }
  29975. }
  29976. function isTextareaWithValue(node, prop) {
  29977. return !!(node.tag === 'textarea' &&
  29978. prop.name === 'bind' &&
  29979. isStaticArgOf(prop.arg, 'value'));
  29980. }
  29981. function mergeCall(call, arg) {
  29982. const existing = call.arguments[0];
  29983. if (existing.type === 17 /* NodeTypes.JS_ARRAY_EXPRESSION */) {
  29984. existing.elements.push(arg);
  29985. }
  29986. else {
  29987. call.arguments[0] = createArrayExpression([existing, arg]);
  29988. }
  29989. }
  29990. function removeStaticBinding(tag, binding) {
  29991. const regExp = new RegExp(`^ ${binding}=".+"$`);
  29992. const i = tag.findIndex(e => typeof e === 'string' && regExp.test(e));
  29993. if (i > -1) {
  29994. tag.splice(i, 1);
  29995. }
  29996. }
  29997. function findVModel(node) {
  29998. return node.props.find(p => p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'model' && p.exp);
  29999. }
  30000. function ssrProcessElement(node, context) {
  30001. const isVoidTag = context.options.isVoidTag || NO;
  30002. const elementsToAdd = node.ssrCodegenNode.elements;
  30003. for (let j = 0; j < elementsToAdd.length; j++) {
  30004. context.pushStringPart(elementsToAdd[j]);
  30005. }
  30006. // Handle slot scopeId
  30007. if (context.withSlotScopeId) {
  30008. context.pushStringPart(createSimpleExpression(`_scopeId`, false));
  30009. }
  30010. // close open tag
  30011. context.pushStringPart(`>`);
  30012. const rawChildren = rawChildrenMap.get(node);
  30013. if (rawChildren) {
  30014. context.pushStringPart(rawChildren);
  30015. }
  30016. else if (node.children.length) {
  30017. processChildren(node, context);
  30018. }
  30019. if (!isVoidTag(node.tag)) {
  30020. // push closing tag
  30021. context.pushStringPart(`</${node.tag}>`);
  30022. }
  30023. }
  30024. const wipMap$1 = new WeakMap();
  30025. // phase 1: build props
  30026. function ssrTransformTransitionGroup(node, context) {
  30027. return () => {
  30028. const tag = findProp(node, 'tag');
  30029. if (tag) {
  30030. const otherProps = node.props.filter(p => p !== tag);
  30031. const { props, directives } = buildProps(node, context, otherProps, true /* isComponent */, false /* isDynamicComponent */, true /* ssr (skip event listeners) */);
  30032. let propsExp = null;
  30033. if (props || directives.length) {
  30034. propsExp = createCallExpression(context.helper(SSR_RENDER_ATTRS), [
  30035. buildSSRProps(props, directives, context)
  30036. ]);
  30037. }
  30038. wipMap$1.set(node, {
  30039. tag,
  30040. propsExp
  30041. });
  30042. }
  30043. };
  30044. }
  30045. // phase 2: process children
  30046. function ssrProcessTransitionGroup(node, context) {
  30047. const entry = wipMap$1.get(node);
  30048. if (entry) {
  30049. const { tag, propsExp } = entry;
  30050. if (tag.type === 7 /* NodeTypes.DIRECTIVE */) {
  30051. // dynamic :tag
  30052. context.pushStringPart(`<`);
  30053. context.pushStringPart(tag.exp);
  30054. if (propsExp) {
  30055. context.pushStringPart(propsExp);
  30056. }
  30057. context.pushStringPart(`>`);
  30058. processChildren(node, context, false,
  30059. /**
  30060. * TransitionGroup has the special runtime behavior of flattening and
  30061. * concatenating all children into a single fragment (in order for them to
  30062. * be patched using the same key map) so we need to account for that here
  30063. * by disabling nested fragment wrappers from being generated.
  30064. */
  30065. true);
  30066. context.pushStringPart(`</`);
  30067. context.pushStringPart(tag.exp);
  30068. context.pushStringPart(`>`);
  30069. }
  30070. else {
  30071. // static tag
  30072. context.pushStringPart(`<${tag.value.content}`);
  30073. if (propsExp) {
  30074. context.pushStringPart(propsExp);
  30075. }
  30076. context.pushStringPart(`>`);
  30077. processChildren(node, context, false, true);
  30078. context.pushStringPart(`</${tag.value.content}>`);
  30079. }
  30080. }
  30081. else {
  30082. // fragment
  30083. processChildren(node, context, true, true);
  30084. }
  30085. }
  30086. // We need to construct the slot functions in the 1st pass to ensure proper
  30087. // scope tracking, but the children of each slot cannot be processed until
  30088. // the 2nd pass, so we store the WIP slot functions in a weakMap during the 1st
  30089. // pass and complete them in the 2nd pass.
  30090. const wipMap = new WeakMap();
  30091. const WIP_SLOT = Symbol();
  30092. const componentTypeMap = new WeakMap();
  30093. // ssr component transform is done in two phases:
  30094. // In phase 1. we use `buildSlot` to analyze the children of the component into
  30095. // WIP slot functions (it must be done in phase 1 because `buildSlot` relies on
  30096. // the core transform context).
  30097. // In phase 2. we convert the WIP slots from phase 1 into ssr-specific codegen
  30098. // nodes.
  30099. const ssrTransformComponent = (node, context) => {
  30100. if (node.type !== 1 /* NodeTypes.ELEMENT */ ||
  30101. node.tagType !== 1 /* ElementTypes.COMPONENT */) {
  30102. return;
  30103. }
  30104. const component = resolveComponentType(node, context, true /* ssr */);
  30105. const isDynamicComponent = isObject$2(component) && component.callee === RESOLVE_DYNAMIC_COMPONENT;
  30106. componentTypeMap.set(node, component);
  30107. if (isSymbol$1(component)) {
  30108. if (component === SUSPENSE) {
  30109. return ssrTransformSuspense(node, context);
  30110. }
  30111. if (component === TRANSITION_GROUP) {
  30112. return ssrTransformTransitionGroup(node, context);
  30113. }
  30114. return; // other built-in components: fallthrough
  30115. }
  30116. // Build the fallback vnode-based branch for the component's slots.
  30117. // We need to clone the node into a fresh copy and use the buildSlots' logic
  30118. // to get access to the children of each slot. We then compile them with
  30119. // a child transform pipeline using vnode-based transforms (instead of ssr-
  30120. // based ones), and save the result branch (a ReturnStatement) in an array.
  30121. // The branch is retrieved when processing slots again in ssr mode.
  30122. const vnodeBranches = [];
  30123. const clonedNode = clone(node);
  30124. return function ssrPostTransformComponent() {
  30125. // Using the cloned node, build the normal VNode-based branches (for
  30126. // fallback in case the child is render-fn based). Store them in an array
  30127. // for later use.
  30128. if (clonedNode.children.length) {
  30129. buildSlots(clonedNode, context, (props, children) => {
  30130. vnodeBranches.push(createVNodeSlotBranch(props, children, context));
  30131. return createFunctionExpression(undefined);
  30132. });
  30133. }
  30134. let propsExp = `null`;
  30135. if (node.props.length) {
  30136. // note we are not passing ssr: true here because for components, v-on
  30137. // handlers should still be passed
  30138. const { props, directives } = buildProps(node, context, undefined, true, isDynamicComponent);
  30139. if (props || directives.length) {
  30140. propsExp = buildSSRProps(props, directives, context);
  30141. }
  30142. }
  30143. const wipEntries = [];
  30144. wipMap.set(node, wipEntries);
  30145. const buildSSRSlotFn = (props, children, loc) => {
  30146. const param0 = (props && stringifyExpression(props)) || `_`;
  30147. const fn = createFunctionExpression([param0, `_push`, `_parent`, `_scopeId`], undefined, // no return, assign body later
  30148. true, // newline
  30149. true, // isSlot
  30150. loc);
  30151. wipEntries.push({
  30152. type: WIP_SLOT,
  30153. fn,
  30154. children,
  30155. // also collect the corresponding vnode branch built earlier
  30156. vnodeBranch: vnodeBranches[wipEntries.length]
  30157. });
  30158. return fn;
  30159. };
  30160. const slots = node.children.length
  30161. ? buildSlots(node, context, buildSSRSlotFn).slots
  30162. : `null`;
  30163. if (typeof component !== 'string') {
  30164. // dynamic component that resolved to a `resolveDynamicComponent` call
  30165. // expression - since the resolved result may be a plain element (string)
  30166. // or a VNode, handle it with `renderVNode`.
  30167. node.ssrCodegenNode = createCallExpression(context.helper(SSR_RENDER_VNODE), [
  30168. `_push`,
  30169. createCallExpression(context.helper(CREATE_VNODE), [
  30170. component,
  30171. propsExp,
  30172. slots
  30173. ]),
  30174. `_parent`
  30175. ]);
  30176. }
  30177. else {
  30178. node.ssrCodegenNode = createCallExpression(context.helper(SSR_RENDER_COMPONENT), [component, propsExp, slots, `_parent`]);
  30179. }
  30180. };
  30181. };
  30182. function ssrProcessComponent(node, context, parent) {
  30183. const component = componentTypeMap.get(node);
  30184. if (!node.ssrCodegenNode) {
  30185. // this is a built-in component that fell-through.
  30186. if (component === TELEPORT) {
  30187. return ssrProcessTeleport(node, context);
  30188. }
  30189. else if (component === SUSPENSE) {
  30190. return ssrProcessSuspense(node, context);
  30191. }
  30192. else if (component === TRANSITION_GROUP) {
  30193. return ssrProcessTransitionGroup(node, context);
  30194. }
  30195. else {
  30196. // real fall-through: Transition / KeepAlive
  30197. // just render its children.
  30198. // #5352: if is at root level of a slot, push an empty string.
  30199. // this does not affect the final output, but avoids all-comment slot
  30200. // content of being treated as empty by ssrRenderSlot().
  30201. if (parent.type === WIP_SLOT) {
  30202. context.pushStringPart(``);
  30203. }
  30204. // #5351: filter out comment children inside transition
  30205. if (component === TRANSITION) {
  30206. node.children = node.children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */);
  30207. }
  30208. processChildren(node, context);
  30209. }
  30210. }
  30211. else {
  30212. // finish up slot function expressions from the 1st pass.
  30213. const wipEntries = wipMap.get(node) || [];
  30214. for (let i = 0; i < wipEntries.length; i++) {
  30215. const { fn, vnodeBranch } = wipEntries[i];
  30216. // For each slot, we generate two branches: one SSR-optimized branch and
  30217. // one normal vnode-based branch. The branches are taken based on the
  30218. // presence of the 2nd `_push` argument (which is only present if the slot
  30219. // is called by `_ssrRenderSlot`.
  30220. fn.body = createIfStatement(createSimpleExpression(`_push`, false), processChildrenAsStatement(wipEntries[i], context, false, true /* withSlotScopeId */), vnodeBranch);
  30221. }
  30222. // component is inside a slot, inherit slot scope Id
  30223. if (context.withSlotScopeId) {
  30224. node.ssrCodegenNode.arguments.push(`_scopeId`);
  30225. }
  30226. if (typeof component === 'string') {
  30227. // static component
  30228. context.pushStatement(createCallExpression(`_push`, [node.ssrCodegenNode]));
  30229. }
  30230. else {
  30231. // dynamic component (`resolveDynamicComponent` call)
  30232. // the codegen node is a `renderVNode` call
  30233. context.pushStatement(node.ssrCodegenNode);
  30234. }
  30235. }
  30236. }
  30237. const rawOptionsMap = new WeakMap();
  30238. const [baseNodeTransforms, baseDirectiveTransforms] = getBaseTransformPreset(true);
  30239. const vnodeNodeTransforms = [...baseNodeTransforms, ...DOMNodeTransforms];
  30240. const vnodeDirectiveTransforms = Object.assign(Object.assign({}, baseDirectiveTransforms), DOMDirectiveTransforms);
  30241. function createVNodeSlotBranch(props, children, parentContext) {
  30242. // apply a sub-transform using vnode-based transforms.
  30243. const rawOptions = rawOptionsMap.get(parentContext.root);
  30244. const subOptions = Object.assign(Object.assign({}, rawOptions), {
  30245. // overwrite with vnode-based transforms
  30246. nodeTransforms: [
  30247. ...vnodeNodeTransforms,
  30248. ...(rawOptions.nodeTransforms || [])
  30249. ], directiveTransforms: Object.assign(Object.assign({}, vnodeDirectiveTransforms), (rawOptions.directiveTransforms || {})) });
  30250. // wrap the children with a wrapper template for proper children treatment.
  30251. const wrapperNode = {
  30252. type: 1 /* NodeTypes.ELEMENT */,
  30253. ns: 0 /* Namespaces.HTML */,
  30254. tag: 'template',
  30255. tagType: 3 /* ElementTypes.TEMPLATE */,
  30256. isSelfClosing: false,
  30257. // important: provide v-slot="props" on the wrapper for proper
  30258. // scope analysis
  30259. props: [
  30260. {
  30261. type: 7 /* NodeTypes.DIRECTIVE */,
  30262. name: 'slot',
  30263. exp: props,
  30264. arg: undefined,
  30265. modifiers: [],
  30266. loc: locStub
  30267. }
  30268. ],
  30269. children,
  30270. loc: locStub,
  30271. codegenNode: undefined
  30272. };
  30273. subTransform(wrapperNode, subOptions, parentContext);
  30274. return createReturnStatement(children);
  30275. }
  30276. function subTransform(node, options, parentContext) {
  30277. const childRoot = createRoot([node]);
  30278. const childContext = createTransformContext(childRoot, options);
  30279. // this sub transform is for vnode fallback branch so it should be handled
  30280. // like normal render functions
  30281. childContext.ssr = false;
  30282. // inherit parent scope analysis state
  30283. childContext.scopes = Object.assign({}, parentContext.scopes);
  30284. childContext.identifiers = Object.assign({}, parentContext.identifiers);
  30285. childContext.imports = parentContext.imports;
  30286. // traverse
  30287. traverseNode(childRoot, childContext);
  30288. ['helpers', 'components', 'directives'].forEach(key => {
  30289. childContext[key].forEach((value, helperKey) => {
  30290. if (key === 'helpers') {
  30291. const parentCount = parentContext.helpers.get(helperKey);
  30292. if (parentCount === undefined) {
  30293. parentContext.helpers.set(helperKey, value);
  30294. }
  30295. else {
  30296. parentContext.helpers.set(helperKey, value + parentCount);
  30297. }
  30298. }
  30299. else {
  30300. parentContext[key].add(value);
  30301. }
  30302. });
  30303. });
  30304. // imports/hoists are not merged because:
  30305. // - imports are only used for asset urls and should be consistent between
  30306. // node/client branches
  30307. // - hoists are not enabled for the client branch here
  30308. }
  30309. function clone(v) {
  30310. if (isArray$3(v)) {
  30311. return v.map(clone);
  30312. }
  30313. else if (isObject$2(v)) {
  30314. const res = {};
  30315. for (const key in v) {
  30316. res[key] = clone(v[key]);
  30317. }
  30318. return res;
  30319. }
  30320. else {
  30321. return v;
  30322. }
  30323. }
  30324. // Because SSR codegen output is completely different from client-side output
  30325. // (e.g. multiple elements can be concatenated into a single template literal
  30326. // instead of each getting a corresponding call), we need to apply an extra
  30327. // transform pass to convert the template AST into a fresh JS AST before
  30328. // passing it to codegen.
  30329. function ssrCodegenTransform(ast, options) {
  30330. const context = createSSRTransformContext(ast, options);
  30331. // inject SFC <style> CSS variables
  30332. // we do this instead of inlining the expression to ensure the vars are
  30333. // only resolved once per render
  30334. if (options.ssrCssVars) {
  30335. const cssContext = createTransformContext(createRoot([]), options);
  30336. const varsExp = processExpression(createSimpleExpression(options.ssrCssVars, false), cssContext);
  30337. context.body.push(createCompoundExpression([`const _cssVars = { style: `, varsExp, `}`]));
  30338. Array.from(cssContext.helpers.keys()).forEach(helper => {
  30339. ast.helpers.add(helper);
  30340. });
  30341. }
  30342. const isFragment = ast.children.length > 1 && ast.children.some(c => !isText$1(c));
  30343. processChildren(ast, context, isFragment);
  30344. ast.codegenNode = createBlockStatement(context.body);
  30345. // Finalize helpers.
  30346. // We need to separate helpers imported from 'vue' vs. '@vue/server-renderer'
  30347. ast.ssrHelpers = Array.from(new Set([
  30348. ...Array.from(ast.helpers).filter(h => h in ssrHelpers),
  30349. ...context.helpers
  30350. ]));
  30351. ast.helpers = new Set(Array.from(ast.helpers).filter(h => !(h in ssrHelpers)));
  30352. }
  30353. function createSSRTransformContext(root, options, helpers = new Set(), withSlotScopeId = false) {
  30354. const body = [];
  30355. let currentString = null;
  30356. return {
  30357. root,
  30358. options,
  30359. body,
  30360. helpers,
  30361. withSlotScopeId,
  30362. onError: options.onError ||
  30363. (e => {
  30364. throw e;
  30365. }),
  30366. helper(name) {
  30367. helpers.add(name);
  30368. return name;
  30369. },
  30370. pushStringPart(part) {
  30371. if (!currentString) {
  30372. const currentCall = createCallExpression(`_push`);
  30373. body.push(currentCall);
  30374. currentString = createTemplateLiteral([]);
  30375. currentCall.arguments.push(currentString);
  30376. }
  30377. const bufferedElements = currentString.elements;
  30378. const lastItem = bufferedElements[bufferedElements.length - 1];
  30379. if (isString$2(part) && isString$2(lastItem)) {
  30380. bufferedElements[bufferedElements.length - 1] += part;
  30381. }
  30382. else {
  30383. bufferedElements.push(part);
  30384. }
  30385. },
  30386. pushStatement(statement) {
  30387. // close current string
  30388. currentString = null;
  30389. body.push(statement);
  30390. }
  30391. };
  30392. }
  30393. function createChildContext(parent, withSlotScopeId = parent.withSlotScopeId) {
  30394. // ensure child inherits parent helpers
  30395. return createSSRTransformContext(parent.root, parent.options, parent.helpers, withSlotScopeId);
  30396. }
  30397. function processChildren(parent, context, asFragment = false, disableNestedFragments = false) {
  30398. if (asFragment) {
  30399. context.pushStringPart(`<!--[-->`);
  30400. }
  30401. const { children } = parent;
  30402. for (let i = 0; i < children.length; i++) {
  30403. const child = children[i];
  30404. switch (child.type) {
  30405. case 1 /* NodeTypes.ELEMENT */:
  30406. switch (child.tagType) {
  30407. case 0 /* ElementTypes.ELEMENT */:
  30408. ssrProcessElement(child, context);
  30409. break;
  30410. case 1 /* ElementTypes.COMPONENT */:
  30411. ssrProcessComponent(child, context, parent);
  30412. break;
  30413. case 2 /* ElementTypes.SLOT */:
  30414. ssrProcessSlotOutlet(child, context);
  30415. break;
  30416. case 3 /* ElementTypes.TEMPLATE */:
  30417. // TODO
  30418. break;
  30419. default:
  30420. context.onError(createSSRCompilerError(64 /* SSRErrorCodes.X_SSR_INVALID_AST_NODE */, child.loc));
  30421. // make sure we exhaust all possible types
  30422. const exhaustiveCheck = child;
  30423. return exhaustiveCheck;
  30424. }
  30425. break;
  30426. case 2 /* NodeTypes.TEXT */:
  30427. context.pushStringPart(escapeHtml(child.content));
  30428. break;
  30429. case 3 /* NodeTypes.COMMENT */:
  30430. // no need to escape comment here because the AST can only
  30431. // contain valid comments.
  30432. context.pushStringPart(`<!--${child.content}-->`);
  30433. break;
  30434. case 5 /* NodeTypes.INTERPOLATION */:
  30435. context.pushStringPart(createCallExpression(context.helper(SSR_INTERPOLATE), [child.content]));
  30436. break;
  30437. case 9 /* NodeTypes.IF */:
  30438. ssrProcessIf(child, context, disableNestedFragments);
  30439. break;
  30440. case 11 /* NodeTypes.FOR */:
  30441. ssrProcessFor(child, context, disableNestedFragments);
  30442. break;
  30443. case 10 /* NodeTypes.IF_BRANCH */:
  30444. // no-op - handled by ssrProcessIf
  30445. break;
  30446. case 12 /* NodeTypes.TEXT_CALL */:
  30447. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  30448. // no-op - these two types can never appear as template child node since
  30449. // `transformText` is not used during SSR compile.
  30450. break;
  30451. default:
  30452. context.onError(createSSRCompilerError(64 /* SSRErrorCodes.X_SSR_INVALID_AST_NODE */, child.loc));
  30453. // make sure we exhaust all possible types
  30454. const exhaustiveCheck = child;
  30455. return exhaustiveCheck;
  30456. }
  30457. }
  30458. if (asFragment) {
  30459. context.pushStringPart(`<!--]-->`);
  30460. }
  30461. }
  30462. function processChildrenAsStatement(parent, parentContext, asFragment = false, withSlotScopeId = parentContext.withSlotScopeId) {
  30463. const childContext = createChildContext(parentContext, withSlotScopeId);
  30464. processChildren(parent, childContext, asFragment);
  30465. return createBlockStatement(childContext.body);
  30466. }
  30467. const ssrTransformModel = (dir, node, context) => {
  30468. const model = dir.exp;
  30469. function checkDuplicatedValue() {
  30470. const value = findProp(node, 'value');
  30471. if (value) {
  30472. context.onError(createDOMCompilerError(58 /* DOMErrorCodes.X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
  30473. }
  30474. }
  30475. if (node.tagType === 0 /* ElementTypes.ELEMENT */) {
  30476. const res = { props: [] };
  30477. const defaultProps = [
  30478. // default value binding for text type inputs
  30479. createObjectProperty(`value`, model)
  30480. ];
  30481. if (node.tag === 'input') {
  30482. const type = findProp(node, 'type');
  30483. if (type) {
  30484. const value = findValueBinding(node);
  30485. if (type.type === 7 /* NodeTypes.DIRECTIVE */) {
  30486. // dynamic type
  30487. res.ssrTagParts = [
  30488. createCallExpression(context.helper(SSR_RENDER_DYNAMIC_MODEL), [
  30489. type.exp,
  30490. model,
  30491. value
  30492. ])
  30493. ];
  30494. }
  30495. else if (type.value) {
  30496. // static type
  30497. switch (type.value.content) {
  30498. case 'radio':
  30499. res.props = [
  30500. createObjectProperty(`checked`, createCallExpression(context.helper(SSR_LOOSE_EQUAL), [
  30501. model,
  30502. value
  30503. ]))
  30504. ];
  30505. break;
  30506. case 'checkbox':
  30507. const trueValueBinding = findProp(node, 'true-value');
  30508. if (trueValueBinding) {
  30509. const trueValue = trueValueBinding.type === 6 /* NodeTypes.ATTRIBUTE */
  30510. ? JSON.stringify(trueValueBinding.value.content)
  30511. : trueValueBinding.exp;
  30512. res.props = [
  30513. createObjectProperty(`checked`, createCallExpression(context.helper(SSR_LOOSE_EQUAL), [
  30514. model,
  30515. trueValue
  30516. ]))
  30517. ];
  30518. }
  30519. else {
  30520. res.props = [
  30521. createObjectProperty(`checked`, createConditionalExpression(createCallExpression(`Array.isArray`, [model]), createCallExpression(context.helper(SSR_LOOSE_CONTAIN), [
  30522. model,
  30523. value
  30524. ]), model))
  30525. ];
  30526. }
  30527. break;
  30528. case 'file':
  30529. context.onError(createDOMCompilerError(57 /* DOMErrorCodes.X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
  30530. break;
  30531. default:
  30532. checkDuplicatedValue();
  30533. res.props = defaultProps;
  30534. break;
  30535. }
  30536. }
  30537. }
  30538. else if (hasDynamicKeyVBind(node)) ;
  30539. else {
  30540. // text type
  30541. checkDuplicatedValue();
  30542. res.props = defaultProps;
  30543. }
  30544. }
  30545. else if (node.tag === 'textarea') {
  30546. checkDuplicatedValue();
  30547. node.children = [createInterpolation(model, model.loc)];
  30548. }
  30549. else if (node.tag === 'select') ;
  30550. else {
  30551. context.onError(createDOMCompilerError(55 /* DOMErrorCodes.X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
  30552. }
  30553. return res;
  30554. }
  30555. else {
  30556. // component v-model
  30557. return transformModel$1(dir, node, context);
  30558. }
  30559. };
  30560. function findValueBinding(node) {
  30561. const valueBinding = findProp(node, 'value');
  30562. return valueBinding
  30563. ? valueBinding.type === 7 /* NodeTypes.DIRECTIVE */
  30564. ? valueBinding.exp
  30565. : createSimpleExpression(valueBinding.value.content, true)
  30566. : createSimpleExpression(`null`, false);
  30567. }
  30568. const ssrTransformShow = (dir, node, context) => {
  30569. if (!dir.exp) {
  30570. context.onError(createDOMCompilerError(59 /* DOMErrorCodes.X_V_SHOW_NO_EXPRESSION */));
  30571. }
  30572. return {
  30573. props: [
  30574. createObjectProperty(`style`, createConditionalExpression(dir.exp, createSimpleExpression(`null`, false), createObjectExpression([
  30575. createObjectProperty(`display`, createSimpleExpression(`none`, true))
  30576. ]), false /* no newline */))
  30577. ]
  30578. };
  30579. };
  30580. const filterChild = (node) => node.children.filter(n => n.type !== 3 /* NodeTypes.COMMENT */);
  30581. const hasSingleChild = (node) => filterChild(node).length === 1;
  30582. const ssrInjectFallthroughAttrs = (node, context) => {
  30583. // _attrs is provided as a function argument.
  30584. // mark it as a known identifier so that it doesn't get prefixed by
  30585. // transformExpression.
  30586. if (node.type === 0 /* NodeTypes.ROOT */) {
  30587. context.identifiers._attrs = 1;
  30588. }
  30589. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  30590. node.tagType === 1 /* ElementTypes.COMPONENT */ &&
  30591. (isBuiltInType(node.tag, 'Transition') ||
  30592. isBuiltInType(node.tag, 'KeepAlive'))) {
  30593. const rootChildren = filterChild(context.root);
  30594. if (rootChildren.length === 1 && rootChildren[0] === node) {
  30595. if (hasSingleChild(node)) {
  30596. injectFallthroughAttrs(node.children[0]);
  30597. }
  30598. return;
  30599. }
  30600. }
  30601. const parent = context.parent;
  30602. if (!parent || parent.type !== 0 /* NodeTypes.ROOT */) {
  30603. return;
  30604. }
  30605. if (node.type === 10 /* NodeTypes.IF_BRANCH */ && hasSingleChild(node)) {
  30606. // detect cases where the parent v-if is not the only root level node
  30607. let hasEncounteredIf = false;
  30608. for (const c of filterChild(parent)) {
  30609. if (c.type === 9 /* NodeTypes.IF */ ||
  30610. (c.type === 1 /* NodeTypes.ELEMENT */ && findDir(c, 'if'))) {
  30611. // multiple root v-if
  30612. if (hasEncounteredIf)
  30613. return;
  30614. hasEncounteredIf = true;
  30615. }
  30616. else if (
  30617. // node before v-if
  30618. !hasEncounteredIf ||
  30619. // non else nodes
  30620. !(c.type === 1 /* NodeTypes.ELEMENT */ && findDir(c, /else/, true))) {
  30621. return;
  30622. }
  30623. }
  30624. injectFallthroughAttrs(node.children[0]);
  30625. }
  30626. else if (hasSingleChild(parent)) {
  30627. injectFallthroughAttrs(node);
  30628. }
  30629. };
  30630. function injectFallthroughAttrs(node) {
  30631. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  30632. (node.tagType === 0 /* ElementTypes.ELEMENT */ ||
  30633. node.tagType === 1 /* ElementTypes.COMPONENT */) &&
  30634. !findDir(node, 'for')) {
  30635. node.props.push({
  30636. type: 7 /* NodeTypes.DIRECTIVE */,
  30637. name: 'bind',
  30638. arg: undefined,
  30639. exp: createSimpleExpression(`_attrs`, false),
  30640. modifiers: [],
  30641. loc: locStub
  30642. });
  30643. }
  30644. }
  30645. const ssrInjectCssVars = (node, context) => {
  30646. if (!context.ssrCssVars) {
  30647. return;
  30648. }
  30649. // _cssVars is initialized once per render function
  30650. // the code is injected in ssrCodegenTransform when creating the
  30651. // ssr transform context
  30652. if (node.type === 0 /* NodeTypes.ROOT */) {
  30653. context.identifiers._cssVars = 1;
  30654. }
  30655. const parent = context.parent;
  30656. if (!parent || parent.type !== 0 /* NodeTypes.ROOT */) {
  30657. return;
  30658. }
  30659. if (node.type === 10 /* NodeTypes.IF_BRANCH */) {
  30660. for (const child of node.children) {
  30661. injectCssVars(child);
  30662. }
  30663. }
  30664. else {
  30665. injectCssVars(node);
  30666. }
  30667. };
  30668. function injectCssVars(node) {
  30669. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  30670. (node.tagType === 0 /* ElementTypes.ELEMENT */ ||
  30671. node.tagType === 1 /* ElementTypes.COMPONENT */) &&
  30672. !findDir(node, 'for')) {
  30673. if (isBuiltInType(node.tag, 'Suspense')) {
  30674. for (const child of node.children) {
  30675. if (child.type === 1 /* NodeTypes.ELEMENT */ &&
  30676. child.tagType === 3 /* ElementTypes.TEMPLATE */) {
  30677. // suspense slot
  30678. child.children.forEach(injectCssVars);
  30679. }
  30680. else {
  30681. injectCssVars(child);
  30682. }
  30683. }
  30684. }
  30685. else {
  30686. node.props.push({
  30687. type: 7 /* NodeTypes.DIRECTIVE */,
  30688. name: 'bind',
  30689. arg: undefined,
  30690. exp: createSimpleExpression(`_cssVars`, false),
  30691. modifiers: [],
  30692. loc: locStub
  30693. });
  30694. }
  30695. }
  30696. }
  30697. function compile(template, options = {}) {
  30698. options = Object.assign(Object.assign(Object.assign({}, options), parserOptions), { ssr: true, inSSR: true, scopeId: options.mode === 'function' ? null : options.scopeId,
  30699. // always prefix since compiler-ssr doesn't have size concern
  30700. prefixIdentifiers: true,
  30701. // disable optimizations that are unnecessary for ssr
  30702. cacheHandlers: false, hoistStatic: false });
  30703. const ast = baseParse(template, options);
  30704. // Save raw options for AST. This is needed when performing sub-transforms
  30705. // on slot vnode branches.
  30706. rawOptionsMap.set(ast, options);
  30707. transform$1(ast, Object.assign(Object.assign({}, options), { hoistStatic: false, nodeTransforms: [
  30708. ssrTransformIf,
  30709. ssrTransformFor,
  30710. trackVForSlotScopes,
  30711. transformExpression,
  30712. ssrTransformSlotOutlet,
  30713. ssrInjectFallthroughAttrs,
  30714. ssrInjectCssVars,
  30715. ssrTransformElement,
  30716. ssrTransformComponent,
  30717. trackSlotScopes,
  30718. transformStyle,
  30719. ...(options.nodeTransforms || []) // user transforms
  30720. ], directiveTransforms: Object.assign({
  30721. // reusing core v-bind
  30722. bind: transformBind, on: transformOn$1,
  30723. // model and show has dedicated SSR handling
  30724. model: ssrTransformModel, show: ssrTransformShow,
  30725. // the following are ignored during SSR
  30726. // on: noopDirectiveTransform,
  30727. cloak: noopDirectiveTransform, once: noopDirectiveTransform, memo: noopDirectiveTransform }, (options.directiveTransforms || {}) // user transforms
  30728. ) }));
  30729. // traverse the template AST and convert into SSR codegen AST
  30730. // by replacing ast.codegenNode.
  30731. ssrCodegenTransform(ast, options);
  30732. return generate(ast, options);
  30733. }
  30734. var CompilerSSR = /*#__PURE__*/Object.freeze({
  30735. __proto__: null,
  30736. compile: compile
  30737. });
  30738. var _polyfillNode_fs = {};
  30739. var _polyfillNode_fs$1 = /*#__PURE__*/Object.freeze({
  30740. __proto__: null,
  30741. default: _polyfillNode_fs
  30742. });
  30743. var require$$0$2 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_fs$1);
  30744. var require$$2$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_path);
  30745. var require$$0$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_util$1);
  30746. const hasWarned$1 = {};
  30747. function warnOnce$4(msg) {
  30748. const isNodeProd = typeof process !== 'undefined' && process.env.NODE_ENV === 'production';
  30749. if (!isNodeProd && !false && !hasWarned$1[msg]) {
  30750. hasWarned$1[msg] = true;
  30751. warn$1(msg);
  30752. }
  30753. }
  30754. function warn$1(msg) {
  30755. console.warn(`\x1b[1m\x1b[33m[@vue/compiler-sfc]\x1b[0m\x1b[33m ${msg}\x1b[0m\n`);
  30756. }
  30757. function preprocess$1({ source, filename, preprocessOptions }, preprocessor) {
  30758. // Consolidate exposes a callback based API, but the callback is in fact
  30759. // called synchronously for most templating engines. In our case, we have to
  30760. // expose a synchronous API so that it is usable in Jest transforms (which
  30761. // have to be sync because they are applied via Node.js require hooks)
  30762. let res = '';
  30763. let err = null;
  30764. preprocessor.render(source, Object.assign({ filename }, preprocessOptions), (_err, _res) => {
  30765. if (_err)
  30766. err = _err;
  30767. res = _res;
  30768. });
  30769. if (err)
  30770. throw err;
  30771. return res;
  30772. }
  30773. function compileTemplate(options) {
  30774. const { preprocessLang, preprocessCustomRequire } = options;
  30775. if (preprocessLang &&
  30776. !preprocessCustomRequire) {
  30777. throw new Error(`[@vue/compiler-sfc] Template preprocessing in the browser build must ` +
  30778. `provide the \`preprocessCustomRequire\` option to return the in-browser ` +
  30779. `version of the preprocessor in the shape of { render(): string }.`);
  30780. }
  30781. const preprocessor = preprocessLang
  30782. ? preprocessCustomRequire
  30783. ? preprocessCustomRequire(preprocessLang)
  30784. : undefined
  30785. : false;
  30786. if (preprocessor) {
  30787. try {
  30788. return doCompileTemplate(Object.assign(Object.assign({}, options), { source: preprocess$1(options, preprocessor) }));
  30789. }
  30790. catch (e) {
  30791. return {
  30792. code: `export default function render() {}`,
  30793. source: options.source,
  30794. tips: [],
  30795. errors: [e]
  30796. };
  30797. }
  30798. }
  30799. else if (preprocessLang) {
  30800. return {
  30801. code: `export default function render() {}`,
  30802. source: options.source,
  30803. tips: [
  30804. `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
  30805. ],
  30806. errors: [
  30807. `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
  30808. ]
  30809. };
  30810. }
  30811. else {
  30812. return doCompileTemplate(options);
  30813. }
  30814. }
  30815. function doCompileTemplate({ filename, id, scoped, slotted, inMap, source, ssr = false, ssrCssVars, isProd = false, compiler = ssr ? CompilerSSR : CompilerDOM, compilerOptions = {}, transformAssetUrls }) {
  30816. const errors = [];
  30817. const warnings = [];
  30818. let nodeTransforms = [];
  30819. if (isObject$2(transformAssetUrls)) {
  30820. const assetOptions = normalizeOptions(transformAssetUrls);
  30821. nodeTransforms = [
  30822. createAssetUrlTransformWithOptions(assetOptions),
  30823. createSrcsetTransformWithOptions(assetOptions)
  30824. ];
  30825. }
  30826. else if (transformAssetUrls !== false) {
  30827. nodeTransforms = [transformAssetUrl, transformSrcset];
  30828. }
  30829. if (ssr && !ssrCssVars) {
  30830. warnOnce$4(`compileTemplate is called with \`ssr: true\` but no ` +
  30831. `corresponding \`cssVars\` option.\`.`);
  30832. }
  30833. if (!id) {
  30834. warnOnce$4(`compileTemplate now requires the \`id\` option.\`.`);
  30835. id = '';
  30836. }
  30837. const shortId = id.replace(/^data-v-/, '');
  30838. const longId = `data-v-${shortId}`;
  30839. let { code, ast, preamble, map } = compiler.compile(source, Object.assign(Object.assign({ mode: 'module', prefixIdentifiers: true, hoistStatic: true, cacheHandlers: true, ssrCssVars: ssr && ssrCssVars && ssrCssVars.length
  30840. ? genCssVarsFromList(ssrCssVars, shortId, isProd, true)
  30841. : '', scopeId: scoped ? longId : undefined, slotted, sourceMap: true }, compilerOptions), { nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []), filename, onError: e => errors.push(e), onWarn: w => warnings.push(w) }));
  30842. // inMap should be the map produced by ./parse.ts which is a simple line-only
  30843. // mapping. If it is present, we need to adjust the final map and errors to
  30844. // reflect the original line numbers.
  30845. if (inMap) {
  30846. if (map) {
  30847. map = mapLines(inMap, map);
  30848. }
  30849. if (errors.length) {
  30850. patchErrors(errors, source, inMap);
  30851. }
  30852. }
  30853. const tips = warnings.map(w => {
  30854. let msg = w.message;
  30855. if (w.loc) {
  30856. msg += `\n${generateCodeFrame(source, w.loc.start.offset, w.loc.end.offset)}`;
  30857. }
  30858. return msg;
  30859. });
  30860. return { code, ast, preamble, source, errors, tips, map };
  30861. }
  30862. function mapLines(oldMap, newMap) {
  30863. if (!oldMap)
  30864. return newMap;
  30865. if (!newMap)
  30866. return oldMap;
  30867. const oldMapConsumer = new SourceMapConsumer$5(oldMap);
  30868. const newMapConsumer = new SourceMapConsumer$5(newMap);
  30869. const mergedMapGenerator = new SourceMapGenerator$6();
  30870. newMapConsumer.eachMapping(m => {
  30871. if (m.originalLine == null) {
  30872. return;
  30873. }
  30874. const origPosInOldMap = oldMapConsumer.originalPositionFor({
  30875. line: m.originalLine,
  30876. column: m.originalColumn
  30877. });
  30878. if (origPosInOldMap.source == null) {
  30879. return;
  30880. }
  30881. mergedMapGenerator.addMapping({
  30882. generated: {
  30883. line: m.generatedLine,
  30884. column: m.generatedColumn
  30885. },
  30886. original: {
  30887. line: origPosInOldMap.line,
  30888. // use current column, since the oldMap produced by @vue/compiler-sfc
  30889. // does not
  30890. column: m.originalColumn
  30891. },
  30892. source: origPosInOldMap.source,
  30893. name: origPosInOldMap.name
  30894. });
  30895. });
  30896. // source-map's type definition is incomplete
  30897. const generator = mergedMapGenerator;
  30898. oldMapConsumer.sources.forEach((sourceFile) => {
  30899. generator._sources.add(sourceFile);
  30900. const sourceContent = oldMapConsumer.sourceContentFor(sourceFile);
  30901. if (sourceContent != null) {
  30902. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  30903. }
  30904. });
  30905. generator._sourceRoot = oldMap.sourceRoot;
  30906. generator._file = oldMap.file;
  30907. return generator.toJSON();
  30908. }
  30909. function patchErrors(errors, source, inMap) {
  30910. const originalSource = inMap.sourcesContent[0];
  30911. const offset = originalSource.indexOf(source);
  30912. const lineOffset = originalSource.slice(0, offset).split(/\r?\n/).length - 1;
  30913. errors.forEach(err => {
  30914. if (err.loc) {
  30915. err.loc.start.line += lineOffset;
  30916. err.loc.start.offset += offset;
  30917. if (err.loc.end !== err.loc.start) {
  30918. err.loc.end.line += lineOffset;
  30919. err.loc.end.offset += offset;
  30920. }
  30921. }
  30922. });
  30923. }
  30924. const defaultExportRE = /((?:^|\n|;)\s*)export(\s*)default/;
  30925. const namedDefaultExportRE = /((?:^|\n|;)\s*)export(.+)(?:as)?(\s*)default/s;
  30926. const exportDefaultClassRE = /((?:^|\n|;)\s*)export\s+default\s+class\s+([\w$]+)/;
  30927. /**
  30928. * Utility for rewriting `export default` in a script block into a variable
  30929. * declaration so that we can inject things into it
  30930. */
  30931. function rewriteDefault(input, as, parserPlugins) {
  30932. if (!hasDefaultExport(input)) {
  30933. return input + `\nconst ${as} = {}`;
  30934. }
  30935. let replaced;
  30936. const classMatch = input.match(exportDefaultClassRE);
  30937. if (classMatch) {
  30938. replaced =
  30939. input.replace(exportDefaultClassRE, '$1class $2') +
  30940. `\nconst ${as} = ${classMatch[2]}`;
  30941. }
  30942. else {
  30943. replaced = input.replace(defaultExportRE, `$1const ${as} =`);
  30944. }
  30945. if (!hasDefaultExport(replaced)) {
  30946. return replaced;
  30947. }
  30948. // if the script somehow still contains `default export`, it probably has
  30949. // multi-line comments or template strings. fallback to a full parse.
  30950. const s = new MagicString$1(input);
  30951. const ast = parse_1$1(input, {
  30952. sourceType: 'module',
  30953. plugins: parserPlugins
  30954. }).program.body;
  30955. ast.forEach(node => {
  30956. if (node.type === 'ExportDefaultDeclaration') {
  30957. if (node.declaration.type === 'ClassDeclaration') {
  30958. s.overwrite(node.start, node.declaration.id.start, `class `);
  30959. s.append(`\nconst ${as} = ${node.declaration.id.name}`);
  30960. }
  30961. else {
  30962. s.overwrite(node.start, node.declaration.start, `const ${as} = `);
  30963. }
  30964. }
  30965. if (node.type === 'ExportNamedDeclaration') {
  30966. for (const specifier of node.specifiers) {
  30967. if (specifier.type === 'ExportSpecifier' &&
  30968. specifier.exported.type === 'Identifier' &&
  30969. specifier.exported.name === 'default') {
  30970. if (node.source) {
  30971. if (specifier.local.name === 'default') {
  30972. const end = specifierEnd(input, specifier.local.end, node.end);
  30973. s.prepend(`import { default as __VUE_DEFAULT__ } from '${node.source.value}'\n`);
  30974. s.overwrite(specifier.start, end, ``);
  30975. s.append(`\nconst ${as} = __VUE_DEFAULT__`);
  30976. continue;
  30977. }
  30978. else {
  30979. const end = specifierEnd(input, specifier.exported.end, node.end);
  30980. s.prepend(`import { ${input.slice(specifier.local.start, specifier.local.end)} } from '${node.source.value}'\n`);
  30981. s.overwrite(specifier.start, end, ``);
  30982. s.append(`\nconst ${as} = ${specifier.local.name}`);
  30983. continue;
  30984. }
  30985. }
  30986. const end = specifierEnd(input, specifier.end, node.end);
  30987. s.overwrite(specifier.start, end, ``);
  30988. s.append(`\nconst ${as} = ${specifier.local.name}`);
  30989. }
  30990. }
  30991. }
  30992. });
  30993. return s.toString();
  30994. }
  30995. function hasDefaultExport(input) {
  30996. return defaultExportRE.test(input) || namedDefaultExportRE.test(input);
  30997. }
  30998. function specifierEnd(input, end, nodeEnd) {
  30999. // export { default , foo } ...
  31000. let hasCommas = false;
  31001. let oldEnd = end;
  31002. while (end < nodeEnd) {
  31003. if (/\s/.test(input.charAt(end))) {
  31004. end++;
  31005. }
  31006. else if (input.charAt(end) === ',') {
  31007. end++;
  31008. hasCommas = true;
  31009. break;
  31010. }
  31011. else if (input.charAt(end) === '}') {
  31012. break;
  31013. }
  31014. }
  31015. return hasCommas ? end : oldEnd;
  31016. }
  31017. const CONVERT_SYMBOL = '$';
  31018. const ESCAPE_SYMBOL = '$$';
  31019. const IMPORT_SOURCE = 'vue/macros';
  31020. const shorthands = ['ref', 'computed', 'shallowRef', 'toRef', 'customRef'];
  31021. const transformCheckRE = /[^\w]\$(?:\$|ref|computed|shallowRef)?\s*(\(|\<)/;
  31022. function shouldTransform(src) {
  31023. return transformCheckRE.test(src);
  31024. }
  31025. function transform(src, { filename, sourceMap, parserPlugins, importHelpersFrom = 'vue' } = {}) {
  31026. const plugins = parserPlugins || [];
  31027. if (filename) {
  31028. if (/\.tsx?$/.test(filename)) {
  31029. plugins.push('typescript');
  31030. }
  31031. if (filename.endsWith('x')) {
  31032. plugins.push('jsx');
  31033. }
  31034. }
  31035. const ast = parse_1$1(src, {
  31036. sourceType: 'module',
  31037. plugins
  31038. });
  31039. const s = new MagicString$1(src);
  31040. const res = transformAST(ast.program, s, 0);
  31041. // inject helper imports
  31042. if (res.importedHelpers.length) {
  31043. s.prepend(`import { ${res.importedHelpers
  31044. .map(h => `${h} as _${h}`)
  31045. .join(', ')} } from '${importHelpersFrom}'\n`);
  31046. }
  31047. return Object.assign(Object.assign({}, res), { code: s.toString(), map: sourceMap
  31048. ? s.generateMap({
  31049. source: filename,
  31050. hires: true,
  31051. includeContent: true
  31052. })
  31053. : null });
  31054. }
  31055. function transformAST(ast, s, offset = 0, knownRefs, knownProps) {
  31056. // TODO remove when out of experimental
  31057. warnExperimental();
  31058. const userImports = Object.create(null);
  31059. for (const node of ast.body) {
  31060. if (node.type !== 'ImportDeclaration')
  31061. continue;
  31062. walkImportDeclaration(node);
  31063. }
  31064. // macro import handling
  31065. let convertSymbol;
  31066. let escapeSymbol;
  31067. for (const { local, imported, source, specifier } of Object.values(userImports)) {
  31068. if (source === IMPORT_SOURCE) {
  31069. if (imported === ESCAPE_SYMBOL) {
  31070. escapeSymbol = local;
  31071. }
  31072. else if (imported === CONVERT_SYMBOL) {
  31073. convertSymbol = local;
  31074. }
  31075. else if (imported !== local) {
  31076. error(`macro imports for ref-creating methods do not support aliasing.`, specifier);
  31077. }
  31078. }
  31079. }
  31080. // default symbol
  31081. if (!convertSymbol && !userImports[CONVERT_SYMBOL]) {
  31082. convertSymbol = CONVERT_SYMBOL;
  31083. }
  31084. if (!escapeSymbol && !userImports[ESCAPE_SYMBOL]) {
  31085. escapeSymbol = ESCAPE_SYMBOL;
  31086. }
  31087. const importedHelpers = new Set();
  31088. const rootScope = {};
  31089. const scopeStack = [rootScope];
  31090. let currentScope = rootScope;
  31091. let escapeScope; // inside $$()
  31092. const excludedIds = new WeakSet();
  31093. const parentStack = [];
  31094. const propsLocalToPublicMap = Object.create(null);
  31095. if (knownRefs) {
  31096. for (const key of knownRefs) {
  31097. rootScope[key] = {};
  31098. }
  31099. }
  31100. if (knownProps) {
  31101. for (const key in knownProps) {
  31102. const { local, isConst } = knownProps[key];
  31103. rootScope[local] = {
  31104. isProp: true,
  31105. isConst: !!isConst
  31106. };
  31107. propsLocalToPublicMap[local] = key;
  31108. }
  31109. }
  31110. function walkImportDeclaration(node) {
  31111. const source = node.source.value;
  31112. if (source === IMPORT_SOURCE) {
  31113. s.remove(node.start + offset, node.end + offset);
  31114. }
  31115. for (const specifier of node.specifiers) {
  31116. const local = specifier.local.name;
  31117. const imported = (specifier.type === 'ImportSpecifier' &&
  31118. specifier.imported.type === 'Identifier' &&
  31119. specifier.imported.name) ||
  31120. 'default';
  31121. userImports[local] = {
  31122. source,
  31123. local,
  31124. imported,
  31125. specifier
  31126. };
  31127. }
  31128. }
  31129. function isRefCreationCall(callee) {
  31130. if (!convertSymbol || currentScope[convertSymbol] !== undefined) {
  31131. return false;
  31132. }
  31133. if (callee === convertSymbol) {
  31134. return convertSymbol;
  31135. }
  31136. if (callee[0] === '$' && shorthands.includes(callee.slice(1))) {
  31137. return callee;
  31138. }
  31139. return false;
  31140. }
  31141. function error(msg, node) {
  31142. const e = new Error(msg);
  31143. e.node = node;
  31144. throw e;
  31145. }
  31146. function helper(msg) {
  31147. importedHelpers.add(msg);
  31148. return `_${msg}`;
  31149. }
  31150. function registerBinding(id, binding) {
  31151. excludedIds.add(id);
  31152. if (currentScope) {
  31153. currentScope[id.name] = binding ? binding : false;
  31154. }
  31155. else {
  31156. error('registerBinding called without active scope, something is wrong.', id);
  31157. }
  31158. }
  31159. const registerRefBinding = (id, isConst = false) => registerBinding(id, { isConst });
  31160. let tempVarCount = 0;
  31161. function genTempVar() {
  31162. return `__$temp_${++tempVarCount}`;
  31163. }
  31164. function snip(node) {
  31165. return s.original.slice(node.start + offset, node.end + offset);
  31166. }
  31167. function walkScope(node, isRoot = false) {
  31168. for (const stmt of node.body) {
  31169. if (stmt.type === 'VariableDeclaration') {
  31170. walkVariableDeclaration(stmt, isRoot);
  31171. }
  31172. else if (stmt.type === 'FunctionDeclaration' ||
  31173. stmt.type === 'ClassDeclaration') {
  31174. if (stmt.declare || !stmt.id)
  31175. continue;
  31176. registerBinding(stmt.id);
  31177. }
  31178. else if ((stmt.type === 'ForOfStatement' || stmt.type === 'ForInStatement') &&
  31179. stmt.left.type === 'VariableDeclaration') {
  31180. walkVariableDeclaration(stmt.left);
  31181. }
  31182. else if (stmt.type === 'ExportNamedDeclaration' &&
  31183. stmt.declaration &&
  31184. stmt.declaration.type === 'VariableDeclaration') {
  31185. walkVariableDeclaration(stmt.declaration, isRoot);
  31186. }
  31187. else if (stmt.type === 'LabeledStatement' &&
  31188. stmt.body.type === 'VariableDeclaration') {
  31189. walkVariableDeclaration(stmt.body, isRoot);
  31190. }
  31191. }
  31192. }
  31193. function walkVariableDeclaration(stmt, isRoot = false) {
  31194. if (stmt.declare) {
  31195. return;
  31196. }
  31197. for (const decl of stmt.declarations) {
  31198. let refCall;
  31199. const isCall = decl.init &&
  31200. decl.init.type === 'CallExpression' &&
  31201. decl.init.callee.type === 'Identifier';
  31202. if (isCall &&
  31203. (refCall = isRefCreationCall(decl.init.callee.name))) {
  31204. processRefDeclaration(refCall, decl.id, decl.init, stmt.kind === 'const');
  31205. }
  31206. else {
  31207. const isProps = isRoot && isCall && decl.init.callee.name === 'defineProps';
  31208. for (const id of extractIdentifiers(decl.id)) {
  31209. if (isProps) {
  31210. // for defineProps destructure, only exclude them since they
  31211. // are already passed in as knownProps
  31212. excludedIds.add(id);
  31213. }
  31214. else {
  31215. registerBinding(id);
  31216. }
  31217. }
  31218. }
  31219. }
  31220. }
  31221. function processRefDeclaration(method, id, call, isConst) {
  31222. excludedIds.add(call.callee);
  31223. if (method === convertSymbol) {
  31224. // $
  31225. // remove macro
  31226. s.remove(call.callee.start + offset, call.callee.end + offset);
  31227. if (id.type === 'Identifier') {
  31228. // single variable
  31229. registerRefBinding(id, isConst);
  31230. }
  31231. else if (id.type === 'ObjectPattern') {
  31232. processRefObjectPattern(id, call, isConst);
  31233. }
  31234. else if (id.type === 'ArrayPattern') {
  31235. processRefArrayPattern(id, call, isConst);
  31236. }
  31237. }
  31238. else {
  31239. // shorthands
  31240. if (id.type === 'Identifier') {
  31241. registerRefBinding(id, isConst);
  31242. // replace call
  31243. s.overwrite(call.start + offset, call.start + method.length + offset, helper(method.slice(1)));
  31244. }
  31245. else {
  31246. error(`${method}() cannot be used with destructure patterns.`, call);
  31247. }
  31248. }
  31249. }
  31250. function processRefObjectPattern(pattern, call, isConst, tempVar, path = []) {
  31251. if (!tempVar) {
  31252. tempVar = genTempVar();
  31253. // const { x } = $(useFoo()) --> const __$temp_1 = useFoo()
  31254. s.overwrite(pattern.start + offset, pattern.end + offset, tempVar);
  31255. }
  31256. let nameId;
  31257. for (const p of pattern.properties) {
  31258. let key;
  31259. let defaultValue;
  31260. if (p.type === 'ObjectProperty') {
  31261. if (p.key.start === p.value.start) {
  31262. // shorthand { foo }
  31263. nameId = p.key;
  31264. if (p.value.type === 'Identifier') {
  31265. // avoid shorthand value identifier from being processed
  31266. excludedIds.add(p.value);
  31267. }
  31268. else if (p.value.type === 'AssignmentPattern' &&
  31269. p.value.left.type === 'Identifier') {
  31270. // { foo = 1 }
  31271. excludedIds.add(p.value.left);
  31272. defaultValue = p.value.right;
  31273. }
  31274. }
  31275. else {
  31276. key = p.computed ? p.key : p.key.name;
  31277. if (p.value.type === 'Identifier') {
  31278. // { foo: bar }
  31279. nameId = p.value;
  31280. }
  31281. else if (p.value.type === 'ObjectPattern') {
  31282. processRefObjectPattern(p.value, call, isConst, tempVar, [
  31283. ...path,
  31284. key
  31285. ]);
  31286. }
  31287. else if (p.value.type === 'ArrayPattern') {
  31288. processRefArrayPattern(p.value, call, isConst, tempVar, [
  31289. ...path,
  31290. key
  31291. ]);
  31292. }
  31293. else if (p.value.type === 'AssignmentPattern') {
  31294. if (p.value.left.type === 'Identifier') {
  31295. // { foo: bar = 1 }
  31296. nameId = p.value.left;
  31297. defaultValue = p.value.right;
  31298. }
  31299. else if (p.value.left.type === 'ObjectPattern') {
  31300. processRefObjectPattern(p.value.left, call, isConst, tempVar, [
  31301. ...path,
  31302. [key, p.value.right]
  31303. ]);
  31304. }
  31305. else if (p.value.left.type === 'ArrayPattern') {
  31306. processRefArrayPattern(p.value.left, call, isConst, tempVar, [
  31307. ...path,
  31308. [key, p.value.right]
  31309. ]);
  31310. }
  31311. else ;
  31312. }
  31313. }
  31314. }
  31315. else {
  31316. // rest element { ...foo }
  31317. error(`reactivity destructure does not support rest elements.`, p);
  31318. }
  31319. if (nameId) {
  31320. registerRefBinding(nameId, isConst);
  31321. // inject toRef() after original replaced pattern
  31322. const source = pathToString(tempVar, path);
  31323. const keyStr = isString$2(key)
  31324. ? `'${key}'`
  31325. : key
  31326. ? snip(key)
  31327. : `'${nameId.name}'`;
  31328. const defaultStr = defaultValue ? `, ${snip(defaultValue)}` : ``;
  31329. s.appendLeft(call.end + offset, `,\n ${nameId.name} = ${helper('toRef')}(${source}, ${keyStr}${defaultStr})`);
  31330. }
  31331. }
  31332. if (nameId) {
  31333. s.appendLeft(call.end + offset, ';');
  31334. }
  31335. }
  31336. function processRefArrayPattern(pattern, call, isConst, tempVar, path = []) {
  31337. if (!tempVar) {
  31338. // const [x] = $(useFoo()) --> const __$temp_1 = useFoo()
  31339. tempVar = genTempVar();
  31340. s.overwrite(pattern.start + offset, pattern.end + offset, tempVar);
  31341. }
  31342. let nameId;
  31343. for (let i = 0; i < pattern.elements.length; i++) {
  31344. const e = pattern.elements[i];
  31345. if (!e)
  31346. continue;
  31347. let defaultValue;
  31348. if (e.type === 'Identifier') {
  31349. // [a] --> [__a]
  31350. nameId = e;
  31351. }
  31352. else if (e.type === 'AssignmentPattern') {
  31353. // [a = 1]
  31354. nameId = e.left;
  31355. defaultValue = e.right;
  31356. }
  31357. else if (e.type === 'RestElement') {
  31358. // [...a]
  31359. error(`reactivity destructure does not support rest elements.`, e);
  31360. }
  31361. else if (e.type === 'ObjectPattern') {
  31362. processRefObjectPattern(e, call, isConst, tempVar, [...path, i]);
  31363. }
  31364. else if (e.type === 'ArrayPattern') {
  31365. processRefArrayPattern(e, call, isConst, tempVar, [...path, i]);
  31366. }
  31367. if (nameId) {
  31368. registerRefBinding(nameId, isConst);
  31369. // inject toRef() after original replaced pattern
  31370. const source = pathToString(tempVar, path);
  31371. const defaultStr = defaultValue ? `, ${snip(defaultValue)}` : ``;
  31372. s.appendLeft(call.end + offset, `,\n ${nameId.name} = ${helper('toRef')}(${source}, ${i}${defaultStr})`);
  31373. }
  31374. }
  31375. if (nameId) {
  31376. s.appendLeft(call.end + offset, ';');
  31377. }
  31378. }
  31379. function pathToString(source, path) {
  31380. if (path.length) {
  31381. for (const seg of path) {
  31382. if (isArray$3(seg)) {
  31383. source = `(${source}${segToString(seg[0])} || ${snip(seg[1])})`;
  31384. }
  31385. else {
  31386. source += segToString(seg);
  31387. }
  31388. }
  31389. }
  31390. return source;
  31391. }
  31392. function segToString(seg) {
  31393. if (typeof seg === 'number') {
  31394. return `[${seg}]`;
  31395. }
  31396. else if (typeof seg === 'string') {
  31397. return `.${seg}`;
  31398. }
  31399. else {
  31400. return snip(seg);
  31401. }
  31402. }
  31403. function rewriteId(scope, id, parent, parentStack) {
  31404. if (hasOwn(scope, id.name)) {
  31405. const binding = scope[id.name];
  31406. if (binding) {
  31407. if (binding.isConst &&
  31408. ((parent.type === 'AssignmentExpression' && id === parent.left) ||
  31409. parent.type === 'UpdateExpression')) {
  31410. error(`Assignment to constant variable.`, id);
  31411. }
  31412. const { isProp } = binding;
  31413. if (isStaticProperty(parent) && parent.shorthand) {
  31414. // let binding used in a property shorthand
  31415. // skip for destructure patterns
  31416. if (!parent.inPattern ||
  31417. isInDestructureAssignment(parent, parentStack)) {
  31418. if (isProp) {
  31419. if (escapeScope) {
  31420. // prop binding in $$()
  31421. // { prop } -> { prop: __props_prop }
  31422. registerEscapedPropBinding(id);
  31423. s.appendLeft(id.end + offset, `: __props_${propsLocalToPublicMap[id.name]}`);
  31424. }
  31425. else {
  31426. // { prop } -> { prop: __props.prop }
  31427. s.appendLeft(id.end + offset, `: ${genPropsAccessExp(propsLocalToPublicMap[id.name])}`);
  31428. }
  31429. }
  31430. else {
  31431. // { foo } -> { foo: foo.value }
  31432. s.appendLeft(id.end + offset, `: ${id.name}.value`);
  31433. }
  31434. }
  31435. }
  31436. else {
  31437. if (isProp) {
  31438. if (escapeScope) {
  31439. // x --> __props_x
  31440. registerEscapedPropBinding(id);
  31441. s.overwrite(id.start + offset, id.end + offset, `__props_${propsLocalToPublicMap[id.name]}`);
  31442. }
  31443. else {
  31444. // x --> __props.x
  31445. s.overwrite(id.start + offset, id.end + offset, genPropsAccessExp(propsLocalToPublicMap[id.name]));
  31446. }
  31447. }
  31448. else {
  31449. // x --> x.value
  31450. s.appendLeft(id.end + offset, '.value');
  31451. }
  31452. }
  31453. }
  31454. return true;
  31455. }
  31456. return false;
  31457. }
  31458. const propBindingRefs = {};
  31459. function registerEscapedPropBinding(id) {
  31460. if (!propBindingRefs.hasOwnProperty(id.name)) {
  31461. propBindingRefs[id.name] = true;
  31462. const publicKey = propsLocalToPublicMap[id.name];
  31463. s.prependRight(offset, `const __props_${publicKey} = ${helper(`toRef`)}(__props, '${publicKey}');\n`);
  31464. }
  31465. }
  31466. // check root scope first
  31467. walkScope(ast, true);
  31468. walk$1(ast, {
  31469. enter(node, parent) {
  31470. parent && parentStack.push(parent);
  31471. // function scopes
  31472. if (isFunctionType(node)) {
  31473. scopeStack.push((currentScope = {}));
  31474. walkFunctionParams(node, registerBinding);
  31475. if (node.body.type === 'BlockStatement') {
  31476. walkScope(node.body);
  31477. }
  31478. return;
  31479. }
  31480. // catch param
  31481. if (node.type === 'CatchClause') {
  31482. scopeStack.push((currentScope = {}));
  31483. if (node.param && node.param.type === 'Identifier') {
  31484. registerBinding(node.param);
  31485. }
  31486. walkScope(node.body);
  31487. return;
  31488. }
  31489. // non-function block scopes
  31490. if (node.type === 'BlockStatement' && !isFunctionType(parent)) {
  31491. scopeStack.push((currentScope = {}));
  31492. walkScope(node);
  31493. return;
  31494. }
  31495. // skip type nodes
  31496. if (parent &&
  31497. parent.type.startsWith('TS') &&
  31498. parent.type !== 'TSAsExpression' &&
  31499. parent.type !== 'TSNonNullExpression' &&
  31500. parent.type !== 'TSTypeAssertion') {
  31501. return this.skip();
  31502. }
  31503. if (node.type === 'Identifier') {
  31504. const binding = rootScope[node.name];
  31505. if (
  31506. // if inside $$(), skip unless this is a destructured prop binding
  31507. !(escapeScope && (!binding || !binding.isProp)) &&
  31508. isReferencedIdentifier(node, parent, parentStack) &&
  31509. !excludedIds.has(node)) {
  31510. // walk up the scope chain to check if id should be appended .value
  31511. let i = scopeStack.length;
  31512. while (i--) {
  31513. if (rewriteId(scopeStack[i], node, parent, parentStack)) {
  31514. return;
  31515. }
  31516. }
  31517. }
  31518. }
  31519. if (node.type === 'CallExpression' && node.callee.type === 'Identifier') {
  31520. const callee = node.callee.name;
  31521. const refCall = isRefCreationCall(callee);
  31522. if (refCall && (!parent || parent.type !== 'VariableDeclarator')) {
  31523. return error(`${refCall} can only be used as the initializer of ` +
  31524. `a variable declaration.`, node);
  31525. }
  31526. if (escapeSymbol &&
  31527. currentScope[escapeSymbol] === undefined &&
  31528. callee === escapeSymbol) {
  31529. escapeScope = node;
  31530. s.remove(node.callee.start + offset, node.callee.end + offset);
  31531. if ((parent === null || parent === void 0 ? void 0 : parent.type) === 'ExpressionStatement') {
  31532. // edge case where the call expression is an expression statement
  31533. // if its own - prepend semicolon to avoid it being parsed as
  31534. // function invocation of previous line
  31535. let i = (node.leadingComments
  31536. ? node.leadingComments[0].start
  31537. : node.start) + offset;
  31538. while (i--) {
  31539. const char = s.original.charAt(i);
  31540. if (char === '\n') {
  31541. // only insert semi if it's actually the fisrt thign after
  31542. // newline
  31543. s.prependRight(node.start + offset, ';');
  31544. break;
  31545. }
  31546. else if (!/\s/.test(char)) {
  31547. break;
  31548. }
  31549. }
  31550. }
  31551. }
  31552. // TODO remove when out of experimental
  31553. if (callee === '$raw') {
  31554. error(`$raw() has been replaced by $$(). ` +
  31555. `See ${RFC_LINK} for latest updates.`, node);
  31556. }
  31557. if (callee === '$fromRef') {
  31558. error(`$fromRef() has been replaced by $(). ` +
  31559. `See ${RFC_LINK} for latest updates.`, node);
  31560. }
  31561. }
  31562. },
  31563. leave(node, parent) {
  31564. parent && parentStack.pop();
  31565. if ((node.type === 'BlockStatement' && !isFunctionType(parent)) ||
  31566. isFunctionType(node)) {
  31567. scopeStack.pop();
  31568. currentScope = scopeStack[scopeStack.length - 1] || null;
  31569. }
  31570. if (node === escapeScope) {
  31571. escapeScope = undefined;
  31572. }
  31573. }
  31574. });
  31575. return {
  31576. rootRefs: Object.keys(rootScope).filter(key => {
  31577. const binding = rootScope[key];
  31578. return binding && !binding.isProp;
  31579. }),
  31580. importedHelpers: [...importedHelpers]
  31581. };
  31582. }
  31583. const RFC_LINK = `https://github.com/vuejs/rfcs/discussions/369`;
  31584. const hasWarned = {};
  31585. function warnExperimental() {
  31586. // eslint-disable-next-line
  31587. if (typeof window !== 'undefined') {
  31588. return;
  31589. }
  31590. warnOnce$3(`Reactivity transform is an experimental feature.\n` +
  31591. `Experimental features may change behavior between patch versions.\n` +
  31592. `It is recommended to pin your vue dependencies to exact versions to avoid breakage.\n` +
  31593. `You can follow the proposal's status at ${RFC_LINK}.`);
  31594. }
  31595. function warnOnce$3(msg) {
  31596. const isNodeProd = typeof process !== 'undefined' && process.env.NODE_ENV === 'production';
  31597. if (!isNodeProd && !false && !hasWarned[msg]) {
  31598. hasWarned[msg] = true;
  31599. warn(msg);
  31600. }
  31601. }
  31602. function warn(msg) {
  31603. console.warn(`\x1b[1m\x1b[33m[@vue/reactivity-transform]\x1b[0m\x1b[33m ${msg}\x1b[0m\n`);
  31604. }
  31605. // Special compiler macros
  31606. const DEFINE_PROPS = 'defineProps';
  31607. const DEFINE_EMITS = 'defineEmits';
  31608. const DEFINE_EXPOSE = 'defineExpose';
  31609. const WITH_DEFAULTS = 'withDefaults';
  31610. // constants
  31611. const DEFAULT_VAR = `__default__`;
  31612. const isBuiltInDir = makeMap(`once,memo,if,for,else,else-if,slot,text,html,on,bind,model,show,cloak,is`);
  31613. /**
  31614. * Compile `<script setup>`
  31615. * It requires the whole SFC descriptor because we need to handle and merge
  31616. * normal `<script>` + `<script setup>` if both are present.
  31617. */
  31618. function compileScript(sfc, options) {
  31619. var _a;
  31620. let { script, scriptSetup, source, filename } = sfc;
  31621. // feature flags
  31622. // TODO remove support for deprecated options when out of experimental
  31623. const enableReactivityTransform = !!options.reactivityTransform ||
  31624. !!options.refSugar ||
  31625. !!options.refTransform;
  31626. const enablePropsTransform = !!options.reactivityTransform || !!options.propsDestructureTransform;
  31627. const isProd = !!options.isProd;
  31628. const genSourceMap = options.sourceMap !== false;
  31629. let refBindings;
  31630. if (!options.id) {
  31631. warnOnce$4(`compileScript now requires passing the \`id\` option.\n` +
  31632. `Upgrade your vite or vue-loader version for compatibility with ` +
  31633. `the latest experimental proposals.`);
  31634. }
  31635. const scopeId = options.id ? options.id.replace(/^data-v-/, '') : '';
  31636. const cssVars = sfc.cssVars;
  31637. const scriptLang = script && script.lang;
  31638. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  31639. const isTS = scriptLang === 'ts' ||
  31640. scriptLang === 'tsx' ||
  31641. scriptSetupLang === 'ts' ||
  31642. scriptSetupLang === 'tsx';
  31643. // resolve parser plugins
  31644. const plugins = [];
  31645. if (!isTS || scriptLang === 'tsx' || scriptSetupLang === 'tsx') {
  31646. plugins.push('jsx');
  31647. }
  31648. else {
  31649. // If don't match the case of adding jsx, should remove the jsx from the babelParserPlugins
  31650. if (options.babelParserPlugins)
  31651. options.babelParserPlugins = options.babelParserPlugins.filter(n => n !== 'jsx');
  31652. }
  31653. if (options.babelParserPlugins)
  31654. plugins.push(...options.babelParserPlugins);
  31655. if (isTS) {
  31656. plugins.push('typescript');
  31657. if (!plugins.includes('decorators')) {
  31658. plugins.push('decorators-legacy');
  31659. }
  31660. }
  31661. if (!scriptSetup) {
  31662. if (!script) {
  31663. throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`);
  31664. }
  31665. if (scriptLang && !isTS && scriptLang !== 'jsx') {
  31666. // do not process non js/ts script blocks
  31667. return script;
  31668. }
  31669. try {
  31670. let content = script.content;
  31671. let map = script.map;
  31672. const scriptAst = parse_1$1(content, {
  31673. plugins,
  31674. sourceType: 'module'
  31675. }).program;
  31676. const bindings = analyzeScriptBindings(scriptAst.body);
  31677. if (enableReactivityTransform && shouldTransform(content)) {
  31678. const s = new MagicString$1(source);
  31679. const startOffset = script.loc.start.offset;
  31680. const endOffset = script.loc.end.offset;
  31681. const { importedHelpers } = transformAST(scriptAst, s, startOffset);
  31682. if (importedHelpers.length) {
  31683. s.prepend(`import { ${importedHelpers
  31684. .map(h => `${h} as _${h}`)
  31685. .join(', ')} } from 'vue'\n`);
  31686. }
  31687. s.remove(0, startOffset);
  31688. s.remove(endOffset, source.length);
  31689. content = s.toString();
  31690. if (genSourceMap) {
  31691. map = s.generateMap({
  31692. source: filename,
  31693. hires: true,
  31694. includeContent: true
  31695. });
  31696. }
  31697. }
  31698. if (cssVars.length) {
  31699. content = rewriteDefault(content, DEFAULT_VAR, plugins);
  31700. content += genNormalScriptCssVarsCode(cssVars, bindings, scopeId, isProd);
  31701. content += `\nexport default ${DEFAULT_VAR}`;
  31702. }
  31703. return Object.assign(Object.assign({}, script), { content,
  31704. map,
  31705. bindings, scriptAst: scriptAst.body });
  31706. }
  31707. catch (e) {
  31708. // silently fallback if parse fails since user may be using custom
  31709. // babel syntax
  31710. return script;
  31711. }
  31712. }
  31713. if (script && scriptLang !== scriptSetupLang) {
  31714. throw new Error(`[@vue/compiler-sfc] <script> and <script setup> must have the same ` +
  31715. `language type.`);
  31716. }
  31717. if (scriptSetupLang && !isTS && scriptSetupLang !== 'jsx') {
  31718. // do not process non js/ts script blocks
  31719. return scriptSetup;
  31720. }
  31721. // metadata that needs to be returned
  31722. const bindingMetadata = {};
  31723. const helperImports = new Set();
  31724. const userImports = Object.create(null);
  31725. const scriptBindings = Object.create(null);
  31726. const setupBindings = Object.create(null);
  31727. let defaultExport;
  31728. let hasDefinePropsCall = false;
  31729. let hasDefineEmitCall = false;
  31730. let hasDefineExposeCall = false;
  31731. let hasDefaultExportName = false;
  31732. let hasDefaultExportRender = false;
  31733. let propsRuntimeDecl;
  31734. let propsRuntimeDefaults;
  31735. let propsDestructureDecl;
  31736. let propsDestructureRestId;
  31737. let propsTypeDecl;
  31738. let propsTypeDeclRaw;
  31739. let propsIdentifier;
  31740. let emitsRuntimeDecl;
  31741. let emitsTypeDecl;
  31742. let emitsTypeDeclRaw;
  31743. let emitIdentifier;
  31744. let hasAwait = false;
  31745. let hasInlinedSsrRenderFn = false;
  31746. // props/emits declared via types
  31747. const typeDeclaredProps = {};
  31748. const typeDeclaredEmits = new Set();
  31749. // record declared types for runtime props type generation
  31750. const declaredTypes = {};
  31751. // props destructure data
  31752. const propsDestructuredBindings = Object.create(null);
  31753. // magic-string state
  31754. const s = new MagicString$1(source);
  31755. const startOffset = scriptSetup.loc.start.offset;
  31756. const endOffset = scriptSetup.loc.end.offset;
  31757. const scriptStartOffset = script && script.loc.start.offset;
  31758. const scriptEndOffset = script && script.loc.end.offset;
  31759. function helper(key) {
  31760. helperImports.add(key);
  31761. return `_${key}`;
  31762. }
  31763. function parse(input, options, offset) {
  31764. try {
  31765. return parse_1$1(input, options).program;
  31766. }
  31767. catch (e) {
  31768. e.message = `[@vue/compiler-sfc] ${e.message}\n\n${sfc.filename}\n${generateCodeFrame(source, e.pos + offset, e.pos + offset + 1)}`;
  31769. throw e;
  31770. }
  31771. }
  31772. function error(msg, node, end = node.end + startOffset) {
  31773. throw new Error(`[@vue/compiler-sfc] ${msg}\n\n${sfc.filename}\n${generateCodeFrame(source, node.start + startOffset, end)}`);
  31774. }
  31775. function hoistNode(node) {
  31776. const start = node.start + startOffset;
  31777. let end = node.end + startOffset;
  31778. // locate comment
  31779. if (node.trailingComments && node.trailingComments.length > 0) {
  31780. const lastCommentNode = node.trailingComments[node.trailingComments.length - 1];
  31781. end = lastCommentNode.end + startOffset;
  31782. }
  31783. // locate the end of whitespace between this statement and the next
  31784. while (end <= source.length) {
  31785. if (!/\s/.test(source.charAt(end))) {
  31786. break;
  31787. }
  31788. end++;
  31789. }
  31790. s.move(start, end, 0);
  31791. }
  31792. function registerUserImport(source, local, imported, isType, isFromSetup, needTemplateUsageCheck) {
  31793. // template usage check is only needed in non-inline mode, so we can skip
  31794. // the work if inlineTemplate is true.
  31795. let isUsedInTemplate = needTemplateUsageCheck;
  31796. if (needTemplateUsageCheck &&
  31797. isTS &&
  31798. sfc.template &&
  31799. !sfc.template.src &&
  31800. !sfc.template.lang) {
  31801. isUsedInTemplate = isImportUsed(local, sfc);
  31802. }
  31803. userImports[local] = {
  31804. isType,
  31805. imported: imported || 'default',
  31806. local,
  31807. source,
  31808. isFromSetup,
  31809. isUsedInTemplate
  31810. };
  31811. }
  31812. function processDefineProps(node, declId, declKind) {
  31813. if (!isCallOf(node, DEFINE_PROPS)) {
  31814. return false;
  31815. }
  31816. if (hasDefinePropsCall) {
  31817. error(`duplicate ${DEFINE_PROPS}() call`, node);
  31818. }
  31819. hasDefinePropsCall = true;
  31820. propsRuntimeDecl = node.arguments[0];
  31821. // call has type parameters - infer runtime types from it
  31822. if (node.typeParameters) {
  31823. if (propsRuntimeDecl) {
  31824. error(`${DEFINE_PROPS}() cannot accept both type and non-type arguments ` +
  31825. `at the same time. Use one or the other.`, node);
  31826. }
  31827. propsTypeDeclRaw = node.typeParameters.params[0];
  31828. propsTypeDecl = resolveQualifiedType(propsTypeDeclRaw, node => node.type === 'TSTypeLiteral');
  31829. if (!propsTypeDecl) {
  31830. error(`type argument passed to ${DEFINE_PROPS}() must be a literal type, ` +
  31831. `or a reference to an interface or literal type.`, propsTypeDeclRaw);
  31832. }
  31833. }
  31834. if (declId) {
  31835. const isConst = declKind === 'const';
  31836. if (enablePropsTransform && declId.type === 'ObjectPattern') {
  31837. propsDestructureDecl = declId;
  31838. // props destructure - handle compilation sugar
  31839. for (const prop of declId.properties) {
  31840. if (prop.type === 'ObjectProperty') {
  31841. const propKey = resolveObjectKey(prop.key, prop.computed);
  31842. if (!propKey) {
  31843. error(`${DEFINE_PROPS}() destructure cannot use computed key.`, prop.key);
  31844. }
  31845. if (prop.value.type === 'AssignmentPattern') {
  31846. // default value { foo = 123 }
  31847. const { left, right } = prop.value;
  31848. if (left.type !== 'Identifier') {
  31849. error(`${DEFINE_PROPS}() destructure does not support nested patterns.`, left);
  31850. }
  31851. // store default value
  31852. propsDestructuredBindings[propKey] = {
  31853. local: left.name,
  31854. default: right,
  31855. isConst
  31856. };
  31857. }
  31858. else if (prop.value.type === 'Identifier') {
  31859. // simple destructure
  31860. propsDestructuredBindings[propKey] = {
  31861. local: prop.value.name,
  31862. isConst
  31863. };
  31864. }
  31865. else {
  31866. error(`${DEFINE_PROPS}() destructure does not support nested patterns.`, prop.value);
  31867. }
  31868. }
  31869. else {
  31870. // rest spread
  31871. propsDestructureRestId = prop.argument.name;
  31872. }
  31873. }
  31874. }
  31875. else {
  31876. propsIdentifier = scriptSetup.content.slice(declId.start, declId.end);
  31877. }
  31878. }
  31879. return true;
  31880. }
  31881. function processWithDefaults(node, declId, declKind) {
  31882. if (!isCallOf(node, WITH_DEFAULTS)) {
  31883. return false;
  31884. }
  31885. if (processDefineProps(node.arguments[0], declId, declKind)) {
  31886. if (propsRuntimeDecl) {
  31887. error(`${WITH_DEFAULTS} can only be used with type-based ` +
  31888. `${DEFINE_PROPS} declaration.`, node);
  31889. }
  31890. if (propsDestructureDecl) {
  31891. error(`${WITH_DEFAULTS}() is unnecessary when using destructure with ${DEFINE_PROPS}().\n` +
  31892. `Prefer using destructure default values, e.g. const { foo = 1 } = defineProps(...).`, node.callee);
  31893. }
  31894. propsRuntimeDefaults = node.arguments[1];
  31895. if (!propsRuntimeDefaults ||
  31896. propsRuntimeDefaults.type !== 'ObjectExpression') {
  31897. error(`The 2nd argument of ${WITH_DEFAULTS} must be an object literal.`, propsRuntimeDefaults || node);
  31898. }
  31899. }
  31900. else {
  31901. error(`${WITH_DEFAULTS}' first argument must be a ${DEFINE_PROPS} call.`, node.arguments[0] || node);
  31902. }
  31903. return true;
  31904. }
  31905. function processDefineEmits(node, declId) {
  31906. if (!isCallOf(node, DEFINE_EMITS)) {
  31907. return false;
  31908. }
  31909. if (hasDefineEmitCall) {
  31910. error(`duplicate ${DEFINE_EMITS}() call`, node);
  31911. }
  31912. hasDefineEmitCall = true;
  31913. emitsRuntimeDecl = node.arguments[0];
  31914. if (node.typeParameters) {
  31915. if (emitsRuntimeDecl) {
  31916. error(`${DEFINE_EMITS}() cannot accept both type and non-type arguments ` +
  31917. `at the same time. Use one or the other.`, node);
  31918. }
  31919. emitsTypeDeclRaw = node.typeParameters.params[0];
  31920. emitsTypeDecl = resolveQualifiedType(emitsTypeDeclRaw, node => node.type === 'TSFunctionType' || node.type === 'TSTypeLiteral');
  31921. if (!emitsTypeDecl) {
  31922. error(`type argument passed to ${DEFINE_EMITS}() must be a function type, ` +
  31923. `a literal type with call signatures, or a reference to the above types.`, emitsTypeDeclRaw);
  31924. }
  31925. }
  31926. if (declId) {
  31927. emitIdentifier =
  31928. declId.type === 'Identifier'
  31929. ? declId.name
  31930. : scriptSetup.content.slice(declId.start, declId.end);
  31931. }
  31932. return true;
  31933. }
  31934. function getAstBody() {
  31935. return scriptAst
  31936. ? [...scriptSetupAst.body, ...scriptAst.body]
  31937. : scriptSetupAst.body;
  31938. }
  31939. function resolveExtendsType(node, qualifier, cache = []) {
  31940. if (node.type === 'TSInterfaceDeclaration' && node.extends) {
  31941. node.extends.forEach(extend => {
  31942. if (extend.type === 'TSExpressionWithTypeArguments' &&
  31943. extend.expression.type === 'Identifier') {
  31944. const body = getAstBody();
  31945. for (const node of body) {
  31946. const qualified = isQualifiedType(node, qualifier, extend.expression.name);
  31947. if (qualified) {
  31948. cache.push(qualified);
  31949. resolveExtendsType(node, qualifier, cache);
  31950. return cache;
  31951. }
  31952. }
  31953. }
  31954. });
  31955. }
  31956. return cache;
  31957. }
  31958. function isQualifiedType(node, qualifier, refName) {
  31959. if (node.type === 'TSInterfaceDeclaration' && node.id.name === refName) {
  31960. return node.body;
  31961. }
  31962. else if (node.type === 'TSTypeAliasDeclaration' &&
  31963. node.id.name === refName &&
  31964. qualifier(node.typeAnnotation)) {
  31965. return node.typeAnnotation;
  31966. }
  31967. else if (node.type === 'ExportNamedDeclaration' && node.declaration) {
  31968. return isQualifiedType(node.declaration, qualifier, refName);
  31969. }
  31970. }
  31971. // filter all extends types to keep the override declaration
  31972. function filterExtendsType(extendsTypes, bodies) {
  31973. extendsTypes.forEach(extend => {
  31974. const body = extend.body;
  31975. body.forEach(newBody => {
  31976. if (newBody.type === 'TSPropertySignature' &&
  31977. newBody.key.type === 'Identifier') {
  31978. const name = newBody.key.name;
  31979. const hasOverride = bodies.some(seenBody => seenBody.type === 'TSPropertySignature' &&
  31980. seenBody.key.type === 'Identifier' &&
  31981. seenBody.key.name === name);
  31982. if (!hasOverride)
  31983. bodies.push(newBody);
  31984. }
  31985. });
  31986. });
  31987. }
  31988. function resolveQualifiedType(node, qualifier) {
  31989. if (qualifier(node)) {
  31990. return node;
  31991. }
  31992. if (node.type === 'TSTypeReference' &&
  31993. node.typeName.type === 'Identifier') {
  31994. const refName = node.typeName.name;
  31995. const body = getAstBody();
  31996. for (let i = 0; i < body.length; i++) {
  31997. const node = body[i];
  31998. let qualified = isQualifiedType(node, qualifier, refName);
  31999. if (qualified) {
  32000. const extendsTypes = resolveExtendsType(node, qualifier);
  32001. if (extendsTypes.length) {
  32002. const bodies = [...qualified.body];
  32003. filterExtendsType(extendsTypes, bodies);
  32004. qualified.body = bodies;
  32005. }
  32006. qualified.__fromNormalScript =
  32007. scriptAst && i >= scriptSetupAst.body.length;
  32008. return qualified;
  32009. }
  32010. }
  32011. }
  32012. }
  32013. function processDefineExpose(node) {
  32014. if (isCallOf(node, DEFINE_EXPOSE)) {
  32015. if (hasDefineExposeCall) {
  32016. error(`duplicate ${DEFINE_EXPOSE}() call`, node);
  32017. }
  32018. hasDefineExposeCall = true;
  32019. return true;
  32020. }
  32021. return false;
  32022. }
  32023. function checkInvalidScopeReference(node, method) {
  32024. if (!node)
  32025. return;
  32026. walkIdentifiers(node, id => {
  32027. if (setupBindings[id.name]) {
  32028. error(`\`${method}()\` in <script setup> cannot reference locally ` +
  32029. `declared variables because it will be hoisted outside of the ` +
  32030. `setup() function. If your component options require initialization ` +
  32031. `in the module scope, use a separate normal <script> to export ` +
  32032. `the options instead.`, id);
  32033. }
  32034. });
  32035. }
  32036. /**
  32037. * await foo()
  32038. * -->
  32039. * ;(
  32040. * ([__temp,__restore] = withAsyncContext(() => foo())),
  32041. * await __temp,
  32042. * __restore()
  32043. * )
  32044. *
  32045. * const a = await foo()
  32046. * -->
  32047. * const a = (
  32048. * ([__temp, __restore] = withAsyncContext(() => foo())),
  32049. * __temp = await __temp,
  32050. * __restore(),
  32051. * __temp
  32052. * )
  32053. */
  32054. function processAwait(node, needSemi, isStatement) {
  32055. const argumentStart = node.argument.extra && node.argument.extra.parenthesized
  32056. ? node.argument.extra.parenStart
  32057. : node.argument.start;
  32058. const argumentStr = source.slice(argumentStart + startOffset, node.argument.end + startOffset);
  32059. const containsNestedAwait = /\bawait\b/.test(argumentStr);
  32060. s.overwrite(node.start + startOffset, argumentStart + startOffset, `${needSemi ? `;` : ``}(\n ([__temp,__restore] = ${helper(`withAsyncContext`)}(${containsNestedAwait ? `async ` : ``}() => `);
  32061. s.appendLeft(node.end + startOffset, `)),\n ${isStatement ? `` : `__temp = `}await __temp,\n __restore()${isStatement ? `` : `,\n __temp`}\n)`);
  32062. }
  32063. /**
  32064. * check defaults. If the default object is an object literal with only
  32065. * static properties, we can directly generate more optimized default
  32066. * declarations. Otherwise we will have to fallback to runtime merging.
  32067. */
  32068. function hasStaticWithDefaults() {
  32069. return (propsRuntimeDefaults &&
  32070. propsRuntimeDefaults.type === 'ObjectExpression' &&
  32071. propsRuntimeDefaults.properties.every(node => (node.type === 'ObjectProperty' &&
  32072. (!node.computed || node.key.type.endsWith('Literal'))) ||
  32073. node.type === 'ObjectMethod'));
  32074. }
  32075. function genRuntimeProps(props) {
  32076. const keys = Object.keys(props);
  32077. if (!keys.length) {
  32078. return ``;
  32079. }
  32080. const hasStaticDefaults = hasStaticWithDefaults();
  32081. const scriptSetupSource = scriptSetup.content;
  32082. let propsDecls = `{
  32083. ${keys
  32084. .map(key => {
  32085. let defaultString;
  32086. const destructured = genDestructuredDefaultValue(key);
  32087. if (destructured) {
  32088. defaultString = `default: ${destructured}`;
  32089. }
  32090. else if (hasStaticDefaults) {
  32091. const prop = propsRuntimeDefaults.properties.find(node => {
  32092. if (node.type === 'SpreadElement')
  32093. return false;
  32094. return resolveObjectKey(node.key, node.computed) === key;
  32095. });
  32096. if (prop) {
  32097. if (prop.type === 'ObjectProperty') {
  32098. // prop has corresponding static default value
  32099. defaultString = `default: ${scriptSetupSource.slice(prop.value.start, prop.value.end)}`;
  32100. }
  32101. else {
  32102. defaultString = `${prop.async ? 'async ' : ''}${prop.kind !== 'method' ? `${prop.kind} ` : ''}default() ${scriptSetupSource.slice(prop.body.start, prop.body.end)}`;
  32103. }
  32104. }
  32105. }
  32106. const { type, required } = props[key];
  32107. if (!isProd) {
  32108. return `${key}: { type: ${toRuntimeTypeString(type)}, required: ${required}${defaultString ? `, ${defaultString}` : ``} }`;
  32109. }
  32110. else if (type.some(el => el === 'Boolean' ||
  32111. ((!hasStaticDefaults || defaultString) && el === 'Function'))) {
  32112. // #4783 for boolean, should keep the type
  32113. // #7111 for function, if default value exists or it's not static, should keep it
  32114. // in production
  32115. return `${key}: { type: ${toRuntimeTypeString(type)}${defaultString ? `, ${defaultString}` : ``} }`;
  32116. }
  32117. else {
  32118. // production: checks are useless
  32119. return `${key}: ${defaultString ? `{ ${defaultString} }` : 'null'}`;
  32120. }
  32121. })
  32122. .join(',\n ')}\n }`;
  32123. if (propsRuntimeDefaults && !hasStaticDefaults) {
  32124. propsDecls = `${helper('mergeDefaults')}(${propsDecls}, ${source.slice(propsRuntimeDefaults.start + startOffset, propsRuntimeDefaults.end + startOffset)})`;
  32125. }
  32126. return `\n props: ${propsDecls},`;
  32127. }
  32128. function genDestructuredDefaultValue(key) {
  32129. const destructured = propsDestructuredBindings[key];
  32130. if (destructured && destructured.default) {
  32131. const value = scriptSetup.content.slice(destructured.default.start, destructured.default.end);
  32132. const isLiteral = destructured.default.type.endsWith('Literal');
  32133. return isLiteral ? value : `() => (${value})`;
  32134. }
  32135. }
  32136. function genSetupPropsType(node) {
  32137. const scriptSource = node.__fromNormalScript
  32138. ? script.content
  32139. : scriptSetup.content;
  32140. if (hasStaticWithDefaults()) {
  32141. // if withDefaults() is used, we need to remove the optional flags
  32142. // on props that have default values
  32143. let res = `{ `;
  32144. const members = node.type === 'TSTypeLiteral' ? node.members : node.body;
  32145. for (const m of members) {
  32146. if ((m.type === 'TSPropertySignature' ||
  32147. m.type === 'TSMethodSignature') &&
  32148. m.typeAnnotation &&
  32149. m.key.type === 'Identifier') {
  32150. if (propsRuntimeDefaults.properties.some(p => {
  32151. if (p.type === 'SpreadElement')
  32152. return false;
  32153. return (resolveObjectKey(p.key, p.computed) ===
  32154. m.key.name);
  32155. })) {
  32156. res +=
  32157. m.key.name +
  32158. (m.type === 'TSMethodSignature' ? '()' : '') +
  32159. scriptSource.slice(m.typeAnnotation.start, m.typeAnnotation.end) +
  32160. ', ';
  32161. }
  32162. else {
  32163. res += scriptSource.slice(m.start, m.typeAnnotation.end) + `, `;
  32164. }
  32165. }
  32166. }
  32167. return (res.length ? res.slice(0, -2) : res) + ` }`;
  32168. }
  32169. else {
  32170. return scriptSource.slice(node.start, node.end);
  32171. }
  32172. }
  32173. // 0. parse both <script> and <script setup> blocks
  32174. const scriptAst = script &&
  32175. parse(script.content, {
  32176. plugins,
  32177. sourceType: 'module'
  32178. }, scriptStartOffset);
  32179. const scriptSetupAst = parse(scriptSetup.content, {
  32180. plugins: [
  32181. ...plugins,
  32182. // allow top level await but only inside <script setup>
  32183. 'topLevelAwait'
  32184. ],
  32185. sourceType: 'module'
  32186. }, startOffset);
  32187. // 1.1 walk import delcarations of <script>
  32188. if (scriptAst) {
  32189. for (const node of scriptAst.body) {
  32190. if (node.type === 'ImportDeclaration') {
  32191. // record imports for dedupe
  32192. for (const specifier of node.specifiers) {
  32193. const imported = specifier.type === 'ImportSpecifier' &&
  32194. specifier.imported.type === 'Identifier' &&
  32195. specifier.imported.name;
  32196. registerUserImport(node.source.value, specifier.local.name, imported, node.importKind === 'type' ||
  32197. (specifier.type === 'ImportSpecifier' &&
  32198. specifier.importKind === 'type'), false, !options.inlineTemplate);
  32199. }
  32200. }
  32201. }
  32202. }
  32203. // 1.2 walk import declarations of <script setup>
  32204. for (const node of scriptSetupAst.body) {
  32205. if (node.type === 'ImportDeclaration') {
  32206. // import declarations are moved to top
  32207. hoistNode(node);
  32208. // dedupe imports
  32209. let removed = 0;
  32210. const removeSpecifier = (i) => {
  32211. const removeLeft = i > removed;
  32212. removed++;
  32213. const current = node.specifiers[i];
  32214. const next = node.specifiers[i + 1];
  32215. s.remove(removeLeft
  32216. ? node.specifiers[i - 1].end + startOffset
  32217. : current.start + startOffset, next && !removeLeft
  32218. ? next.start + startOffset
  32219. : current.end + startOffset);
  32220. };
  32221. for (let i = 0; i < node.specifiers.length; i++) {
  32222. const specifier = node.specifiers[i];
  32223. const local = specifier.local.name;
  32224. let imported = specifier.type === 'ImportSpecifier' &&
  32225. specifier.imported.type === 'Identifier' &&
  32226. specifier.imported.name;
  32227. if (specifier.type === 'ImportNamespaceSpecifier') {
  32228. imported = '*';
  32229. }
  32230. const source = node.source.value;
  32231. const existing = userImports[local];
  32232. if (source === 'vue' &&
  32233. (imported === DEFINE_PROPS ||
  32234. imported === DEFINE_EMITS ||
  32235. imported === DEFINE_EXPOSE)) {
  32236. warnOnce$4(`\`${imported}\` is a compiler macro and no longer needs to be imported.`);
  32237. removeSpecifier(i);
  32238. }
  32239. else if (existing) {
  32240. if (existing.source === source && existing.imported === imported) {
  32241. // already imported in <script setup>, dedupe
  32242. removeSpecifier(i);
  32243. }
  32244. else {
  32245. error(`different imports aliased to same local name.`, specifier);
  32246. }
  32247. }
  32248. else {
  32249. registerUserImport(source, local, imported, node.importKind === 'type' ||
  32250. (specifier.type === 'ImportSpecifier' &&
  32251. specifier.importKind === 'type'), true, !options.inlineTemplate);
  32252. }
  32253. }
  32254. if (node.specifiers.length && removed === node.specifiers.length) {
  32255. s.remove(node.start + startOffset, node.end + startOffset);
  32256. }
  32257. }
  32258. }
  32259. // 1.3 resolve possible user import alias of `ref` and `reactive`
  32260. const vueImportAliases = {};
  32261. for (const key in userImports) {
  32262. const { source, imported, local } = userImports[key];
  32263. if (source === 'vue')
  32264. vueImportAliases[imported] = local;
  32265. }
  32266. // 2.1 process normal <script> body
  32267. if (script && scriptAst) {
  32268. for (const node of scriptAst.body) {
  32269. if (node.type === 'ExportDefaultDeclaration') {
  32270. // export default
  32271. defaultExport = node;
  32272. // check if user has manually specified `name` or 'render` option in
  32273. // export default
  32274. // if has name, skip name inference
  32275. // if has render and no template, generate return object instead of
  32276. // empty render function (#4980)
  32277. let optionProperties;
  32278. if (defaultExport.declaration.type === 'ObjectExpression') {
  32279. optionProperties = defaultExport.declaration.properties;
  32280. }
  32281. else if (defaultExport.declaration.type === 'CallExpression' &&
  32282. defaultExport.declaration.arguments[0].type === 'ObjectExpression') {
  32283. optionProperties = defaultExport.declaration.arguments[0].properties;
  32284. }
  32285. if (optionProperties) {
  32286. for (const s of optionProperties) {
  32287. if (s.type === 'ObjectProperty' &&
  32288. s.key.type === 'Identifier' &&
  32289. s.key.name === 'name') {
  32290. hasDefaultExportName = true;
  32291. }
  32292. if ((s.type === 'ObjectMethod' || s.type === 'ObjectProperty') &&
  32293. s.key.type === 'Identifier' &&
  32294. s.key.name === 'render') {
  32295. // TODO warn when we provide a better way to do it?
  32296. hasDefaultExportRender = true;
  32297. }
  32298. }
  32299. }
  32300. // export default { ... } --> const __default__ = { ... }
  32301. const start = node.start + scriptStartOffset;
  32302. const end = node.declaration.start + scriptStartOffset;
  32303. s.overwrite(start, end, `const ${DEFAULT_VAR} = `);
  32304. }
  32305. else if (node.type === 'ExportNamedDeclaration') {
  32306. const defaultSpecifier = node.specifiers.find(s => s.exported.type === 'Identifier' && s.exported.name === 'default');
  32307. if (defaultSpecifier) {
  32308. defaultExport = node;
  32309. // 1. remove specifier
  32310. if (node.specifiers.length > 1) {
  32311. s.remove(defaultSpecifier.start + scriptStartOffset, defaultSpecifier.end + scriptStartOffset);
  32312. }
  32313. else {
  32314. s.remove(node.start + scriptStartOffset, node.end + scriptStartOffset);
  32315. }
  32316. if (node.source) {
  32317. // export { x as default } from './x'
  32318. // rewrite to `import { x as __default__ } from './x'` and
  32319. // add to top
  32320. s.prepend(`import { ${defaultSpecifier.local.name} as ${DEFAULT_VAR} } from '${node.source.value}'\n`);
  32321. }
  32322. else {
  32323. // export { x as default }
  32324. // rewrite to `const __default__ = x` and move to end
  32325. s.appendLeft(scriptEndOffset, `\nconst ${DEFAULT_VAR} = ${defaultSpecifier.local.name}\n`);
  32326. }
  32327. }
  32328. if (node.declaration) {
  32329. walkDeclaration(node.declaration, scriptBindings, vueImportAliases);
  32330. }
  32331. }
  32332. else if ((node.type === 'VariableDeclaration' ||
  32333. node.type === 'FunctionDeclaration' ||
  32334. node.type === 'ClassDeclaration' ||
  32335. node.type === 'TSEnumDeclaration') &&
  32336. !node.declare) {
  32337. walkDeclaration(node, scriptBindings, vueImportAliases);
  32338. }
  32339. }
  32340. // apply reactivity transform
  32341. if (enableReactivityTransform && shouldTransform(script.content)) {
  32342. const { rootRefs, importedHelpers } = transformAST(scriptAst, s, scriptStartOffset);
  32343. refBindings = rootRefs;
  32344. for (const h of importedHelpers) {
  32345. helperImports.add(h);
  32346. }
  32347. }
  32348. // <script> after <script setup>
  32349. // we need to move the block up so that `const __default__` is
  32350. // declared before being used in the actual component definition
  32351. if (scriptStartOffset > startOffset) {
  32352. // if content doesn't end with newline, add one
  32353. if (!/\n$/.test(script.content.trim())) {
  32354. s.appendLeft(scriptEndOffset, `\n`);
  32355. }
  32356. s.move(scriptStartOffset, scriptEndOffset, 0);
  32357. }
  32358. }
  32359. // 2.2 process <script setup> body
  32360. for (const node of scriptSetupAst.body) {
  32361. // (Dropped) `ref: x` bindings
  32362. // TODO remove when out of experimental
  32363. if (node.type === 'LabeledStatement' &&
  32364. node.label.name === 'ref' &&
  32365. node.body.type === 'ExpressionStatement') {
  32366. error(`ref sugar using the label syntax was an experimental proposal and ` +
  32367. `has been dropped based on community feedback. Please check out ` +
  32368. `the new proposal at https://github.com/vuejs/rfcs/discussions/369`, node);
  32369. }
  32370. if (node.type === 'ExpressionStatement') {
  32371. // process `defineProps` and `defineEmit(s)` calls
  32372. if (processDefineProps(node.expression) ||
  32373. processDefineEmits(node.expression) ||
  32374. processWithDefaults(node.expression)) {
  32375. s.remove(node.start + startOffset, node.end + startOffset);
  32376. }
  32377. else if (processDefineExpose(node.expression)) {
  32378. // defineExpose({}) -> expose({})
  32379. const callee = node.expression.callee;
  32380. s.overwrite(callee.start + startOffset, callee.end + startOffset, 'expose');
  32381. }
  32382. }
  32383. if (node.type === 'VariableDeclaration' && !node.declare) {
  32384. const total = node.declarations.length;
  32385. let left = total;
  32386. for (let i = 0; i < total; i++) {
  32387. const decl = node.declarations[i];
  32388. if (decl.init) {
  32389. // defineProps / defineEmits
  32390. const isDefineProps = processDefineProps(decl.init, decl.id, node.kind) ||
  32391. processWithDefaults(decl.init, decl.id, node.kind);
  32392. const isDefineEmits = processDefineEmits(decl.init, decl.id);
  32393. if (isDefineProps || isDefineEmits) {
  32394. if (left === 1) {
  32395. s.remove(node.start + startOffset, node.end + startOffset);
  32396. }
  32397. else {
  32398. let start = decl.start + startOffset;
  32399. let end = decl.end + startOffset;
  32400. if (i === 0) {
  32401. // first one, locate the start of the next
  32402. end = node.declarations[i + 1].start + startOffset;
  32403. }
  32404. else {
  32405. // not first one, locate the end of the prev
  32406. start = node.declarations[i - 1].end + startOffset;
  32407. }
  32408. s.remove(start, end);
  32409. left--;
  32410. }
  32411. }
  32412. }
  32413. }
  32414. }
  32415. // walk declarations to record declared bindings
  32416. if ((node.type === 'VariableDeclaration' ||
  32417. node.type === 'FunctionDeclaration' ||
  32418. node.type === 'ClassDeclaration') &&
  32419. !node.declare) {
  32420. walkDeclaration(node, setupBindings, vueImportAliases);
  32421. }
  32422. // walk statements & named exports / variable declarations for top level
  32423. // await
  32424. if ((node.type === 'VariableDeclaration' && !node.declare) ||
  32425. node.type.endsWith('Statement')) {
  32426. const scope = [scriptSetupAst.body];
  32427. walk$1(node, {
  32428. enter(child, parent) {
  32429. if (isFunctionType(child)) {
  32430. this.skip();
  32431. }
  32432. if (child.type === 'BlockStatement') {
  32433. scope.push(child.body);
  32434. }
  32435. if (child.type === 'AwaitExpression') {
  32436. hasAwait = true;
  32437. // if the await expression is an expression statement and
  32438. // - is in the root scope
  32439. // - or is not the first statement in a nested block scope
  32440. // then it needs a semicolon before the generated code.
  32441. const currentScope = scope[scope.length - 1];
  32442. const needsSemi = currentScope.some((n, i) => {
  32443. return ((scope.length === 1 || i > 0) &&
  32444. n.type === 'ExpressionStatement' &&
  32445. n.start === child.start);
  32446. });
  32447. processAwait(child, needsSemi, parent.type === 'ExpressionStatement');
  32448. }
  32449. },
  32450. exit(node) {
  32451. if (node.type === 'BlockStatement')
  32452. scope.pop();
  32453. }
  32454. });
  32455. }
  32456. if ((node.type === 'ExportNamedDeclaration' && node.exportKind !== 'type') ||
  32457. node.type === 'ExportAllDeclaration' ||
  32458. node.type === 'ExportDefaultDeclaration') {
  32459. error(`<script setup> cannot contain ES module exports. ` +
  32460. `If you are using a previous version of <script setup>, please ` +
  32461. `consult the updated RFC at https://github.com/vuejs/rfcs/pull/227.`, node);
  32462. }
  32463. if (isTS) {
  32464. // runtime enum
  32465. if (node.type === 'TSEnumDeclaration') {
  32466. registerBinding(setupBindings, node.id, "setup-const" /* BindingTypes.SETUP_CONST */);
  32467. }
  32468. // move all Type declarations to outer scope
  32469. if (node.type.startsWith('TS') ||
  32470. (node.type === 'ExportNamedDeclaration' &&
  32471. node.exportKind === 'type') ||
  32472. (node.type === 'VariableDeclaration' && node.declare)) {
  32473. recordType(node, declaredTypes);
  32474. hoistNode(node);
  32475. }
  32476. }
  32477. }
  32478. // 3. Apply reactivity transform
  32479. if ((enableReactivityTransform &&
  32480. // normal <script> had ref bindings that maybe used in <script setup>
  32481. (refBindings || shouldTransform(scriptSetup.content))) ||
  32482. propsDestructureDecl) {
  32483. const { rootRefs, importedHelpers } = transformAST(scriptSetupAst, s, startOffset, refBindings, propsDestructuredBindings);
  32484. refBindings = refBindings ? [...refBindings, ...rootRefs] : rootRefs;
  32485. for (const h of importedHelpers) {
  32486. helperImports.add(h);
  32487. }
  32488. }
  32489. // 4. extract runtime props/emits code from setup context type
  32490. if (propsTypeDecl) {
  32491. extractRuntimeProps(propsTypeDecl, typeDeclaredProps, declaredTypes);
  32492. }
  32493. if (emitsTypeDecl) {
  32494. extractRuntimeEmits(emitsTypeDecl, typeDeclaredEmits);
  32495. }
  32496. // 5. check useOptions args to make sure it doesn't reference setup scope
  32497. // variables
  32498. checkInvalidScopeReference(propsRuntimeDecl, DEFINE_PROPS);
  32499. checkInvalidScopeReference(propsRuntimeDefaults, DEFINE_PROPS);
  32500. checkInvalidScopeReference(propsDestructureDecl, DEFINE_PROPS);
  32501. checkInvalidScopeReference(emitsRuntimeDecl, DEFINE_EMITS);
  32502. // 6. remove non-script content
  32503. if (script) {
  32504. if (startOffset < scriptStartOffset) {
  32505. // <script setup> before <script>
  32506. s.remove(0, startOffset);
  32507. s.remove(endOffset, scriptStartOffset);
  32508. s.remove(scriptEndOffset, source.length);
  32509. }
  32510. else {
  32511. // <script> before <script setup>
  32512. s.remove(0, scriptStartOffset);
  32513. s.remove(scriptEndOffset, startOffset);
  32514. s.remove(endOffset, source.length);
  32515. }
  32516. }
  32517. else {
  32518. // only <script setup>
  32519. s.remove(0, startOffset);
  32520. s.remove(endOffset, source.length);
  32521. }
  32522. // 7. analyze binding metadata
  32523. if (scriptAst) {
  32524. Object.assign(bindingMetadata, analyzeScriptBindings(scriptAst.body));
  32525. }
  32526. if (propsRuntimeDecl) {
  32527. for (const key of getObjectOrArrayExpressionKeys(propsRuntimeDecl)) {
  32528. bindingMetadata[key] = "props" /* BindingTypes.PROPS */;
  32529. }
  32530. }
  32531. for (const key in typeDeclaredProps) {
  32532. bindingMetadata[key] = "props" /* BindingTypes.PROPS */;
  32533. }
  32534. // props aliases
  32535. if (propsDestructureDecl) {
  32536. if (propsDestructureRestId) {
  32537. bindingMetadata[propsDestructureRestId] =
  32538. "setup-reactive-const" /* BindingTypes.SETUP_REACTIVE_CONST */;
  32539. }
  32540. for (const key in propsDestructuredBindings) {
  32541. const { local } = propsDestructuredBindings[key];
  32542. if (local !== key) {
  32543. bindingMetadata[local] = "props-aliased" /* BindingTypes.PROPS_ALIASED */;
  32544. (bindingMetadata.__propsAliases ||
  32545. (bindingMetadata.__propsAliases = {}))[local] = key;
  32546. }
  32547. }
  32548. }
  32549. for (const [key, { isType, imported, source }] of Object.entries(userImports)) {
  32550. if (isType)
  32551. continue;
  32552. bindingMetadata[key] =
  32553. imported === '*' ||
  32554. (imported === 'default' && source.endsWith('.vue')) ||
  32555. source === 'vue'
  32556. ? "setup-const" /* BindingTypes.SETUP_CONST */
  32557. : "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */;
  32558. }
  32559. for (const key in scriptBindings) {
  32560. bindingMetadata[key] = scriptBindings[key];
  32561. }
  32562. for (const key in setupBindings) {
  32563. bindingMetadata[key] = setupBindings[key];
  32564. }
  32565. // known ref bindings
  32566. if (refBindings) {
  32567. for (const key of refBindings) {
  32568. bindingMetadata[key] = "setup-ref" /* BindingTypes.SETUP_REF */;
  32569. }
  32570. }
  32571. // 8. inject `useCssVars` calls
  32572. if (cssVars.length &&
  32573. // no need to do this when targeting SSR
  32574. !(options.inlineTemplate && ((_a = options.templateOptions) === null || _a === void 0 ? void 0 : _a.ssr))) {
  32575. helperImports.add(CSS_VARS_HELPER);
  32576. helperImports.add('unref');
  32577. s.prependRight(startOffset, `\n${genCssVarsCode(cssVars, bindingMetadata, scopeId, isProd)}\n`);
  32578. }
  32579. // 9. finalize setup() argument signature
  32580. let args = `__props`;
  32581. if (propsTypeDecl) {
  32582. // mark as any and only cast on assignment
  32583. // since the user defined complex types may be incompatible with the
  32584. // inferred type from generated runtime declarations
  32585. args += `: any`;
  32586. }
  32587. // inject user assignment of props
  32588. // we use a default __props so that template expressions referencing props
  32589. // can use it directly
  32590. if (propsIdentifier) {
  32591. s.prependLeft(startOffset, `\nconst ${propsIdentifier} = __props${propsTypeDecl ? ` as ${genSetupPropsType(propsTypeDecl)}` : ``};\n`);
  32592. }
  32593. if (propsDestructureRestId) {
  32594. s.prependLeft(startOffset, `\nconst ${propsDestructureRestId} = ${helper(`createPropsRestProxy`)}(__props, ${JSON.stringify(Object.keys(propsDestructuredBindings))});\n`);
  32595. }
  32596. // inject temp variables for async context preservation
  32597. if (hasAwait) {
  32598. const any = isTS ? `: any` : ``;
  32599. s.prependLeft(startOffset, `\nlet __temp${any}, __restore${any}\n`);
  32600. }
  32601. const destructureElements = hasDefineExposeCall || !options.inlineTemplate ? [`expose`] : [];
  32602. if (emitIdentifier) {
  32603. destructureElements.push(emitIdentifier === `emit` ? `emit` : `emit: ${emitIdentifier}`);
  32604. }
  32605. if (destructureElements.length) {
  32606. args += `, { ${destructureElements.join(', ')} }`;
  32607. if (emitsTypeDecl) {
  32608. const content = emitsTypeDecl.__fromNormalScript
  32609. ? script.content
  32610. : scriptSetup.content;
  32611. args += `: { emit: (${content.slice(emitsTypeDecl.start, emitsTypeDecl.end)}), expose: any, slots: any, attrs: any }`;
  32612. }
  32613. }
  32614. // 10. generate return statement
  32615. let returned;
  32616. if (!options.inlineTemplate || (!sfc.template && hasDefaultExportRender)) {
  32617. // non-inline mode, or has manual render in normal <script>
  32618. // return bindings from script and script setup
  32619. const allBindings = Object.assign(Object.assign({}, scriptBindings), setupBindings);
  32620. for (const key in userImports) {
  32621. if (!userImports[key].isType && userImports[key].isUsedInTemplate) {
  32622. allBindings[key] = true;
  32623. }
  32624. }
  32625. returned = `{ `;
  32626. for (const key in allBindings) {
  32627. if (allBindings[key] === true &&
  32628. userImports[key].source !== 'vue' &&
  32629. !userImports[key].source.endsWith('.vue')) {
  32630. // generate getter for import bindings
  32631. // skip vue imports since we know they will never change
  32632. returned += `get ${key}() { return ${key} }, `;
  32633. }
  32634. else if (bindingMetadata[key] === "setup-let" /* BindingTypes.SETUP_LET */) {
  32635. // local let binding, also add setter
  32636. const setArg = key === 'v' ? `_v` : `v`;
  32637. returned +=
  32638. `get ${key}() { return ${key} }, ` +
  32639. `set ${key}(${setArg}) { ${key} = ${setArg} }, `;
  32640. }
  32641. else {
  32642. returned += `${key}, `;
  32643. }
  32644. }
  32645. returned = returned.replace(/, $/, '') + ` }`;
  32646. }
  32647. else {
  32648. // inline mode
  32649. if (sfc.template && !sfc.template.src) {
  32650. if (options.templateOptions && options.templateOptions.ssr) {
  32651. hasInlinedSsrRenderFn = true;
  32652. }
  32653. // inline render function mode - we are going to compile the template and
  32654. // inline it right here
  32655. const { code, ast, preamble, tips, errors } = compileTemplate(Object.assign(Object.assign({ filename, source: sfc.template.content, inMap: sfc.template.map }, options.templateOptions), { id: scopeId, scoped: sfc.styles.some(s => s.scoped), isProd: options.isProd, ssrCssVars: sfc.cssVars, compilerOptions: Object.assign(Object.assign({}, (options.templateOptions &&
  32656. options.templateOptions.compilerOptions)), { inline: true, isTS,
  32657. bindingMetadata }) }));
  32658. if (tips.length) {
  32659. tips.forEach(warnOnce$4);
  32660. }
  32661. const err = errors[0];
  32662. if (typeof err === 'string') {
  32663. throw new Error(err);
  32664. }
  32665. else if (err) {
  32666. if (err.loc) {
  32667. err.message +=
  32668. `\n\n` +
  32669. sfc.filename +
  32670. '\n' +
  32671. generateCodeFrame(source, err.loc.start.offset, err.loc.end.offset) +
  32672. `\n`;
  32673. }
  32674. throw err;
  32675. }
  32676. if (preamble) {
  32677. s.prepend(preamble);
  32678. }
  32679. // avoid duplicated unref import
  32680. // as this may get injected by the render function preamble OR the
  32681. // css vars codegen
  32682. if (ast && ast.helpers.has(UNREF)) {
  32683. helperImports.delete('unref');
  32684. }
  32685. returned = code;
  32686. }
  32687. else {
  32688. returned = `() => {}`;
  32689. }
  32690. }
  32691. if (!options.inlineTemplate && !false) {
  32692. // in non-inline mode, the `__isScriptSetup: true` flag is used by
  32693. // componentPublicInstance proxy to allow properties that start with $ or _
  32694. s.appendRight(endOffset, `\nconst __returned__ = ${returned}\n` +
  32695. `Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })\n` +
  32696. `return __returned__` +
  32697. `\n}\n\n`);
  32698. }
  32699. else {
  32700. s.appendRight(endOffset, `\nreturn ${returned}\n}\n\n`);
  32701. }
  32702. // 11. finalize default export
  32703. let runtimeOptions = ``;
  32704. if (!hasDefaultExportName && filename && filename !== DEFAULT_FILENAME) {
  32705. const match = filename.match(/([^/\\]+)\.\w+$/);
  32706. if (match) {
  32707. runtimeOptions += `\n __name: '${match[1]}',`;
  32708. }
  32709. }
  32710. if (hasInlinedSsrRenderFn) {
  32711. runtimeOptions += `\n __ssrInlineRender: true,`;
  32712. }
  32713. if (propsRuntimeDecl) {
  32714. let declCode = scriptSetup.content
  32715. .slice(propsRuntimeDecl.start, propsRuntimeDecl.end)
  32716. .trim();
  32717. if (propsDestructureDecl) {
  32718. const defaults = [];
  32719. for (const key in propsDestructuredBindings) {
  32720. const d = genDestructuredDefaultValue(key);
  32721. if (d)
  32722. defaults.push(`${key}: ${d}`);
  32723. }
  32724. if (defaults.length) {
  32725. declCode = `${helper(`mergeDefaults`)}(${declCode}, {\n ${defaults.join(',\n ')}\n})`;
  32726. }
  32727. }
  32728. runtimeOptions += `\n props: ${declCode},`;
  32729. }
  32730. else if (propsTypeDecl) {
  32731. runtimeOptions += genRuntimeProps(typeDeclaredProps);
  32732. }
  32733. if (emitsRuntimeDecl) {
  32734. runtimeOptions += `\n emits: ${scriptSetup.content
  32735. .slice(emitsRuntimeDecl.start, emitsRuntimeDecl.end)
  32736. .trim()},`;
  32737. }
  32738. else if (emitsTypeDecl) {
  32739. runtimeOptions += genRuntimeEmits(typeDeclaredEmits);
  32740. }
  32741. // <script setup> components are closed by default. If the user did not
  32742. // explicitly call `defineExpose`, call expose() with no args.
  32743. const exposeCall = hasDefineExposeCall || options.inlineTemplate ? `` : ` expose();\n`;
  32744. // wrap setup code with function.
  32745. if (isTS) {
  32746. // for TS, make sure the exported type is still valid type with
  32747. // correct props information
  32748. // we have to use object spread for types to be merged properly
  32749. // user's TS setting should compile it down to proper targets
  32750. // export default defineComponent({ ...__default__, ... })
  32751. const def = defaultExport ? `\n ...${DEFAULT_VAR},` : ``;
  32752. s.prependLeft(startOffset, `\nexport default /*#__PURE__*/${helper(`defineComponent`)}({${def}${runtimeOptions}\n ${hasAwait ? `async ` : ``}setup(${args}) {\n${exposeCall}`);
  32753. s.appendRight(endOffset, `})`);
  32754. }
  32755. else {
  32756. if (defaultExport) {
  32757. // without TS, can't rely on rest spread, so we use Object.assign
  32758. // export default Object.assign(__default__, { ... })
  32759. s.prependLeft(startOffset, `\nexport default /*#__PURE__*/Object.assign(${DEFAULT_VAR}, {${runtimeOptions}\n ` +
  32760. `${hasAwait ? `async ` : ``}setup(${args}) {\n${exposeCall}`);
  32761. s.appendRight(endOffset, `})`);
  32762. }
  32763. else {
  32764. s.prependLeft(startOffset, `\nexport default {${runtimeOptions}\n ` +
  32765. `${hasAwait ? `async ` : ``}setup(${args}) {\n${exposeCall}`);
  32766. s.appendRight(endOffset, `}`);
  32767. }
  32768. }
  32769. // 12. finalize Vue helper imports
  32770. if (helperImports.size > 0) {
  32771. s.prepend(`import { ${[...helperImports]
  32772. .map(h => `${h} as _${h}`)
  32773. .join(', ')} } from 'vue'\n`);
  32774. }
  32775. s.trim();
  32776. return Object.assign(Object.assign({}, scriptSetup), { bindings: bindingMetadata, imports: userImports, content: s.toString(), map: genSourceMap
  32777. ? s.generateMap({
  32778. source: filename,
  32779. hires: true,
  32780. includeContent: true
  32781. })
  32782. : undefined, scriptAst: scriptAst === null || scriptAst === void 0 ? void 0 : scriptAst.body, scriptSetupAst: scriptSetupAst === null || scriptSetupAst === void 0 ? void 0 : scriptSetupAst.body });
  32783. }
  32784. function registerBinding(bindings, node, type) {
  32785. bindings[node.name] = type;
  32786. }
  32787. function walkDeclaration(node, bindings, userImportAliases) {
  32788. if (node.type === 'VariableDeclaration') {
  32789. const isConst = node.kind === 'const';
  32790. // export const foo = ...
  32791. for (const { id, init } of node.declarations) {
  32792. const isDefineCall = !!(isConst &&
  32793. isCallOf(init, c => c === DEFINE_PROPS || c === DEFINE_EMITS || c === WITH_DEFAULTS));
  32794. if (id.type === 'Identifier') {
  32795. let bindingType;
  32796. const userReactiveBinding = userImportAliases['reactive'];
  32797. if (isCallOf(init, userReactiveBinding)) {
  32798. // treat reactive() calls as let since it's meant to be mutable
  32799. bindingType = isConst
  32800. ? "setup-reactive-const" /* BindingTypes.SETUP_REACTIVE_CONST */
  32801. : "setup-let" /* BindingTypes.SETUP_LET */;
  32802. }
  32803. else if (
  32804. // if a declaration is a const literal, we can mark it so that
  32805. // the generated render fn code doesn't need to unref() it
  32806. isDefineCall ||
  32807. (isConst && canNeverBeRef(init, userReactiveBinding))) {
  32808. bindingType = isCallOf(init, DEFINE_PROPS)
  32809. ? "setup-reactive-const" /* BindingTypes.SETUP_REACTIVE_CONST */
  32810. : "setup-const" /* BindingTypes.SETUP_CONST */;
  32811. }
  32812. else if (isConst) {
  32813. if (isCallOf(init, userImportAliases['ref'])) {
  32814. bindingType = "setup-ref" /* BindingTypes.SETUP_REF */;
  32815. }
  32816. else {
  32817. bindingType = "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */;
  32818. }
  32819. }
  32820. else {
  32821. bindingType = "setup-let" /* BindingTypes.SETUP_LET */;
  32822. }
  32823. registerBinding(bindings, id, bindingType);
  32824. }
  32825. else {
  32826. if (isCallOf(init, DEFINE_PROPS)) {
  32827. continue;
  32828. }
  32829. if (id.type === 'ObjectPattern') {
  32830. walkObjectPattern(id, bindings, isConst, isDefineCall);
  32831. }
  32832. else if (id.type === 'ArrayPattern') {
  32833. walkArrayPattern(id, bindings, isConst, isDefineCall);
  32834. }
  32835. }
  32836. }
  32837. }
  32838. else if (node.type === 'TSEnumDeclaration' ||
  32839. node.type === 'FunctionDeclaration' ||
  32840. node.type === 'ClassDeclaration') {
  32841. // export function foo() {} / export class Foo {}
  32842. // export declarations must be named.
  32843. bindings[node.id.name] = "setup-const" /* BindingTypes.SETUP_CONST */;
  32844. }
  32845. }
  32846. function walkObjectPattern(node, bindings, isConst, isDefineCall = false) {
  32847. for (const p of node.properties) {
  32848. if (p.type === 'ObjectProperty') {
  32849. if (p.key.type === 'Identifier' && p.key === p.value) {
  32850. // shorthand: const { x } = ...
  32851. const type = isDefineCall
  32852. ? "setup-const" /* BindingTypes.SETUP_CONST */
  32853. : isConst
  32854. ? "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */
  32855. : "setup-let" /* BindingTypes.SETUP_LET */;
  32856. registerBinding(bindings, p.key, type);
  32857. }
  32858. else {
  32859. walkPattern(p.value, bindings, isConst, isDefineCall);
  32860. }
  32861. }
  32862. else {
  32863. // ...rest
  32864. // argument can only be identifier when destructuring
  32865. const type = isConst ? "setup-const" /* BindingTypes.SETUP_CONST */ : "setup-let" /* BindingTypes.SETUP_LET */;
  32866. registerBinding(bindings, p.argument, type);
  32867. }
  32868. }
  32869. }
  32870. function walkArrayPattern(node, bindings, isConst, isDefineCall = false) {
  32871. for (const e of node.elements) {
  32872. e && walkPattern(e, bindings, isConst, isDefineCall);
  32873. }
  32874. }
  32875. function walkPattern(node, bindings, isConst, isDefineCall = false) {
  32876. if (node.type === 'Identifier') {
  32877. const type = isDefineCall
  32878. ? "setup-const" /* BindingTypes.SETUP_CONST */
  32879. : isConst
  32880. ? "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */
  32881. : "setup-let" /* BindingTypes.SETUP_LET */;
  32882. registerBinding(bindings, node, type);
  32883. }
  32884. else if (node.type === 'RestElement') {
  32885. // argument can only be identifier when destructuring
  32886. const type = isConst ? "setup-const" /* BindingTypes.SETUP_CONST */ : "setup-let" /* BindingTypes.SETUP_LET */;
  32887. registerBinding(bindings, node.argument, type);
  32888. }
  32889. else if (node.type === 'ObjectPattern') {
  32890. walkObjectPattern(node, bindings, isConst);
  32891. }
  32892. else if (node.type === 'ArrayPattern') {
  32893. walkArrayPattern(node, bindings, isConst);
  32894. }
  32895. else if (node.type === 'AssignmentPattern') {
  32896. if (node.left.type === 'Identifier') {
  32897. const type = isDefineCall
  32898. ? "setup-const" /* BindingTypes.SETUP_CONST */
  32899. : isConst
  32900. ? "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */
  32901. : "setup-let" /* BindingTypes.SETUP_LET */;
  32902. registerBinding(bindings, node.left, type);
  32903. }
  32904. else {
  32905. walkPattern(node.left, bindings, isConst);
  32906. }
  32907. }
  32908. }
  32909. function recordType(node, declaredTypes) {
  32910. if (node.type === 'TSInterfaceDeclaration') {
  32911. declaredTypes[node.id.name] = [`Object`];
  32912. }
  32913. else if (node.type === 'TSTypeAliasDeclaration') {
  32914. declaredTypes[node.id.name] = inferRuntimeType(node.typeAnnotation, declaredTypes);
  32915. }
  32916. else if (node.type === 'ExportNamedDeclaration' && node.declaration) {
  32917. recordType(node.declaration, declaredTypes);
  32918. }
  32919. }
  32920. function extractRuntimeProps(node, props, declaredTypes, isProd) {
  32921. const members = node.type === 'TSTypeLiteral' ? node.members : node.body;
  32922. for (const m of members) {
  32923. if ((m.type === 'TSPropertySignature' || m.type === 'TSMethodSignature') &&
  32924. m.key.type === 'Identifier') {
  32925. let type;
  32926. if (m.type === 'TSMethodSignature') {
  32927. type = ['Function'];
  32928. }
  32929. else if (m.typeAnnotation) {
  32930. type = inferRuntimeType(m.typeAnnotation.typeAnnotation, declaredTypes);
  32931. }
  32932. props[m.key.name] = {
  32933. key: m.key.name,
  32934. required: !m.optional,
  32935. type: type || [`null`]
  32936. };
  32937. }
  32938. }
  32939. }
  32940. function inferRuntimeType(node, declaredTypes) {
  32941. switch (node.type) {
  32942. case 'TSStringKeyword':
  32943. return ['String'];
  32944. case 'TSNumberKeyword':
  32945. return ['Number'];
  32946. case 'TSBooleanKeyword':
  32947. return ['Boolean'];
  32948. case 'TSObjectKeyword':
  32949. return ['Object'];
  32950. case 'TSTypeLiteral':
  32951. // TODO (nice to have) generate runtime property validation
  32952. return ['Object'];
  32953. case 'TSFunctionType':
  32954. return ['Function'];
  32955. case 'TSArrayType':
  32956. case 'TSTupleType':
  32957. // TODO (nice to have) generate runtime element type/length checks
  32958. return ['Array'];
  32959. case 'TSLiteralType':
  32960. switch (node.literal.type) {
  32961. case 'StringLiteral':
  32962. return ['String'];
  32963. case 'BooleanLiteral':
  32964. return ['Boolean'];
  32965. case 'NumericLiteral':
  32966. case 'BigIntLiteral':
  32967. return ['Number'];
  32968. default:
  32969. return [`null`];
  32970. }
  32971. case 'TSTypeReference':
  32972. if (node.typeName.type === 'Identifier') {
  32973. if (declaredTypes[node.typeName.name]) {
  32974. return declaredTypes[node.typeName.name];
  32975. }
  32976. switch (node.typeName.name) {
  32977. case 'Array':
  32978. case 'Function':
  32979. case 'Object':
  32980. case 'Set':
  32981. case 'Map':
  32982. case 'WeakSet':
  32983. case 'WeakMap':
  32984. case 'Date':
  32985. case 'Promise':
  32986. return [node.typeName.name];
  32987. case 'Record':
  32988. case 'Partial':
  32989. case 'Readonly':
  32990. case 'Pick':
  32991. case 'Omit':
  32992. case 'Exclude':
  32993. case 'Extract':
  32994. case 'Required':
  32995. case 'InstanceType':
  32996. return ['Object'];
  32997. }
  32998. }
  32999. return [`null`];
  33000. case 'TSParenthesizedType':
  33001. return inferRuntimeType(node.typeAnnotation, declaredTypes);
  33002. case 'TSUnionType':
  33003. return [
  33004. ...new Set([].concat(...node.types.map(t => inferRuntimeType(t, declaredTypes))))
  33005. ];
  33006. case 'TSIntersectionType':
  33007. return ['Object'];
  33008. case 'TSSymbolKeyword':
  33009. return ['Symbol'];
  33010. default:
  33011. return [`null`]; // no runtime check
  33012. }
  33013. }
  33014. function toRuntimeTypeString(types) {
  33015. return types.length > 1 ? `[${types.join(', ')}]` : types[0];
  33016. }
  33017. function extractRuntimeEmits(node, emits) {
  33018. if (node.type === 'TSTypeLiteral' || node.type === 'TSInterfaceBody') {
  33019. const members = node.type === 'TSTypeLiteral' ? node.members : node.body;
  33020. for (let t of members) {
  33021. if (t.type === 'TSCallSignatureDeclaration') {
  33022. extractEventNames(t.parameters[0], emits);
  33023. }
  33024. }
  33025. return;
  33026. }
  33027. else {
  33028. extractEventNames(node.parameters[0], emits);
  33029. }
  33030. }
  33031. function extractEventNames(eventName, emits) {
  33032. if (eventName.type === 'Identifier' &&
  33033. eventName.typeAnnotation &&
  33034. eventName.typeAnnotation.type === 'TSTypeAnnotation') {
  33035. const typeNode = eventName.typeAnnotation.typeAnnotation;
  33036. if (typeNode.type === 'TSLiteralType') {
  33037. if (typeNode.literal.type !== 'UnaryExpression') {
  33038. emits.add(String(typeNode.literal.value));
  33039. }
  33040. }
  33041. else if (typeNode.type === 'TSUnionType') {
  33042. for (const t of typeNode.types) {
  33043. if (t.type === 'TSLiteralType' &&
  33044. t.literal.type !== 'UnaryExpression') {
  33045. emits.add(String(t.literal.value));
  33046. }
  33047. }
  33048. }
  33049. }
  33050. }
  33051. function genRuntimeEmits(emits) {
  33052. return emits.size
  33053. ? `\n emits: [${Array.from(emits)
  33054. .map(p => JSON.stringify(p))
  33055. .join(', ')}],`
  33056. : ``;
  33057. }
  33058. function isCallOf(node, test) {
  33059. return !!(node &&
  33060. test &&
  33061. node.type === 'CallExpression' &&
  33062. node.callee.type === 'Identifier' &&
  33063. (typeof test === 'string'
  33064. ? node.callee.name === test
  33065. : test(node.callee.name)));
  33066. }
  33067. function canNeverBeRef(node, userReactiveImport) {
  33068. if (isCallOf(node, userReactiveImport)) {
  33069. return true;
  33070. }
  33071. switch (node.type) {
  33072. case 'UnaryExpression':
  33073. case 'BinaryExpression':
  33074. case 'ArrayExpression':
  33075. case 'ObjectExpression':
  33076. case 'FunctionExpression':
  33077. case 'ArrowFunctionExpression':
  33078. case 'UpdateExpression':
  33079. case 'ClassExpression':
  33080. case 'TaggedTemplateExpression':
  33081. return true;
  33082. case 'SequenceExpression':
  33083. return canNeverBeRef(node.expressions[node.expressions.length - 1], userReactiveImport);
  33084. default:
  33085. if (node.type.endsWith('Literal')) {
  33086. return true;
  33087. }
  33088. return false;
  33089. }
  33090. }
  33091. /**
  33092. * Analyze bindings in normal `<script>`
  33093. * Note that `compileScriptSetup` already analyzes bindings as part of its
  33094. * compilation process so this should only be used on single `<script>` SFCs.
  33095. */
  33096. function analyzeScriptBindings(ast) {
  33097. for (const node of ast) {
  33098. if (node.type === 'ExportDefaultDeclaration' &&
  33099. node.declaration.type === 'ObjectExpression') {
  33100. return analyzeBindingsFromOptions(node.declaration);
  33101. }
  33102. }
  33103. return {};
  33104. }
  33105. function analyzeBindingsFromOptions(node) {
  33106. const bindings = {};
  33107. // #3270, #3275
  33108. // mark non-script-setup so we don't resolve components/directives from these
  33109. Object.defineProperty(bindings, '__isScriptSetup', {
  33110. enumerable: false,
  33111. value: false
  33112. });
  33113. for (const property of node.properties) {
  33114. if (property.type === 'ObjectProperty' &&
  33115. !property.computed &&
  33116. property.key.type === 'Identifier') {
  33117. // props
  33118. if (property.key.name === 'props') {
  33119. // props: ['foo']
  33120. // props: { foo: ... }
  33121. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  33122. bindings[key] = "props" /* BindingTypes.PROPS */;
  33123. }
  33124. }
  33125. // inject
  33126. else if (property.key.name === 'inject') {
  33127. // inject: ['foo']
  33128. // inject: { foo: {} }
  33129. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  33130. bindings[key] = "options" /* BindingTypes.OPTIONS */;
  33131. }
  33132. }
  33133. // computed & methods
  33134. else if (property.value.type === 'ObjectExpression' &&
  33135. (property.key.name === 'computed' || property.key.name === 'methods')) {
  33136. // methods: { foo() {} }
  33137. // computed: { foo() {} }
  33138. for (const key of getObjectExpressionKeys(property.value)) {
  33139. bindings[key] = "options" /* BindingTypes.OPTIONS */;
  33140. }
  33141. }
  33142. }
  33143. // setup & data
  33144. else if (property.type === 'ObjectMethod' &&
  33145. property.key.type === 'Identifier' &&
  33146. (property.key.name === 'setup' || property.key.name === 'data')) {
  33147. for (const bodyItem of property.body.body) {
  33148. // setup() {
  33149. // return {
  33150. // foo: null
  33151. // }
  33152. // }
  33153. if (bodyItem.type === 'ReturnStatement' &&
  33154. bodyItem.argument &&
  33155. bodyItem.argument.type === 'ObjectExpression') {
  33156. for (const key of getObjectExpressionKeys(bodyItem.argument)) {
  33157. bindings[key] =
  33158. property.key.name === 'setup'
  33159. ? "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */
  33160. : "data" /* BindingTypes.DATA */;
  33161. }
  33162. }
  33163. }
  33164. }
  33165. }
  33166. return bindings;
  33167. }
  33168. function getObjectExpressionKeys(node) {
  33169. const keys = [];
  33170. for (const prop of node.properties) {
  33171. if (prop.type === 'SpreadElement')
  33172. continue;
  33173. const key = resolveObjectKey(prop.key, prop.computed);
  33174. if (key)
  33175. keys.push(String(key));
  33176. }
  33177. return keys;
  33178. }
  33179. function getArrayExpressionKeys(node) {
  33180. const keys = [];
  33181. for (const element of node.elements) {
  33182. if (element && element.type === 'StringLiteral') {
  33183. keys.push(element.value);
  33184. }
  33185. }
  33186. return keys;
  33187. }
  33188. function getObjectOrArrayExpressionKeys(value) {
  33189. if (value.type === 'ArrayExpression') {
  33190. return getArrayExpressionKeys(value);
  33191. }
  33192. if (value.type === 'ObjectExpression') {
  33193. return getObjectExpressionKeys(value);
  33194. }
  33195. return [];
  33196. }
  33197. const templateUsageCheckCache = createCache();
  33198. function resolveTemplateUsageCheckString(sfc) {
  33199. const { content, ast } = sfc.template;
  33200. const cached = templateUsageCheckCache.get(content);
  33201. if (cached) {
  33202. return cached;
  33203. }
  33204. let code = '';
  33205. transform$1(createRoot([ast]), {
  33206. nodeTransforms: [
  33207. node => {
  33208. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  33209. if (!parserOptions.isNativeTag(node.tag) &&
  33210. !parserOptions.isBuiltInComponent(node.tag)) {
  33211. code += `,${camelize(node.tag)},${capitalize$1(camelize(node.tag))}`;
  33212. }
  33213. for (let i = 0; i < node.props.length; i++) {
  33214. const prop = node.props[i];
  33215. if (prop.type === 7 /* NodeTypes.DIRECTIVE */) {
  33216. if (!isBuiltInDir(prop.name)) {
  33217. code += `,v${capitalize$1(camelize(prop.name))}`;
  33218. }
  33219. if (prop.exp) {
  33220. code += `,${processExp(prop.exp.content, prop.name)}`;
  33221. }
  33222. }
  33223. }
  33224. }
  33225. else if (node.type === 5 /* NodeTypes.INTERPOLATION */) {
  33226. code += `,${processExp(node.content.content)}`;
  33227. }
  33228. }
  33229. ]
  33230. });
  33231. code += ';';
  33232. templateUsageCheckCache.set(content, code);
  33233. return code;
  33234. }
  33235. const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
  33236. function processExp(exp, dir) {
  33237. if (/ as\s+\w|<.*>|:/.test(exp)) {
  33238. if (dir === 'slot') {
  33239. exp = `(${exp})=>{}`;
  33240. }
  33241. else if (dir === 'on') {
  33242. exp = `()=>{return ${exp}}`;
  33243. }
  33244. else if (dir === 'for') {
  33245. const inMatch = exp.match(forAliasRE);
  33246. if (inMatch) {
  33247. const [, LHS, RHS] = inMatch;
  33248. return processExp(`(${LHS})=>{}`) + processExp(RHS);
  33249. }
  33250. }
  33251. let ret = '';
  33252. // has potential type cast or generic arguments that uses types
  33253. const ast = parseExpression_1(exp, { plugins: ['typescript'] });
  33254. walkIdentifiers(ast, node => {
  33255. ret += `,` + node.name;
  33256. });
  33257. return ret;
  33258. }
  33259. return stripStrings(exp);
  33260. }
  33261. function stripStrings(exp) {
  33262. return exp
  33263. .replace(/'[^']*'|"[^"]*"/g, '')
  33264. .replace(/`[^`]+`/g, stripTemplateString);
  33265. }
  33266. function stripTemplateString(str) {
  33267. const interpMatch = str.match(/\${[^}]+}/g);
  33268. if (interpMatch) {
  33269. return interpMatch.map(m => m.slice(2, -1)).join(',');
  33270. }
  33271. return '';
  33272. }
  33273. function isImportUsed(local, sfc) {
  33274. return new RegExp(
  33275. // #4274 escape $ since it's a special char in regex
  33276. // (and is the only regex special char that is valid in identifiers)
  33277. `[^\\w$_]${local.replace(/\$/g, '\\$')}[^\\w$_]`).test(resolveTemplateUsageCheckString(sfc));
  33278. }
  33279. /**
  33280. * Note: this comparison assumes the prev/next script are already identical,
  33281. * and only checks the special case where <script setup lang="ts"> unused import
  33282. * pruning result changes due to template changes.
  33283. */
  33284. function hmrShouldReload(prevImports, next) {
  33285. if (!next.scriptSetup ||
  33286. (next.scriptSetup.lang !== 'ts' && next.scriptSetup.lang !== 'tsx')) {
  33287. return false;
  33288. }
  33289. // for each previous import, check if its used status remain the same based on
  33290. // the next descriptor's template
  33291. for (const key in prevImports) {
  33292. // if an import was previous unused, but now is used, we need to force
  33293. // reload so that the script now includes that import.
  33294. if (!prevImports[key].isUsedInTemplate && isImportUsed(key, next)) {
  33295. return true;
  33296. }
  33297. }
  33298. return false;
  33299. }
  33300. function resolveObjectKey(node, computed) {
  33301. switch (node.type) {
  33302. case 'StringLiteral':
  33303. case 'NumericLiteral':
  33304. return node.value;
  33305. case 'Identifier':
  33306. if (!computed)
  33307. return node.name;
  33308. }
  33309. return undefined;
  33310. }
  33311. const DEFAULT_FILENAME = 'anonymous.vue';
  33312. const sourceToSFC = createCache();
  33313. function parse$5(source, { sourceMap = true, filename = DEFAULT_FILENAME, sourceRoot = '', pad = false, ignoreEmpty = true, compiler = CompilerDOM } = {}) {
  33314. const sourceKey = source + sourceMap + filename + sourceRoot + pad + compiler.parse;
  33315. const cache = sourceToSFC.get(sourceKey);
  33316. if (cache) {
  33317. return cache;
  33318. }
  33319. const descriptor = {
  33320. filename,
  33321. source,
  33322. template: null,
  33323. script: null,
  33324. scriptSetup: null,
  33325. styles: [],
  33326. customBlocks: [],
  33327. cssVars: [],
  33328. slotted: false,
  33329. shouldForceReload: prevImports => hmrShouldReload(prevImports, descriptor)
  33330. };
  33331. const errors = [];
  33332. const ast = compiler.parse(source, {
  33333. // there are no components at SFC parsing level
  33334. isNativeTag: () => true,
  33335. // preserve all whitespaces
  33336. isPreTag: () => true,
  33337. getTextMode: ({ tag, props }, parent) => {
  33338. // all top level elements except <template> are parsed as raw text
  33339. // containers
  33340. if ((!parent && tag !== 'template') ||
  33341. // <template lang="xxx"> should also be treated as raw text
  33342. (tag === 'template' &&
  33343. props.some(p => p.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  33344. p.name === 'lang' &&
  33345. p.value &&
  33346. p.value.content &&
  33347. p.value.content !== 'html'))) {
  33348. return 2 /* TextModes.RAWTEXT */;
  33349. }
  33350. else {
  33351. return 0 /* TextModes.DATA */;
  33352. }
  33353. },
  33354. onError: e => {
  33355. errors.push(e);
  33356. }
  33357. });
  33358. ast.children.forEach(node => {
  33359. if (node.type !== 1 /* NodeTypes.ELEMENT */) {
  33360. return;
  33361. }
  33362. // we only want to keep the nodes that are not empty (when the tag is not a template)
  33363. if (ignoreEmpty &&
  33364. node.tag !== 'template' &&
  33365. isEmpty(node) &&
  33366. !hasSrc(node)) {
  33367. return;
  33368. }
  33369. switch (node.tag) {
  33370. case 'template':
  33371. if (!descriptor.template) {
  33372. const templateBlock = (descriptor.template = createBlock(node, source, false));
  33373. templateBlock.ast = node;
  33374. // warn against 2.x <template functional>
  33375. if (templateBlock.attrs.functional) {
  33376. const err = new SyntaxError(`<template functional> is no longer supported in Vue 3, since ` +
  33377. `functional components no longer have significant performance ` +
  33378. `difference from stateful ones. Just use a normal <template> ` +
  33379. `instead.`);
  33380. err.loc = node.props.find(p => p.name === 'functional').loc;
  33381. errors.push(err);
  33382. }
  33383. }
  33384. else {
  33385. errors.push(createDuplicateBlockError(node));
  33386. }
  33387. break;
  33388. case 'script':
  33389. const scriptBlock = createBlock(node, source, pad);
  33390. const isSetup = !!scriptBlock.attrs.setup;
  33391. if (isSetup && !descriptor.scriptSetup) {
  33392. descriptor.scriptSetup = scriptBlock;
  33393. break;
  33394. }
  33395. if (!isSetup && !descriptor.script) {
  33396. descriptor.script = scriptBlock;
  33397. break;
  33398. }
  33399. errors.push(createDuplicateBlockError(node, isSetup));
  33400. break;
  33401. case 'style':
  33402. const styleBlock = createBlock(node, source, pad);
  33403. if (styleBlock.attrs.vars) {
  33404. errors.push(new SyntaxError(`<style vars> has been replaced by a new proposal: ` +
  33405. `https://github.com/vuejs/rfcs/pull/231`));
  33406. }
  33407. descriptor.styles.push(styleBlock);
  33408. break;
  33409. default:
  33410. descriptor.customBlocks.push(createBlock(node, source, pad));
  33411. break;
  33412. }
  33413. });
  33414. if (!descriptor.template && !descriptor.script && !descriptor.scriptSetup) {
  33415. errors.push(new SyntaxError(`At least one <template> or <script> is required in a single file component.`));
  33416. }
  33417. if (descriptor.scriptSetup) {
  33418. if (descriptor.scriptSetup.src) {
  33419. errors.push(new SyntaxError(`<script setup> cannot use the "src" attribute because ` +
  33420. `its syntax will be ambiguous outside of the component.`));
  33421. descriptor.scriptSetup = null;
  33422. }
  33423. if (descriptor.script && descriptor.script.src) {
  33424. errors.push(new SyntaxError(`<script> cannot use the "src" attribute when <script setup> is ` +
  33425. `also present because they must be processed together.`));
  33426. descriptor.script = null;
  33427. }
  33428. }
  33429. if (sourceMap) {
  33430. const genMap = (block) => {
  33431. if (block && !block.src) {
  33432. block.map = generateSourceMap(filename, source, block.content, sourceRoot, !pad || block.type === 'template' ? block.loc.start.line - 1 : 0);
  33433. }
  33434. };
  33435. genMap(descriptor.template);
  33436. genMap(descriptor.script);
  33437. descriptor.styles.forEach(genMap);
  33438. descriptor.customBlocks.forEach(genMap);
  33439. }
  33440. // parse CSS vars
  33441. descriptor.cssVars = parseCssVars(descriptor);
  33442. // check if the SFC uses :slotted
  33443. const slottedRE = /(?:::v-|:)slotted\(/;
  33444. descriptor.slotted = descriptor.styles.some(s => s.scoped && slottedRE.test(s.content));
  33445. const result = {
  33446. descriptor,
  33447. errors
  33448. };
  33449. sourceToSFC.set(sourceKey, result);
  33450. return result;
  33451. }
  33452. function createDuplicateBlockError(node, isScriptSetup = false) {
  33453. const err = new SyntaxError(`Single file component can contain only one <${node.tag}${isScriptSetup ? ` setup` : ``}> element`);
  33454. err.loc = node.loc;
  33455. return err;
  33456. }
  33457. function createBlock(node, source, pad) {
  33458. const type = node.tag;
  33459. let { start, end } = node.loc;
  33460. let content = '';
  33461. if (node.children.length) {
  33462. start = node.children[0].loc.start;
  33463. end = node.children[node.children.length - 1].loc.end;
  33464. content = source.slice(start.offset, end.offset);
  33465. }
  33466. else {
  33467. const offset = node.loc.source.indexOf(`</`);
  33468. if (offset > -1) {
  33469. start = {
  33470. line: start.line,
  33471. column: start.column + offset,
  33472. offset: start.offset + offset
  33473. };
  33474. }
  33475. end = Object.assign({}, start);
  33476. }
  33477. const loc = {
  33478. source: content,
  33479. start,
  33480. end
  33481. };
  33482. const attrs = {};
  33483. const block = {
  33484. type,
  33485. content,
  33486. loc,
  33487. attrs
  33488. };
  33489. if (pad) {
  33490. block.content = padContent(source, block, pad) + block.content;
  33491. }
  33492. node.props.forEach(p => {
  33493. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  33494. attrs[p.name] = p.value ? p.value.content || true : true;
  33495. if (p.name === 'lang') {
  33496. block.lang = p.value && p.value.content;
  33497. }
  33498. else if (p.name === 'src') {
  33499. block.src = p.value && p.value.content;
  33500. }
  33501. else if (type === 'style') {
  33502. if (p.name === 'scoped') {
  33503. block.scoped = true;
  33504. }
  33505. else if (p.name === 'module') {
  33506. block.module = attrs[p.name];
  33507. }
  33508. }
  33509. else if (type === 'script' && p.name === 'setup') {
  33510. block.setup = attrs.setup;
  33511. }
  33512. }
  33513. });
  33514. return block;
  33515. }
  33516. const splitRE = /\r?\n/g;
  33517. const emptyRE = /^(?:\/\/)?\s*$/;
  33518. const replaceRE = /./g;
  33519. function generateSourceMap(filename, source, generated, sourceRoot, lineOffset) {
  33520. const map = new SourceMapGenerator$6({
  33521. file: filename.replace(/\\/g, '/'),
  33522. sourceRoot: sourceRoot.replace(/\\/g, '/')
  33523. });
  33524. map.setSourceContent(filename, source);
  33525. generated.split(splitRE).forEach((line, index) => {
  33526. if (!emptyRE.test(line)) {
  33527. const originalLine = index + 1 + lineOffset;
  33528. const generatedLine = index + 1;
  33529. for (let i = 0; i < line.length; i++) {
  33530. if (!/\s/.test(line[i])) {
  33531. map.addMapping({
  33532. source: filename,
  33533. original: {
  33534. line: originalLine,
  33535. column: i
  33536. },
  33537. generated: {
  33538. line: generatedLine,
  33539. column: i
  33540. }
  33541. });
  33542. }
  33543. }
  33544. }
  33545. });
  33546. return JSON.parse(map.toString());
  33547. }
  33548. function padContent(content, block, pad) {
  33549. content = content.slice(0, block.loc.start.offset);
  33550. if (pad === 'space') {
  33551. return content.replace(replaceRE, ' ');
  33552. }
  33553. else {
  33554. const offset = content.split(splitRE).length;
  33555. const padChar = block.type === 'script' && !block.lang ? '//\n' : '\n';
  33556. return Array(offset).join(padChar);
  33557. }
  33558. }
  33559. function hasSrc(node) {
  33560. return node.props.some(p => {
  33561. if (p.type !== 6 /* NodeTypes.ATTRIBUTE */) {
  33562. return false;
  33563. }
  33564. return p.name === 'src';
  33565. });
  33566. }
  33567. /**
  33568. * Returns true if the node has no children
  33569. * once the empty text nodes (trimmed content) have been filtered out.
  33570. */
  33571. function isEmpty(node) {
  33572. for (let i = 0; i < node.children.length; i++) {
  33573. const child = node.children[i];
  33574. if (child.type !== 2 /* NodeTypes.TEXT */ || child.content.trim() !== '') {
  33575. return false;
  33576. }
  33577. }
  33578. return true;
  33579. }
  33580. var picocolors = {exports: {}};
  33581. // MIT lisence
  33582. // from https://github.com/substack/tty-browserify/blob/1ba769a6429d242f36226538835b4034bf6b7886/index.js
  33583. function isatty() {
  33584. return false;
  33585. }
  33586. function ReadStream() {
  33587. throw new Error('tty.ReadStream is not implemented');
  33588. }
  33589. function WriteStream() {
  33590. throw new Error('tty.ReadStream is not implemented');
  33591. }
  33592. var _polyfillNode_tty = {
  33593. isatty: isatty,
  33594. ReadStream: ReadStream,
  33595. WriteStream: WriteStream
  33596. };
  33597. var _polyfillNode_tty$1 = /*#__PURE__*/Object.freeze({
  33598. __proto__: null,
  33599. ReadStream: ReadStream,
  33600. WriteStream: WriteStream,
  33601. default: _polyfillNode_tty,
  33602. isatty: isatty
  33603. });
  33604. var require$$0 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_tty$1);
  33605. let tty = require$$0;
  33606. let isColorSupported =
  33607. !("NO_COLOR" in ({}) || browser$1.argv.includes("--no-color")) &&
  33608. ("FORCE_COLOR" in ({}) ||
  33609. browser$1.argv.includes("--color") ||
  33610. "" === "win32" ||
  33611. (tty.isatty(1) && browser$1.env.TERM !== "dumb") ||
  33612. "CI" in ({}));
  33613. let formatter =
  33614. (open, close, replace = open) =>
  33615. input => {
  33616. let string = "" + input;
  33617. let index = string.indexOf(close, open.length);
  33618. return ~index
  33619. ? open + replaceClose(string, close, replace, index) + close
  33620. : open + string + close
  33621. };
  33622. let replaceClose = (string, close, replace, index) => {
  33623. let start = string.substring(0, index) + replace;
  33624. let end = string.substring(index + close.length);
  33625. let nextIndex = end.indexOf(close);
  33626. return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end
  33627. };
  33628. let createColors = (enabled = isColorSupported) => ({
  33629. isColorSupported: enabled,
  33630. reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String,
  33631. bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String,
  33632. dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String,
  33633. italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String,
  33634. underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String,
  33635. inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String,
  33636. hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String,
  33637. strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String,
  33638. black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String,
  33639. red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String,
  33640. green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String,
  33641. yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String,
  33642. blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String,
  33643. magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String,
  33644. cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String,
  33645. white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String,
  33646. gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String,
  33647. bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String,
  33648. bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String,
  33649. bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String,
  33650. bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String,
  33651. bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String,
  33652. bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String,
  33653. bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String,
  33654. bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String,
  33655. });
  33656. picocolors.exports = createColors();
  33657. picocolors.exports.createColors = createColors;
  33658. const SINGLE_QUOTE = "'".charCodeAt(0);
  33659. const DOUBLE_QUOTE = '"'.charCodeAt(0);
  33660. const BACKSLASH = '\\'.charCodeAt(0);
  33661. const SLASH = '/'.charCodeAt(0);
  33662. const NEWLINE = '\n'.charCodeAt(0);
  33663. const SPACE = ' '.charCodeAt(0);
  33664. const FEED = '\f'.charCodeAt(0);
  33665. const TAB = '\t'.charCodeAt(0);
  33666. const CR = '\r'.charCodeAt(0);
  33667. const OPEN_SQUARE = '['.charCodeAt(0);
  33668. const CLOSE_SQUARE = ']'.charCodeAt(0);
  33669. const OPEN_PARENTHESES = '('.charCodeAt(0);
  33670. const CLOSE_PARENTHESES = ')'.charCodeAt(0);
  33671. const OPEN_CURLY = '{'.charCodeAt(0);
  33672. const CLOSE_CURLY = '}'.charCodeAt(0);
  33673. const SEMICOLON = ';'.charCodeAt(0);
  33674. const ASTERISK = '*'.charCodeAt(0);
  33675. const COLON = ':'.charCodeAt(0);
  33676. const AT = '@'.charCodeAt(0);
  33677. const RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g;
  33678. const RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g;
  33679. const RE_BAD_BRACKET = /.[\n"'(/\\]/;
  33680. const RE_HEX_ESCAPE = /[\da-f]/i;
  33681. var tokenize$1 = function tokenizer(input, options = {}) {
  33682. let css = input.css.valueOf();
  33683. let ignore = options.ignoreErrors;
  33684. let code, next, quote, content, escape;
  33685. let escaped, escapePos, prev, n, currentToken;
  33686. let length = css.length;
  33687. let pos = 0;
  33688. let buffer = [];
  33689. let returned = [];
  33690. function position() {
  33691. return pos
  33692. }
  33693. function unclosed(what) {
  33694. throw input.error('Unclosed ' + what, pos)
  33695. }
  33696. function endOfFile() {
  33697. return returned.length === 0 && pos >= length
  33698. }
  33699. function nextToken(opts) {
  33700. if (returned.length) return returned.pop()
  33701. if (pos >= length) return
  33702. let ignoreUnclosed = opts ? opts.ignoreUnclosed : false;
  33703. code = css.charCodeAt(pos);
  33704. switch (code) {
  33705. case NEWLINE:
  33706. case SPACE:
  33707. case TAB:
  33708. case CR:
  33709. case FEED: {
  33710. next = pos;
  33711. do {
  33712. next += 1;
  33713. code = css.charCodeAt(next);
  33714. } while (
  33715. code === SPACE ||
  33716. code === NEWLINE ||
  33717. code === TAB ||
  33718. code === CR ||
  33719. code === FEED
  33720. )
  33721. currentToken = ['space', css.slice(pos, next)];
  33722. pos = next - 1;
  33723. break
  33724. }
  33725. case OPEN_SQUARE:
  33726. case CLOSE_SQUARE:
  33727. case OPEN_CURLY:
  33728. case CLOSE_CURLY:
  33729. case COLON:
  33730. case SEMICOLON:
  33731. case CLOSE_PARENTHESES: {
  33732. let controlChar = String.fromCharCode(code);
  33733. currentToken = [controlChar, controlChar, pos];
  33734. break
  33735. }
  33736. case OPEN_PARENTHESES: {
  33737. prev = buffer.length ? buffer.pop()[1] : '';
  33738. n = css.charCodeAt(pos + 1);
  33739. if (
  33740. prev === 'url' &&
  33741. n !== SINGLE_QUOTE &&
  33742. n !== DOUBLE_QUOTE &&
  33743. n !== SPACE &&
  33744. n !== NEWLINE &&
  33745. n !== TAB &&
  33746. n !== FEED &&
  33747. n !== CR
  33748. ) {
  33749. next = pos;
  33750. do {
  33751. escaped = false;
  33752. next = css.indexOf(')', next + 1);
  33753. if (next === -1) {
  33754. if (ignore || ignoreUnclosed) {
  33755. next = pos;
  33756. break
  33757. } else {
  33758. unclosed('bracket');
  33759. }
  33760. }
  33761. escapePos = next;
  33762. while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
  33763. escapePos -= 1;
  33764. escaped = !escaped;
  33765. }
  33766. } while (escaped)
  33767. currentToken = ['brackets', css.slice(pos, next + 1), pos, next];
  33768. pos = next;
  33769. } else {
  33770. next = css.indexOf(')', pos + 1);
  33771. content = css.slice(pos, next + 1);
  33772. if (next === -1 || RE_BAD_BRACKET.test(content)) {
  33773. currentToken = ['(', '(', pos];
  33774. } else {
  33775. currentToken = ['brackets', content, pos, next];
  33776. pos = next;
  33777. }
  33778. }
  33779. break
  33780. }
  33781. case SINGLE_QUOTE:
  33782. case DOUBLE_QUOTE: {
  33783. quote = code === SINGLE_QUOTE ? "'" : '"';
  33784. next = pos;
  33785. do {
  33786. escaped = false;
  33787. next = css.indexOf(quote, next + 1);
  33788. if (next === -1) {
  33789. if (ignore || ignoreUnclosed) {
  33790. next = pos + 1;
  33791. break
  33792. } else {
  33793. unclosed('string');
  33794. }
  33795. }
  33796. escapePos = next;
  33797. while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
  33798. escapePos -= 1;
  33799. escaped = !escaped;
  33800. }
  33801. } while (escaped)
  33802. currentToken = ['string', css.slice(pos, next + 1), pos, next];
  33803. pos = next;
  33804. break
  33805. }
  33806. case AT: {
  33807. RE_AT_END.lastIndex = pos + 1;
  33808. RE_AT_END.test(css);
  33809. if (RE_AT_END.lastIndex === 0) {
  33810. next = css.length - 1;
  33811. } else {
  33812. next = RE_AT_END.lastIndex - 2;
  33813. }
  33814. currentToken = ['at-word', css.slice(pos, next + 1), pos, next];
  33815. pos = next;
  33816. break
  33817. }
  33818. case BACKSLASH: {
  33819. next = pos;
  33820. escape = true;
  33821. while (css.charCodeAt(next + 1) === BACKSLASH) {
  33822. next += 1;
  33823. escape = !escape;
  33824. }
  33825. code = css.charCodeAt(next + 1);
  33826. if (
  33827. escape &&
  33828. code !== SLASH &&
  33829. code !== SPACE &&
  33830. code !== NEWLINE &&
  33831. code !== TAB &&
  33832. code !== CR &&
  33833. code !== FEED
  33834. ) {
  33835. next += 1;
  33836. if (RE_HEX_ESCAPE.test(css.charAt(next))) {
  33837. while (RE_HEX_ESCAPE.test(css.charAt(next + 1))) {
  33838. next += 1;
  33839. }
  33840. if (css.charCodeAt(next + 1) === SPACE) {
  33841. next += 1;
  33842. }
  33843. }
  33844. }
  33845. currentToken = ['word', css.slice(pos, next + 1), pos, next];
  33846. pos = next;
  33847. break
  33848. }
  33849. default: {
  33850. if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) {
  33851. next = css.indexOf('*/', pos + 2) + 1;
  33852. if (next === 0) {
  33853. if (ignore || ignoreUnclosed) {
  33854. next = css.length;
  33855. } else {
  33856. unclosed('comment');
  33857. }
  33858. }
  33859. currentToken = ['comment', css.slice(pos, next + 1), pos, next];
  33860. pos = next;
  33861. } else {
  33862. RE_WORD_END.lastIndex = pos + 1;
  33863. RE_WORD_END.test(css);
  33864. if (RE_WORD_END.lastIndex === 0) {
  33865. next = css.length - 1;
  33866. } else {
  33867. next = RE_WORD_END.lastIndex - 2;
  33868. }
  33869. currentToken = ['word', css.slice(pos, next + 1), pos, next];
  33870. buffer.push(currentToken);
  33871. pos = next;
  33872. }
  33873. break
  33874. }
  33875. }
  33876. pos++;
  33877. return currentToken
  33878. }
  33879. function back(token) {
  33880. returned.push(token);
  33881. }
  33882. return {
  33883. back,
  33884. nextToken,
  33885. endOfFile,
  33886. position
  33887. }
  33888. };
  33889. let pico$1 = picocolors.exports;
  33890. let tokenizer$1 = tokenize$1;
  33891. let Input$5;
  33892. function registerInput(dependant) {
  33893. Input$5 = dependant;
  33894. }
  33895. const HIGHLIGHT_THEME = {
  33896. 'brackets': pico$1.cyan,
  33897. 'at-word': pico$1.cyan,
  33898. 'comment': pico$1.gray,
  33899. 'string': pico$1.green,
  33900. 'class': pico$1.yellow,
  33901. 'hash': pico$1.magenta,
  33902. 'call': pico$1.cyan,
  33903. '(': pico$1.cyan,
  33904. ')': pico$1.cyan,
  33905. '{': pico$1.yellow,
  33906. '}': pico$1.yellow,
  33907. '[': pico$1.yellow,
  33908. ']': pico$1.yellow,
  33909. ':': pico$1.yellow,
  33910. ';': pico$1.yellow
  33911. };
  33912. function getTokenType([type, value], processor) {
  33913. if (type === 'word') {
  33914. if (value[0] === '.') {
  33915. return 'class'
  33916. }
  33917. if (value[0] === '#') {
  33918. return 'hash'
  33919. }
  33920. }
  33921. if (!processor.endOfFile()) {
  33922. let next = processor.nextToken();
  33923. processor.back(next);
  33924. if (next[0] === 'brackets' || next[0] === '(') return 'call'
  33925. }
  33926. return type
  33927. }
  33928. function terminalHighlight$2(css) {
  33929. let processor = tokenizer$1(new Input$5(css), { ignoreErrors: true });
  33930. let result = '';
  33931. while (!processor.endOfFile()) {
  33932. let token = processor.nextToken();
  33933. let color = HIGHLIGHT_THEME[getTokenType(token, processor)];
  33934. if (color) {
  33935. result += token[1]
  33936. .split(/\r?\n/)
  33937. .map(i => color(i))
  33938. .join('\n');
  33939. } else {
  33940. result += token[1];
  33941. }
  33942. }
  33943. return result
  33944. }
  33945. terminalHighlight$2.registerInput = registerInput;
  33946. var terminalHighlight_1 = terminalHighlight$2;
  33947. let pico = picocolors.exports;
  33948. let terminalHighlight$1 = terminalHighlight_1;
  33949. let CssSyntaxError$3 = class CssSyntaxError extends Error {
  33950. constructor(message, line, column, source, file, plugin) {
  33951. super(message);
  33952. this.name = 'CssSyntaxError';
  33953. this.reason = message;
  33954. if (file) {
  33955. this.file = file;
  33956. }
  33957. if (source) {
  33958. this.source = source;
  33959. }
  33960. if (plugin) {
  33961. this.plugin = plugin;
  33962. }
  33963. if (typeof line !== 'undefined' && typeof column !== 'undefined') {
  33964. if (typeof line === 'number') {
  33965. this.line = line;
  33966. this.column = column;
  33967. } else {
  33968. this.line = line.line;
  33969. this.column = line.column;
  33970. this.endLine = column.line;
  33971. this.endColumn = column.column;
  33972. }
  33973. }
  33974. this.setMessage();
  33975. if (Error.captureStackTrace) {
  33976. Error.captureStackTrace(this, CssSyntaxError$3);
  33977. }
  33978. }
  33979. setMessage() {
  33980. this.message = this.plugin ? this.plugin + ': ' : '';
  33981. this.message += this.file ? this.file : '<css input>';
  33982. if (typeof this.line !== 'undefined') {
  33983. this.message += ':' + this.line + ':' + this.column;
  33984. }
  33985. this.message += ': ' + this.reason;
  33986. }
  33987. showSourceCode(color) {
  33988. if (!this.source) return ''
  33989. let css = this.source;
  33990. if (color == null) color = pico.isColorSupported;
  33991. if (terminalHighlight$1) {
  33992. if (color) css = terminalHighlight$1(css);
  33993. }
  33994. let lines = css.split(/\r?\n/);
  33995. let start = Math.max(this.line - 3, 0);
  33996. let end = Math.min(this.line + 2, lines.length);
  33997. let maxWidth = String(end).length;
  33998. let mark, aside;
  33999. if (color) {
  34000. let { bold, red, gray } = pico.createColors(true);
  34001. mark = text => bold(red(text));
  34002. aside = text => gray(text);
  34003. } else {
  34004. mark = aside = str => str;
  34005. }
  34006. return lines
  34007. .slice(start, end)
  34008. .map((line, index) => {
  34009. let number = start + 1 + index;
  34010. let gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | ';
  34011. if (number === this.line) {
  34012. let spacing =
  34013. aside(gutter.replace(/\d/g, ' ')) +
  34014. line.slice(0, this.column - 1).replace(/[^\t]/g, ' ');
  34015. return mark('>') + aside(gutter) + line + '\n ' + spacing + mark('^')
  34016. }
  34017. return ' ' + aside(gutter) + line
  34018. })
  34019. .join('\n')
  34020. }
  34021. toString() {
  34022. let code = this.showSourceCode();
  34023. if (code) {
  34024. code = '\n\n' + code + '\n';
  34025. }
  34026. return this.name + ': ' + this.message + code
  34027. }
  34028. };
  34029. var cssSyntaxError = CssSyntaxError$3;
  34030. CssSyntaxError$3.default = CssSyntaxError$3;
  34031. var symbols = {};
  34032. symbols.isClean = Symbol('isClean');
  34033. symbols.my = Symbol('my');
  34034. const DEFAULT_RAW = {
  34035. colon: ': ',
  34036. indent: ' ',
  34037. beforeDecl: '\n',
  34038. beforeRule: '\n',
  34039. beforeOpen: ' ',
  34040. beforeClose: '\n',
  34041. beforeComment: '\n',
  34042. after: '\n',
  34043. emptyBody: '',
  34044. commentLeft: ' ',
  34045. commentRight: ' ',
  34046. semicolon: false
  34047. };
  34048. function capitalize(str) {
  34049. return str[0].toUpperCase() + str.slice(1)
  34050. }
  34051. let Stringifier$2 = class Stringifier {
  34052. constructor(builder) {
  34053. this.builder = builder;
  34054. }
  34055. stringify(node, semicolon) {
  34056. /* c8 ignore start */
  34057. if (!this[node.type]) {
  34058. throw new Error(
  34059. 'Unknown AST node type ' +
  34060. node.type +
  34061. '. ' +
  34062. 'Maybe you need to change PostCSS stringifier.'
  34063. )
  34064. }
  34065. /* c8 ignore stop */
  34066. this[node.type](node, semicolon);
  34067. }
  34068. document(node) {
  34069. this.body(node);
  34070. }
  34071. root(node) {
  34072. this.body(node);
  34073. if (node.raws.after) this.builder(node.raws.after);
  34074. }
  34075. comment(node) {
  34076. let left = this.raw(node, 'left', 'commentLeft');
  34077. let right = this.raw(node, 'right', 'commentRight');
  34078. this.builder('/*' + left + node.text + right + '*/', node);
  34079. }
  34080. decl(node, semicolon) {
  34081. let between = this.raw(node, 'between', 'colon');
  34082. let string = node.prop + between + this.rawValue(node, 'value');
  34083. if (node.important) {
  34084. string += node.raws.important || ' !important';
  34085. }
  34086. if (semicolon) string += ';';
  34087. this.builder(string, node);
  34088. }
  34089. rule(node) {
  34090. this.block(node, this.rawValue(node, 'selector'));
  34091. if (node.raws.ownSemicolon) {
  34092. this.builder(node.raws.ownSemicolon, node, 'end');
  34093. }
  34094. }
  34095. atrule(node, semicolon) {
  34096. let name = '@' + node.name;
  34097. let params = node.params ? this.rawValue(node, 'params') : '';
  34098. if (typeof node.raws.afterName !== 'undefined') {
  34099. name += node.raws.afterName;
  34100. } else if (params) {
  34101. name += ' ';
  34102. }
  34103. if (node.nodes) {
  34104. this.block(node, name + params);
  34105. } else {
  34106. let end = (node.raws.between || '') + (semicolon ? ';' : '');
  34107. this.builder(name + params + end, node);
  34108. }
  34109. }
  34110. body(node) {
  34111. let last = node.nodes.length - 1;
  34112. while (last > 0) {
  34113. if (node.nodes[last].type !== 'comment') break
  34114. last -= 1;
  34115. }
  34116. let semicolon = this.raw(node, 'semicolon');
  34117. for (let i = 0; i < node.nodes.length; i++) {
  34118. let child = node.nodes[i];
  34119. let before = this.raw(child, 'before');
  34120. if (before) this.builder(before);
  34121. this.stringify(child, last !== i || semicolon);
  34122. }
  34123. }
  34124. block(node, start) {
  34125. let between = this.raw(node, 'between', 'beforeOpen');
  34126. this.builder(start + between + '{', node, 'start');
  34127. let after;
  34128. if (node.nodes && node.nodes.length) {
  34129. this.body(node);
  34130. after = this.raw(node, 'after');
  34131. } else {
  34132. after = this.raw(node, 'after', 'emptyBody');
  34133. }
  34134. if (after) this.builder(after);
  34135. this.builder('}', node, 'end');
  34136. }
  34137. raw(node, own, detect) {
  34138. let value;
  34139. if (!detect) detect = own;
  34140. // Already had
  34141. if (own) {
  34142. value = node.raws[own];
  34143. if (typeof value !== 'undefined') return value
  34144. }
  34145. let parent = node.parent;
  34146. if (detect === 'before') {
  34147. // Hack for first rule in CSS
  34148. if (!parent || (parent.type === 'root' && parent.first === node)) {
  34149. return ''
  34150. }
  34151. // `root` nodes in `document` should use only their own raws
  34152. if (parent && parent.type === 'document') {
  34153. return ''
  34154. }
  34155. }
  34156. // Floating child without parent
  34157. if (!parent) return DEFAULT_RAW[detect]
  34158. // Detect style by other nodes
  34159. let root = node.root();
  34160. if (!root.rawCache) root.rawCache = {};
  34161. if (typeof root.rawCache[detect] !== 'undefined') {
  34162. return root.rawCache[detect]
  34163. }
  34164. if (detect === 'before' || detect === 'after') {
  34165. return this.beforeAfter(node, detect)
  34166. } else {
  34167. let method = 'raw' + capitalize(detect);
  34168. if (this[method]) {
  34169. value = this[method](root, node);
  34170. } else {
  34171. root.walk(i => {
  34172. value = i.raws[own];
  34173. if (typeof value !== 'undefined') return false
  34174. });
  34175. }
  34176. }
  34177. if (typeof value === 'undefined') value = DEFAULT_RAW[detect];
  34178. root.rawCache[detect] = value;
  34179. return value
  34180. }
  34181. rawSemicolon(root) {
  34182. let value;
  34183. root.walk(i => {
  34184. if (i.nodes && i.nodes.length && i.last.type === 'decl') {
  34185. value = i.raws.semicolon;
  34186. if (typeof value !== 'undefined') return false
  34187. }
  34188. });
  34189. return value
  34190. }
  34191. rawEmptyBody(root) {
  34192. let value;
  34193. root.walk(i => {
  34194. if (i.nodes && i.nodes.length === 0) {
  34195. value = i.raws.after;
  34196. if (typeof value !== 'undefined') return false
  34197. }
  34198. });
  34199. return value
  34200. }
  34201. rawIndent(root) {
  34202. if (root.raws.indent) return root.raws.indent
  34203. let value;
  34204. root.walk(i => {
  34205. let p = i.parent;
  34206. if (p && p !== root && p.parent && p.parent === root) {
  34207. if (typeof i.raws.before !== 'undefined') {
  34208. let parts = i.raws.before.split('\n');
  34209. value = parts[parts.length - 1];
  34210. value = value.replace(/\S/g, '');
  34211. return false
  34212. }
  34213. }
  34214. });
  34215. return value
  34216. }
  34217. rawBeforeComment(root, node) {
  34218. let value;
  34219. root.walkComments(i => {
  34220. if (typeof i.raws.before !== 'undefined') {
  34221. value = i.raws.before;
  34222. if (value.includes('\n')) {
  34223. value = value.replace(/[^\n]+$/, '');
  34224. }
  34225. return false
  34226. }
  34227. });
  34228. if (typeof value === 'undefined') {
  34229. value = this.raw(node, null, 'beforeDecl');
  34230. } else if (value) {
  34231. value = value.replace(/\S/g, '');
  34232. }
  34233. return value
  34234. }
  34235. rawBeforeDecl(root, node) {
  34236. let value;
  34237. root.walkDecls(i => {
  34238. if (typeof i.raws.before !== 'undefined') {
  34239. value = i.raws.before;
  34240. if (value.includes('\n')) {
  34241. value = value.replace(/[^\n]+$/, '');
  34242. }
  34243. return false
  34244. }
  34245. });
  34246. if (typeof value === 'undefined') {
  34247. value = this.raw(node, null, 'beforeRule');
  34248. } else if (value) {
  34249. value = value.replace(/\S/g, '');
  34250. }
  34251. return value
  34252. }
  34253. rawBeforeRule(root) {
  34254. let value;
  34255. root.walk(i => {
  34256. if (i.nodes && (i.parent !== root || root.first !== i)) {
  34257. if (typeof i.raws.before !== 'undefined') {
  34258. value = i.raws.before;
  34259. if (value.includes('\n')) {
  34260. value = value.replace(/[^\n]+$/, '');
  34261. }
  34262. return false
  34263. }
  34264. }
  34265. });
  34266. if (value) value = value.replace(/\S/g, '');
  34267. return value
  34268. }
  34269. rawBeforeClose(root) {
  34270. let value;
  34271. root.walk(i => {
  34272. if (i.nodes && i.nodes.length > 0) {
  34273. if (typeof i.raws.after !== 'undefined') {
  34274. value = i.raws.after;
  34275. if (value.includes('\n')) {
  34276. value = value.replace(/[^\n]+$/, '');
  34277. }
  34278. return false
  34279. }
  34280. }
  34281. });
  34282. if (value) value = value.replace(/\S/g, '');
  34283. return value
  34284. }
  34285. rawBeforeOpen(root) {
  34286. let value;
  34287. root.walk(i => {
  34288. if (i.type !== 'decl') {
  34289. value = i.raws.between;
  34290. if (typeof value !== 'undefined') return false
  34291. }
  34292. });
  34293. return value
  34294. }
  34295. rawColon(root) {
  34296. let value;
  34297. root.walkDecls(i => {
  34298. if (typeof i.raws.between !== 'undefined') {
  34299. value = i.raws.between.replace(/[^\s:]/g, '');
  34300. return false
  34301. }
  34302. });
  34303. return value
  34304. }
  34305. beforeAfter(node, detect) {
  34306. let value;
  34307. if (node.type === 'decl') {
  34308. value = this.raw(node, null, 'beforeDecl');
  34309. } else if (node.type === 'comment') {
  34310. value = this.raw(node, null, 'beforeComment');
  34311. } else if (detect === 'before') {
  34312. value = this.raw(node, null, 'beforeRule');
  34313. } else {
  34314. value = this.raw(node, null, 'beforeClose');
  34315. }
  34316. let buf = node.parent;
  34317. let depth = 0;
  34318. while (buf && buf.type !== 'root') {
  34319. depth += 1;
  34320. buf = buf.parent;
  34321. }
  34322. if (value.includes('\n')) {
  34323. let indent = this.raw(node, null, 'indent');
  34324. if (indent.length) {
  34325. for (let step = 0; step < depth; step++) value += indent;
  34326. }
  34327. }
  34328. return value
  34329. }
  34330. rawValue(node, prop) {
  34331. let value = node[prop];
  34332. let raw = node.raws[prop];
  34333. if (raw && raw.value === value) {
  34334. return raw.raw
  34335. }
  34336. return value
  34337. }
  34338. };
  34339. var stringifier = Stringifier$2;
  34340. Stringifier$2.default = Stringifier$2;
  34341. let Stringifier$1 = stringifier;
  34342. function stringify$4(node, builder) {
  34343. let str = new Stringifier$1(builder);
  34344. str.stringify(node);
  34345. }
  34346. var stringify_1 = stringify$4;
  34347. stringify$4.default = stringify$4;
  34348. let { isClean: isClean$2, my: my$2 } = symbols;
  34349. let CssSyntaxError$2 = cssSyntaxError;
  34350. let Stringifier = stringifier;
  34351. let stringify$3 = stringify_1;
  34352. function cloneNode(obj, parent) {
  34353. let cloned = new obj.constructor();
  34354. for (let i in obj) {
  34355. if (!Object.prototype.hasOwnProperty.call(obj, i)) {
  34356. /* c8 ignore next 2 */
  34357. continue
  34358. }
  34359. if (i === 'proxyCache') continue
  34360. let value = obj[i];
  34361. let type = typeof value;
  34362. if (i === 'parent' && type === 'object') {
  34363. if (parent) cloned[i] = parent;
  34364. } else if (i === 'source') {
  34365. cloned[i] = value;
  34366. } else if (Array.isArray(value)) {
  34367. cloned[i] = value.map(j => cloneNode(j, cloned));
  34368. } else {
  34369. if (type === 'object' && value !== null) value = cloneNode(value);
  34370. cloned[i] = value;
  34371. }
  34372. }
  34373. return cloned
  34374. }
  34375. let Node$4 = class Node {
  34376. constructor(defaults = {}) {
  34377. this.raws = {};
  34378. this[isClean$2] = false;
  34379. this[my$2] = true;
  34380. for (let name in defaults) {
  34381. if (name === 'nodes') {
  34382. this.nodes = [];
  34383. for (let node of defaults[name]) {
  34384. if (typeof node.clone === 'function') {
  34385. this.append(node.clone());
  34386. } else {
  34387. this.append(node);
  34388. }
  34389. }
  34390. } else {
  34391. this[name] = defaults[name];
  34392. }
  34393. }
  34394. }
  34395. error(message, opts = {}) {
  34396. if (this.source) {
  34397. let { start, end } = this.rangeBy(opts);
  34398. return this.source.input.error(
  34399. message,
  34400. { line: start.line, column: start.column },
  34401. { line: end.line, column: end.column },
  34402. opts
  34403. )
  34404. }
  34405. return new CssSyntaxError$2(message)
  34406. }
  34407. warn(result, text, opts) {
  34408. let data = { node: this };
  34409. for (let i in opts) data[i] = opts[i];
  34410. return result.warn(text, data)
  34411. }
  34412. remove() {
  34413. if (this.parent) {
  34414. this.parent.removeChild(this);
  34415. }
  34416. this.parent = undefined;
  34417. return this
  34418. }
  34419. toString(stringifier = stringify$3) {
  34420. if (stringifier.stringify) stringifier = stringifier.stringify;
  34421. let result = '';
  34422. stringifier(this, i => {
  34423. result += i;
  34424. });
  34425. return result
  34426. }
  34427. assign(overrides = {}) {
  34428. for (let name in overrides) {
  34429. this[name] = overrides[name];
  34430. }
  34431. return this
  34432. }
  34433. clone(overrides = {}) {
  34434. let cloned = cloneNode(this);
  34435. for (let name in overrides) {
  34436. cloned[name] = overrides[name];
  34437. }
  34438. return cloned
  34439. }
  34440. cloneBefore(overrides = {}) {
  34441. let cloned = this.clone(overrides);
  34442. this.parent.insertBefore(this, cloned);
  34443. return cloned
  34444. }
  34445. cloneAfter(overrides = {}) {
  34446. let cloned = this.clone(overrides);
  34447. this.parent.insertAfter(this, cloned);
  34448. return cloned
  34449. }
  34450. replaceWith(...nodes) {
  34451. if (this.parent) {
  34452. let bookmark = this;
  34453. let foundSelf = false;
  34454. for (let node of nodes) {
  34455. if (node === this) {
  34456. foundSelf = true;
  34457. } else if (foundSelf) {
  34458. this.parent.insertAfter(bookmark, node);
  34459. bookmark = node;
  34460. } else {
  34461. this.parent.insertBefore(bookmark, node);
  34462. }
  34463. }
  34464. if (!foundSelf) {
  34465. this.remove();
  34466. }
  34467. }
  34468. return this
  34469. }
  34470. next() {
  34471. if (!this.parent) return undefined
  34472. let index = this.parent.index(this);
  34473. return this.parent.nodes[index + 1]
  34474. }
  34475. prev() {
  34476. if (!this.parent) return undefined
  34477. let index = this.parent.index(this);
  34478. return this.parent.nodes[index - 1]
  34479. }
  34480. before(add) {
  34481. this.parent.insertBefore(this, add);
  34482. return this
  34483. }
  34484. after(add) {
  34485. this.parent.insertAfter(this, add);
  34486. return this
  34487. }
  34488. root() {
  34489. let result = this;
  34490. while (result.parent && result.parent.type !== 'document') {
  34491. result = result.parent;
  34492. }
  34493. return result
  34494. }
  34495. raw(prop, defaultType) {
  34496. let str = new Stringifier();
  34497. return str.raw(this, prop, defaultType)
  34498. }
  34499. cleanRaws(keepBetween) {
  34500. delete this.raws.before;
  34501. delete this.raws.after;
  34502. if (!keepBetween) delete this.raws.between;
  34503. }
  34504. toJSON(_, inputs) {
  34505. let fixed = {};
  34506. let emitInputs = inputs == null;
  34507. inputs = inputs || new Map();
  34508. let inputsNextIndex = 0;
  34509. for (let name in this) {
  34510. if (!Object.prototype.hasOwnProperty.call(this, name)) {
  34511. /* c8 ignore next 2 */
  34512. continue
  34513. }
  34514. if (name === 'parent' || name === 'proxyCache') continue
  34515. let value = this[name];
  34516. if (Array.isArray(value)) {
  34517. fixed[name] = value.map(i => {
  34518. if (typeof i === 'object' && i.toJSON) {
  34519. return i.toJSON(null, inputs)
  34520. } else {
  34521. return i
  34522. }
  34523. });
  34524. } else if (typeof value === 'object' && value.toJSON) {
  34525. fixed[name] = value.toJSON(null, inputs);
  34526. } else if (name === 'source') {
  34527. let inputId = inputs.get(value.input);
  34528. if (inputId == null) {
  34529. inputId = inputsNextIndex;
  34530. inputs.set(value.input, inputsNextIndex);
  34531. inputsNextIndex++;
  34532. }
  34533. fixed[name] = {
  34534. inputId,
  34535. start: value.start,
  34536. end: value.end
  34537. };
  34538. } else {
  34539. fixed[name] = value;
  34540. }
  34541. }
  34542. if (emitInputs) {
  34543. fixed.inputs = [...inputs.keys()].map(input => input.toJSON());
  34544. }
  34545. return fixed
  34546. }
  34547. positionInside(index) {
  34548. let string = this.toString();
  34549. let column = this.source.start.column;
  34550. let line = this.source.start.line;
  34551. for (let i = 0; i < index; i++) {
  34552. if (string[i] === '\n') {
  34553. column = 1;
  34554. line += 1;
  34555. } else {
  34556. column += 1;
  34557. }
  34558. }
  34559. return { line, column }
  34560. }
  34561. positionBy(opts) {
  34562. let pos = this.source.start;
  34563. if (opts.index) {
  34564. pos = this.positionInside(opts.index);
  34565. } else if (opts.word) {
  34566. let index = this.toString().indexOf(opts.word);
  34567. if (index !== -1) pos = this.positionInside(index);
  34568. }
  34569. return pos
  34570. }
  34571. rangeBy(opts) {
  34572. let start = {
  34573. line: this.source.start.line,
  34574. column: this.source.start.column
  34575. };
  34576. let end = this.source.end
  34577. ? {
  34578. line: this.source.end.line,
  34579. column: this.source.end.column + 1
  34580. }
  34581. : {
  34582. line: start.line,
  34583. column: start.column + 1
  34584. };
  34585. if (opts.word) {
  34586. let index = this.toString().indexOf(opts.word);
  34587. if (index !== -1) {
  34588. start = this.positionInside(index);
  34589. end = this.positionInside(index + opts.word.length);
  34590. }
  34591. } else {
  34592. if (opts.start) {
  34593. start = {
  34594. line: opts.start.line,
  34595. column: opts.start.column
  34596. };
  34597. } else if (opts.index) {
  34598. start = this.positionInside(opts.index);
  34599. }
  34600. if (opts.end) {
  34601. end = {
  34602. line: opts.end.line,
  34603. column: opts.end.column
  34604. };
  34605. } else if (opts.endIndex) {
  34606. end = this.positionInside(opts.endIndex);
  34607. } else if (opts.index) {
  34608. end = this.positionInside(opts.index + 1);
  34609. }
  34610. }
  34611. if (
  34612. end.line < start.line ||
  34613. (end.line === start.line && end.column <= start.column)
  34614. ) {
  34615. end = { line: start.line, column: start.column + 1 };
  34616. }
  34617. return { start, end }
  34618. }
  34619. getProxyProcessor() {
  34620. return {
  34621. set(node, prop, value) {
  34622. if (node[prop] === value) return true
  34623. node[prop] = value;
  34624. if (
  34625. prop === 'prop' ||
  34626. prop === 'value' ||
  34627. prop === 'name' ||
  34628. prop === 'params' ||
  34629. prop === 'important' ||
  34630. /* c8 ignore next */
  34631. prop === 'text'
  34632. ) {
  34633. node.markDirty();
  34634. }
  34635. return true
  34636. },
  34637. get(node, prop) {
  34638. if (prop === 'proxyOf') {
  34639. return node
  34640. } else if (prop === 'root') {
  34641. return () => node.root().toProxy()
  34642. } else {
  34643. return node[prop]
  34644. }
  34645. }
  34646. }
  34647. }
  34648. toProxy() {
  34649. if (!this.proxyCache) {
  34650. this.proxyCache = new Proxy(this, this.getProxyProcessor());
  34651. }
  34652. return this.proxyCache
  34653. }
  34654. addToError(error) {
  34655. error.postcssNode = this;
  34656. if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
  34657. let s = this.source;
  34658. error.stack = error.stack.replace(
  34659. /\n\s{4}at /,
  34660. `$&${s.input.from}:${s.start.line}:${s.start.column}$&`
  34661. );
  34662. }
  34663. return error
  34664. }
  34665. markDirty() {
  34666. if (this[isClean$2]) {
  34667. this[isClean$2] = false;
  34668. let next = this;
  34669. while ((next = next.parent)) {
  34670. next[isClean$2] = false;
  34671. }
  34672. }
  34673. }
  34674. get proxyOf() {
  34675. return this
  34676. }
  34677. };
  34678. var node$2 = Node$4;
  34679. Node$4.default = Node$4;
  34680. let Node$3 = node$2;
  34681. let Declaration$4 = class Declaration extends Node$3 {
  34682. constructor(defaults) {
  34683. if (
  34684. defaults &&
  34685. typeof defaults.value !== 'undefined' &&
  34686. typeof defaults.value !== 'string'
  34687. ) {
  34688. defaults = { ...defaults, value: String(defaults.value) };
  34689. }
  34690. super(defaults);
  34691. this.type = 'decl';
  34692. }
  34693. get variable() {
  34694. return this.prop.startsWith('--') || this.prop[0] === '$'
  34695. }
  34696. };
  34697. var declaration = Declaration$4;
  34698. Declaration$4.default = Declaration$4;
  34699. var sourceMap$1 = {};
  34700. var sourceMapGenerator = {};
  34701. var base64Vlq = {};
  34702. var base64$1 = {};
  34703. /* -*- Mode: js; js-indent-level: 2; -*- */
  34704. /*
  34705. * Copyright 2011 Mozilla Foundation and contributors
  34706. * Licensed under the New BSD license. See LICENSE or:
  34707. * http://opensource.org/licenses/BSD-3-Clause
  34708. */
  34709. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  34710. /**
  34711. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  34712. */
  34713. base64$1.encode = function (number) {
  34714. if (0 <= number && number < intToCharMap.length) {
  34715. return intToCharMap[number];
  34716. }
  34717. throw new TypeError("Must be between 0 and 63: " + number);
  34718. };
  34719. /**
  34720. * Decode a single base 64 character code digit to an integer. Returns -1 on
  34721. * failure.
  34722. */
  34723. base64$1.decode = function (charCode) {
  34724. var bigA = 65; // 'A'
  34725. var bigZ = 90; // 'Z'
  34726. var littleA = 97; // 'a'
  34727. var littleZ = 122; // 'z'
  34728. var zero = 48; // '0'
  34729. var nine = 57; // '9'
  34730. var plus = 43; // '+'
  34731. var slash = 47; // '/'
  34732. var littleOffset = 26;
  34733. var numberOffset = 52;
  34734. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  34735. if (bigA <= charCode && charCode <= bigZ) {
  34736. return (charCode - bigA);
  34737. }
  34738. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  34739. if (littleA <= charCode && charCode <= littleZ) {
  34740. return (charCode - littleA + littleOffset);
  34741. }
  34742. // 52 - 61: 0123456789
  34743. if (zero <= charCode && charCode <= nine) {
  34744. return (charCode - zero + numberOffset);
  34745. }
  34746. // 62: +
  34747. if (charCode == plus) {
  34748. return 62;
  34749. }
  34750. // 63: /
  34751. if (charCode == slash) {
  34752. return 63;
  34753. }
  34754. // Invalid base64 digit.
  34755. return -1;
  34756. };
  34757. /* -*- Mode: js; js-indent-level: 2; -*- */
  34758. /*
  34759. * Copyright 2011 Mozilla Foundation and contributors
  34760. * Licensed under the New BSD license. See LICENSE or:
  34761. * http://opensource.org/licenses/BSD-3-Clause
  34762. *
  34763. * Based on the Base 64 VLQ implementation in Closure Compiler:
  34764. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  34765. *
  34766. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  34767. * Redistribution and use in source and binary forms, with or without
  34768. * modification, are permitted provided that the following conditions are
  34769. * met:
  34770. *
  34771. * * Redistributions of source code must retain the above copyright
  34772. * notice, this list of conditions and the following disclaimer.
  34773. * * Redistributions in binary form must reproduce the above
  34774. * copyright notice, this list of conditions and the following
  34775. * disclaimer in the documentation and/or other materials provided
  34776. * with the distribution.
  34777. * * Neither the name of Google Inc. nor the names of its
  34778. * contributors may be used to endorse or promote products derived
  34779. * from this software without specific prior written permission.
  34780. *
  34781. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  34782. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  34783. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  34784. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  34785. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  34786. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  34787. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  34788. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  34789. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  34790. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  34791. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  34792. */
  34793. var base64 = base64$1;
  34794. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  34795. // length quantities we use in the source map spec, the first bit is the sign,
  34796. // the next four bits are the actual value, and the 6th bit is the
  34797. // continuation bit. The continuation bit tells us whether there are more
  34798. // digits in this value following this digit.
  34799. //
  34800. // Continuation
  34801. // | Sign
  34802. // | |
  34803. // V V
  34804. // 101011
  34805. var VLQ_BASE_SHIFT = 5;
  34806. // binary: 100000
  34807. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  34808. // binary: 011111
  34809. var VLQ_BASE_MASK = VLQ_BASE - 1;
  34810. // binary: 100000
  34811. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  34812. /**
  34813. * Converts from a two-complement value to a value where the sign bit is
  34814. * placed in the least significant bit. For example, as decimals:
  34815. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  34816. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  34817. */
  34818. function toVLQSigned(aValue) {
  34819. return aValue < 0
  34820. ? ((-aValue) << 1) + 1
  34821. : (aValue << 1) + 0;
  34822. }
  34823. /**
  34824. * Converts to a two-complement value from a value where the sign bit is
  34825. * placed in the least significant bit. For example, as decimals:
  34826. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  34827. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  34828. */
  34829. function fromVLQSigned(aValue) {
  34830. var isNegative = (aValue & 1) === 1;
  34831. var shifted = aValue >> 1;
  34832. return isNegative
  34833. ? -shifted
  34834. : shifted;
  34835. }
  34836. /**
  34837. * Returns the base 64 VLQ encoded value.
  34838. */
  34839. base64Vlq.encode = function base64VLQ_encode(aValue) {
  34840. var encoded = "";
  34841. var digit;
  34842. var vlq = toVLQSigned(aValue);
  34843. do {
  34844. digit = vlq & VLQ_BASE_MASK;
  34845. vlq >>>= VLQ_BASE_SHIFT;
  34846. if (vlq > 0) {
  34847. // There are still more digits in this value, so we must make sure the
  34848. // continuation bit is marked.
  34849. digit |= VLQ_CONTINUATION_BIT;
  34850. }
  34851. encoded += base64.encode(digit);
  34852. } while (vlq > 0);
  34853. return encoded;
  34854. };
  34855. /**
  34856. * Decodes the next base 64 VLQ value from the given string and returns the
  34857. * value and the rest of the string via the out parameter.
  34858. */
  34859. base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  34860. var strLen = aStr.length;
  34861. var result = 0;
  34862. var shift = 0;
  34863. var continuation, digit;
  34864. do {
  34865. if (aIndex >= strLen) {
  34866. throw new Error("Expected more digits in base 64 VLQ value.");
  34867. }
  34868. digit = base64.decode(aStr.charCodeAt(aIndex++));
  34869. if (digit === -1) {
  34870. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  34871. }
  34872. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  34873. digit &= VLQ_BASE_MASK;
  34874. result = result + (digit << shift);
  34875. shift += VLQ_BASE_SHIFT;
  34876. } while (continuation);
  34877. aOutParam.value = fromVLQSigned(result);
  34878. aOutParam.rest = aIndex;
  34879. };
  34880. var util$6 = {};
  34881. /* -*- Mode: js; js-indent-level: 2; -*- */
  34882. (function (exports) {
  34883. /*
  34884. * Copyright 2011 Mozilla Foundation and contributors
  34885. * Licensed under the New BSD license. See LICENSE or:
  34886. * http://opensource.org/licenses/BSD-3-Clause
  34887. */
  34888. /**
  34889. * This is a helper function for getting values from parameter/options
  34890. * objects.
  34891. *
  34892. * @param args The object we are extracting values from
  34893. * @param name The name of the property we are getting.
  34894. * @param defaultValue An optional value to return if the property is missing
  34895. * from the object. If this is not specified and the property is missing, an
  34896. * error will be thrown.
  34897. */
  34898. function getArg(aArgs, aName, aDefaultValue) {
  34899. if (aName in aArgs) {
  34900. return aArgs[aName];
  34901. } else if (arguments.length === 3) {
  34902. return aDefaultValue;
  34903. } else {
  34904. throw new Error('"' + aName + '" is a required argument.');
  34905. }
  34906. }
  34907. exports.getArg = getArg;
  34908. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  34909. var dataUrlRegexp = /^data:.+\,.+$/;
  34910. function urlParse(aUrl) {
  34911. var match = aUrl.match(urlRegexp);
  34912. if (!match) {
  34913. return null;
  34914. }
  34915. return {
  34916. scheme: match[1],
  34917. auth: match[2],
  34918. host: match[3],
  34919. port: match[4],
  34920. path: match[5]
  34921. };
  34922. }
  34923. exports.urlParse = urlParse;
  34924. function urlGenerate(aParsedUrl) {
  34925. var url = '';
  34926. if (aParsedUrl.scheme) {
  34927. url += aParsedUrl.scheme + ':';
  34928. }
  34929. url += '//';
  34930. if (aParsedUrl.auth) {
  34931. url += aParsedUrl.auth + '@';
  34932. }
  34933. if (aParsedUrl.host) {
  34934. url += aParsedUrl.host;
  34935. }
  34936. if (aParsedUrl.port) {
  34937. url += ":" + aParsedUrl.port;
  34938. }
  34939. if (aParsedUrl.path) {
  34940. url += aParsedUrl.path;
  34941. }
  34942. return url;
  34943. }
  34944. exports.urlGenerate = urlGenerate;
  34945. var MAX_CACHED_INPUTS = 32;
  34946. /**
  34947. * Takes some function `f(input) -> result` and returns a memoized version of
  34948. * `f`.
  34949. *
  34950. * We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The
  34951. * memoization is a dumb-simple, linear least-recently-used cache.
  34952. */
  34953. function lruMemoize(f) {
  34954. var cache = [];
  34955. return function(input) {
  34956. for (var i = 0; i < cache.length; i++) {
  34957. if (cache[i].input === input) {
  34958. var temp = cache[0];
  34959. cache[0] = cache[i];
  34960. cache[i] = temp;
  34961. return cache[0].result;
  34962. }
  34963. }
  34964. var result = f(input);
  34965. cache.unshift({
  34966. input,
  34967. result,
  34968. });
  34969. if (cache.length > MAX_CACHED_INPUTS) {
  34970. cache.pop();
  34971. }
  34972. return result;
  34973. };
  34974. }
  34975. /**
  34976. * Normalizes a path, or the path portion of a URL:
  34977. *
  34978. * - Replaces consecutive slashes with one slash.
  34979. * - Removes unnecessary '.' parts.
  34980. * - Removes unnecessary '<dir>/..' parts.
  34981. *
  34982. * Based on code in the Node.js 'path' core module.
  34983. *
  34984. * @param aPath The path or url to normalize.
  34985. */
  34986. var normalize = lruMemoize(function normalize(aPath) {
  34987. var path = aPath;
  34988. var url = urlParse(aPath);
  34989. if (url) {
  34990. if (!url.path) {
  34991. return aPath;
  34992. }
  34993. path = url.path;
  34994. }
  34995. var isAbsolute = exports.isAbsolute(path);
  34996. // Split the path into parts between `/` characters. This is much faster than
  34997. // using `.split(/\/+/g)`.
  34998. var parts = [];
  34999. var start = 0;
  35000. var i = 0;
  35001. while (true) {
  35002. start = i;
  35003. i = path.indexOf("/", start);
  35004. if (i === -1) {
  35005. parts.push(path.slice(start));
  35006. break;
  35007. } else {
  35008. parts.push(path.slice(start, i));
  35009. while (i < path.length && path[i] === "/") {
  35010. i++;
  35011. }
  35012. }
  35013. }
  35014. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  35015. part = parts[i];
  35016. if (part === '.') {
  35017. parts.splice(i, 1);
  35018. } else if (part === '..') {
  35019. up++;
  35020. } else if (up > 0) {
  35021. if (part === '') {
  35022. // The first part is blank if the path is absolute. Trying to go
  35023. // above the root is a no-op. Therefore we can remove all '..' parts
  35024. // directly after the root.
  35025. parts.splice(i + 1, up);
  35026. up = 0;
  35027. } else {
  35028. parts.splice(i, 2);
  35029. up--;
  35030. }
  35031. }
  35032. }
  35033. path = parts.join('/');
  35034. if (path === '') {
  35035. path = isAbsolute ? '/' : '.';
  35036. }
  35037. if (url) {
  35038. url.path = path;
  35039. return urlGenerate(url);
  35040. }
  35041. return path;
  35042. });
  35043. exports.normalize = normalize;
  35044. /**
  35045. * Joins two paths/URLs.
  35046. *
  35047. * @param aRoot The root path or URL.
  35048. * @param aPath The path or URL to be joined with the root.
  35049. *
  35050. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  35051. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  35052. * first.
  35053. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  35054. * is updated with the result and aRoot is returned. Otherwise the result
  35055. * is returned.
  35056. * - If aPath is absolute, the result is aPath.
  35057. * - Otherwise the two paths are joined with a slash.
  35058. * - Joining for example 'http://' and 'www.example.com' is also supported.
  35059. */
  35060. function join(aRoot, aPath) {
  35061. if (aRoot === "") {
  35062. aRoot = ".";
  35063. }
  35064. if (aPath === "") {
  35065. aPath = ".";
  35066. }
  35067. var aPathUrl = urlParse(aPath);
  35068. var aRootUrl = urlParse(aRoot);
  35069. if (aRootUrl) {
  35070. aRoot = aRootUrl.path || '/';
  35071. }
  35072. // `join(foo, '//www.example.org')`
  35073. if (aPathUrl && !aPathUrl.scheme) {
  35074. if (aRootUrl) {
  35075. aPathUrl.scheme = aRootUrl.scheme;
  35076. }
  35077. return urlGenerate(aPathUrl);
  35078. }
  35079. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  35080. return aPath;
  35081. }
  35082. // `join('http://', 'www.example.com')`
  35083. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  35084. aRootUrl.host = aPath;
  35085. return urlGenerate(aRootUrl);
  35086. }
  35087. var joined = aPath.charAt(0) === '/'
  35088. ? aPath
  35089. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  35090. if (aRootUrl) {
  35091. aRootUrl.path = joined;
  35092. return urlGenerate(aRootUrl);
  35093. }
  35094. return joined;
  35095. }
  35096. exports.join = join;
  35097. exports.isAbsolute = function (aPath) {
  35098. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  35099. };
  35100. /**
  35101. * Make a path relative to a URL or another path.
  35102. *
  35103. * @param aRoot The root path or URL.
  35104. * @param aPath The path or URL to be made relative to aRoot.
  35105. */
  35106. function relative(aRoot, aPath) {
  35107. if (aRoot === "") {
  35108. aRoot = ".";
  35109. }
  35110. aRoot = aRoot.replace(/\/$/, '');
  35111. // It is possible for the path to be above the root. In this case, simply
  35112. // checking whether the root is a prefix of the path won't work. Instead, we
  35113. // need to remove components from the root one by one, until either we find
  35114. // a prefix that fits, or we run out of components to remove.
  35115. var level = 0;
  35116. while (aPath.indexOf(aRoot + '/') !== 0) {
  35117. var index = aRoot.lastIndexOf("/");
  35118. if (index < 0) {
  35119. return aPath;
  35120. }
  35121. // If the only part of the root that is left is the scheme (i.e. http://,
  35122. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  35123. // have exhausted all components, so the path is not relative to the root.
  35124. aRoot = aRoot.slice(0, index);
  35125. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  35126. return aPath;
  35127. }
  35128. ++level;
  35129. }
  35130. // Make sure we add a "../" for each component we removed from the root.
  35131. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  35132. }
  35133. exports.relative = relative;
  35134. var supportsNullProto = (function () {
  35135. var obj = Object.create(null);
  35136. return !('__proto__' in obj);
  35137. }());
  35138. function identity (s) {
  35139. return s;
  35140. }
  35141. /**
  35142. * Because behavior goes wacky when you set `__proto__` on objects, we
  35143. * have to prefix all the strings in our set with an arbitrary character.
  35144. *
  35145. * See https://github.com/mozilla/source-map/pull/31 and
  35146. * https://github.com/mozilla/source-map/issues/30
  35147. *
  35148. * @param String aStr
  35149. */
  35150. function toSetString(aStr) {
  35151. if (isProtoString(aStr)) {
  35152. return '$' + aStr;
  35153. }
  35154. return aStr;
  35155. }
  35156. exports.toSetString = supportsNullProto ? identity : toSetString;
  35157. function fromSetString(aStr) {
  35158. if (isProtoString(aStr)) {
  35159. return aStr.slice(1);
  35160. }
  35161. return aStr;
  35162. }
  35163. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  35164. function isProtoString(s) {
  35165. if (!s) {
  35166. return false;
  35167. }
  35168. var length = s.length;
  35169. if (length < 9 /* "__proto__".length */) {
  35170. return false;
  35171. }
  35172. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  35173. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  35174. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  35175. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  35176. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  35177. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  35178. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  35179. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  35180. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  35181. return false;
  35182. }
  35183. for (var i = length - 10; i >= 0; i--) {
  35184. if (s.charCodeAt(i) !== 36 /* '$' */) {
  35185. return false;
  35186. }
  35187. }
  35188. return true;
  35189. }
  35190. /**
  35191. * Comparator between two mappings where the original positions are compared.
  35192. *
  35193. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  35194. * mappings with the same original source/line/column, but different generated
  35195. * line and column the same. Useful when searching for a mapping with a
  35196. * stubbed out mapping.
  35197. */
  35198. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  35199. var cmp = strcmp(mappingA.source, mappingB.source);
  35200. if (cmp !== 0) {
  35201. return cmp;
  35202. }
  35203. cmp = mappingA.originalLine - mappingB.originalLine;
  35204. if (cmp !== 0) {
  35205. return cmp;
  35206. }
  35207. cmp = mappingA.originalColumn - mappingB.originalColumn;
  35208. if (cmp !== 0 || onlyCompareOriginal) {
  35209. return cmp;
  35210. }
  35211. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  35212. if (cmp !== 0) {
  35213. return cmp;
  35214. }
  35215. cmp = mappingA.generatedLine - mappingB.generatedLine;
  35216. if (cmp !== 0) {
  35217. return cmp;
  35218. }
  35219. return strcmp(mappingA.name, mappingB.name);
  35220. }
  35221. exports.compareByOriginalPositions = compareByOriginalPositions;
  35222. function compareByOriginalPositionsNoSource(mappingA, mappingB, onlyCompareOriginal) {
  35223. var cmp;
  35224. cmp = mappingA.originalLine - mappingB.originalLine;
  35225. if (cmp !== 0) {
  35226. return cmp;
  35227. }
  35228. cmp = mappingA.originalColumn - mappingB.originalColumn;
  35229. if (cmp !== 0 || onlyCompareOriginal) {
  35230. return cmp;
  35231. }
  35232. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  35233. if (cmp !== 0) {
  35234. return cmp;
  35235. }
  35236. cmp = mappingA.generatedLine - mappingB.generatedLine;
  35237. if (cmp !== 0) {
  35238. return cmp;
  35239. }
  35240. return strcmp(mappingA.name, mappingB.name);
  35241. }
  35242. exports.compareByOriginalPositionsNoSource = compareByOriginalPositionsNoSource;
  35243. /**
  35244. * Comparator between two mappings with deflated source and name indices where
  35245. * the generated positions are compared.
  35246. *
  35247. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  35248. * mappings with the same generated line and column, but different
  35249. * source/name/original line and column the same. Useful when searching for a
  35250. * mapping with a stubbed out mapping.
  35251. */
  35252. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  35253. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  35254. if (cmp !== 0) {
  35255. return cmp;
  35256. }
  35257. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  35258. if (cmp !== 0 || onlyCompareGenerated) {
  35259. return cmp;
  35260. }
  35261. cmp = strcmp(mappingA.source, mappingB.source);
  35262. if (cmp !== 0) {
  35263. return cmp;
  35264. }
  35265. cmp = mappingA.originalLine - mappingB.originalLine;
  35266. if (cmp !== 0) {
  35267. return cmp;
  35268. }
  35269. cmp = mappingA.originalColumn - mappingB.originalColumn;
  35270. if (cmp !== 0) {
  35271. return cmp;
  35272. }
  35273. return strcmp(mappingA.name, mappingB.name);
  35274. }
  35275. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  35276. function compareByGeneratedPositionsDeflatedNoLine(mappingA, mappingB, onlyCompareGenerated) {
  35277. var cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  35278. if (cmp !== 0 || onlyCompareGenerated) {
  35279. return cmp;
  35280. }
  35281. cmp = strcmp(mappingA.source, mappingB.source);
  35282. if (cmp !== 0) {
  35283. return cmp;
  35284. }
  35285. cmp = mappingA.originalLine - mappingB.originalLine;
  35286. if (cmp !== 0) {
  35287. return cmp;
  35288. }
  35289. cmp = mappingA.originalColumn - mappingB.originalColumn;
  35290. if (cmp !== 0) {
  35291. return cmp;
  35292. }
  35293. return strcmp(mappingA.name, mappingB.name);
  35294. }
  35295. exports.compareByGeneratedPositionsDeflatedNoLine = compareByGeneratedPositionsDeflatedNoLine;
  35296. function strcmp(aStr1, aStr2) {
  35297. if (aStr1 === aStr2) {
  35298. return 0;
  35299. }
  35300. if (aStr1 === null) {
  35301. return 1; // aStr2 !== null
  35302. }
  35303. if (aStr2 === null) {
  35304. return -1; // aStr1 !== null
  35305. }
  35306. if (aStr1 > aStr2) {
  35307. return 1;
  35308. }
  35309. return -1;
  35310. }
  35311. /**
  35312. * Comparator between two mappings with inflated source and name strings where
  35313. * the generated positions are compared.
  35314. */
  35315. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  35316. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  35317. if (cmp !== 0) {
  35318. return cmp;
  35319. }
  35320. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  35321. if (cmp !== 0) {
  35322. return cmp;
  35323. }
  35324. cmp = strcmp(mappingA.source, mappingB.source);
  35325. if (cmp !== 0) {
  35326. return cmp;
  35327. }
  35328. cmp = mappingA.originalLine - mappingB.originalLine;
  35329. if (cmp !== 0) {
  35330. return cmp;
  35331. }
  35332. cmp = mappingA.originalColumn - mappingB.originalColumn;
  35333. if (cmp !== 0) {
  35334. return cmp;
  35335. }
  35336. return strcmp(mappingA.name, mappingB.name);
  35337. }
  35338. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  35339. /**
  35340. * Strip any JSON XSSI avoidance prefix from the string (as documented
  35341. * in the source maps specification), and then parse the string as
  35342. * JSON.
  35343. */
  35344. function parseSourceMapInput(str) {
  35345. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  35346. }
  35347. exports.parseSourceMapInput = parseSourceMapInput;
  35348. /**
  35349. * Compute the URL of a source given the the source root, the source's
  35350. * URL, and the source map's URL.
  35351. */
  35352. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  35353. sourceURL = sourceURL || '';
  35354. if (sourceRoot) {
  35355. // This follows what Chrome does.
  35356. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  35357. sourceRoot += '/';
  35358. }
  35359. // The spec says:
  35360. // Line 4: An optional source root, useful for relocating source
  35361. // files on a server or removing repeated values in the
  35362. // “sources” entry. This value is prepended to the individual
  35363. // entries in the “source” field.
  35364. sourceURL = sourceRoot + sourceURL;
  35365. }
  35366. // Historically, SourceMapConsumer did not take the sourceMapURL as
  35367. // a parameter. This mode is still somewhat supported, which is why
  35368. // this code block is conditional. However, it's preferable to pass
  35369. // the source map URL to SourceMapConsumer, so that this function
  35370. // can implement the source URL resolution algorithm as outlined in
  35371. // the spec. This block is basically the equivalent of:
  35372. // new URL(sourceURL, sourceMapURL).toString()
  35373. // ... except it avoids using URL, which wasn't available in the
  35374. // older releases of node still supported by this library.
  35375. //
  35376. // The spec says:
  35377. // If the sources are not absolute URLs after prepending of the
  35378. // “sourceRoot”, the sources are resolved relative to the
  35379. // SourceMap (like resolving script src in a html document).
  35380. if (sourceMapURL) {
  35381. var parsed = urlParse(sourceMapURL);
  35382. if (!parsed) {
  35383. throw new Error("sourceMapURL could not be parsed");
  35384. }
  35385. if (parsed.path) {
  35386. // Strip the last path component, but keep the "/".
  35387. var index = parsed.path.lastIndexOf('/');
  35388. if (index >= 0) {
  35389. parsed.path = parsed.path.substring(0, index + 1);
  35390. }
  35391. }
  35392. sourceURL = join(urlGenerate(parsed), sourceURL);
  35393. }
  35394. return normalize(sourceURL);
  35395. }
  35396. exports.computeSourceURL = computeSourceURL;
  35397. } (util$6));
  35398. var arraySet = {};
  35399. /* -*- Mode: js; js-indent-level: 2; -*- */
  35400. /*
  35401. * Copyright 2011 Mozilla Foundation and contributors
  35402. * Licensed under the New BSD license. See LICENSE or:
  35403. * http://opensource.org/licenses/BSD-3-Clause
  35404. */
  35405. var util$5 = util$6;
  35406. var has = Object.prototype.hasOwnProperty;
  35407. var hasNativeMap = typeof Map !== "undefined";
  35408. /**
  35409. * A data structure which is a combination of an array and a set. Adding a new
  35410. * member is O(1), testing for membership is O(1), and finding the index of an
  35411. * element is O(1). Removing elements from the set is not supported. Only
  35412. * strings are supported for membership.
  35413. */
  35414. function ArraySet$2() {
  35415. this._array = [];
  35416. this._set = hasNativeMap ? new Map() : Object.create(null);
  35417. }
  35418. /**
  35419. * Static method for creating ArraySet instances from an existing array.
  35420. */
  35421. ArraySet$2.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  35422. var set = new ArraySet$2();
  35423. for (var i = 0, len = aArray.length; i < len; i++) {
  35424. set.add(aArray[i], aAllowDuplicates);
  35425. }
  35426. return set;
  35427. };
  35428. /**
  35429. * Return how many unique items are in this ArraySet. If duplicates have been
  35430. * added, than those do not count towards the size.
  35431. *
  35432. * @returns Number
  35433. */
  35434. ArraySet$2.prototype.size = function ArraySet_size() {
  35435. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  35436. };
  35437. /**
  35438. * Add the given string to this set.
  35439. *
  35440. * @param String aStr
  35441. */
  35442. ArraySet$2.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  35443. var sStr = hasNativeMap ? aStr : util$5.toSetString(aStr);
  35444. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  35445. var idx = this._array.length;
  35446. if (!isDuplicate || aAllowDuplicates) {
  35447. this._array.push(aStr);
  35448. }
  35449. if (!isDuplicate) {
  35450. if (hasNativeMap) {
  35451. this._set.set(aStr, idx);
  35452. } else {
  35453. this._set[sStr] = idx;
  35454. }
  35455. }
  35456. };
  35457. /**
  35458. * Is the given string a member of this set?
  35459. *
  35460. * @param String aStr
  35461. */
  35462. ArraySet$2.prototype.has = function ArraySet_has(aStr) {
  35463. if (hasNativeMap) {
  35464. return this._set.has(aStr);
  35465. } else {
  35466. var sStr = util$5.toSetString(aStr);
  35467. return has.call(this._set, sStr);
  35468. }
  35469. };
  35470. /**
  35471. * What is the index of the given string in the array?
  35472. *
  35473. * @param String aStr
  35474. */
  35475. ArraySet$2.prototype.indexOf = function ArraySet_indexOf(aStr) {
  35476. if (hasNativeMap) {
  35477. var idx = this._set.get(aStr);
  35478. if (idx >= 0) {
  35479. return idx;
  35480. }
  35481. } else {
  35482. var sStr = util$5.toSetString(aStr);
  35483. if (has.call(this._set, sStr)) {
  35484. return this._set[sStr];
  35485. }
  35486. }
  35487. throw new Error('"' + aStr + '" is not in the set.');
  35488. };
  35489. /**
  35490. * What is the element at the given index?
  35491. *
  35492. * @param Number aIdx
  35493. */
  35494. ArraySet$2.prototype.at = function ArraySet_at(aIdx) {
  35495. if (aIdx >= 0 && aIdx < this._array.length) {
  35496. return this._array[aIdx];
  35497. }
  35498. throw new Error('No element indexed by ' + aIdx);
  35499. };
  35500. /**
  35501. * Returns the array representation of this set (which has the proper indices
  35502. * indicated by indexOf). Note that this is a copy of the internal array used
  35503. * for storing the members so that no one can mess with internal state.
  35504. */
  35505. ArraySet$2.prototype.toArray = function ArraySet_toArray() {
  35506. return this._array.slice();
  35507. };
  35508. arraySet.ArraySet = ArraySet$2;
  35509. var mappingList = {};
  35510. /* -*- Mode: js; js-indent-level: 2; -*- */
  35511. /*
  35512. * Copyright 2014 Mozilla Foundation and contributors
  35513. * Licensed under the New BSD license. See LICENSE or:
  35514. * http://opensource.org/licenses/BSD-3-Clause
  35515. */
  35516. var util$4 = util$6;
  35517. /**
  35518. * Determine whether mappingB is after mappingA with respect to generated
  35519. * position.
  35520. */
  35521. function generatedPositionAfter(mappingA, mappingB) {
  35522. // Optimized for most common case
  35523. var lineA = mappingA.generatedLine;
  35524. var lineB = mappingB.generatedLine;
  35525. var columnA = mappingA.generatedColumn;
  35526. var columnB = mappingB.generatedColumn;
  35527. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  35528. util$4.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  35529. }
  35530. /**
  35531. * A data structure to provide a sorted view of accumulated mappings in a
  35532. * performance conscious manner. It trades a neglibable overhead in general
  35533. * case for a large speedup in case of mappings being added in order.
  35534. */
  35535. function MappingList$1() {
  35536. this._array = [];
  35537. this._sorted = true;
  35538. // Serves as infimum
  35539. this._last = {generatedLine: -1, generatedColumn: 0};
  35540. }
  35541. /**
  35542. * Iterate through internal items. This method takes the same arguments that
  35543. * `Array.prototype.forEach` takes.
  35544. *
  35545. * NOTE: The order of the mappings is NOT guaranteed.
  35546. */
  35547. MappingList$1.prototype.unsortedForEach =
  35548. function MappingList_forEach(aCallback, aThisArg) {
  35549. this._array.forEach(aCallback, aThisArg);
  35550. };
  35551. /**
  35552. * Add the given source mapping.
  35553. *
  35554. * @param Object aMapping
  35555. */
  35556. MappingList$1.prototype.add = function MappingList_add(aMapping) {
  35557. if (generatedPositionAfter(this._last, aMapping)) {
  35558. this._last = aMapping;
  35559. this._array.push(aMapping);
  35560. } else {
  35561. this._sorted = false;
  35562. this._array.push(aMapping);
  35563. }
  35564. };
  35565. /**
  35566. * Returns the flat, sorted array of mappings. The mappings are sorted by
  35567. * generated position.
  35568. *
  35569. * WARNING: This method returns internal data without copying, for
  35570. * performance. The return value must NOT be mutated, and should be treated as
  35571. * an immutable borrow. If you want to take ownership, you must make your own
  35572. * copy.
  35573. */
  35574. MappingList$1.prototype.toArray = function MappingList_toArray() {
  35575. if (!this._sorted) {
  35576. this._array.sort(util$4.compareByGeneratedPositionsInflated);
  35577. this._sorted = true;
  35578. }
  35579. return this._array;
  35580. };
  35581. mappingList.MappingList = MappingList$1;
  35582. /* -*- Mode: js; js-indent-level: 2; -*- */
  35583. /*
  35584. * Copyright 2011 Mozilla Foundation and contributors
  35585. * Licensed under the New BSD license. See LICENSE or:
  35586. * http://opensource.org/licenses/BSD-3-Clause
  35587. */
  35588. var base64VLQ$1 = base64Vlq;
  35589. var util$3 = util$6;
  35590. var ArraySet$1 = arraySet.ArraySet;
  35591. var MappingList = mappingList.MappingList;
  35592. /**
  35593. * An instance of the SourceMapGenerator represents a source map which is
  35594. * being built incrementally. You may pass an object with the following
  35595. * properties:
  35596. *
  35597. * - file: The filename of the generated source.
  35598. * - sourceRoot: A root for all relative URLs in this source map.
  35599. */
  35600. function SourceMapGenerator$5(aArgs) {
  35601. if (!aArgs) {
  35602. aArgs = {};
  35603. }
  35604. this._file = util$3.getArg(aArgs, 'file', null);
  35605. this._sourceRoot = util$3.getArg(aArgs, 'sourceRoot', null);
  35606. this._skipValidation = util$3.getArg(aArgs, 'skipValidation', false);
  35607. this._sources = new ArraySet$1();
  35608. this._names = new ArraySet$1();
  35609. this._mappings = new MappingList();
  35610. this._sourcesContents = null;
  35611. }
  35612. SourceMapGenerator$5.prototype._version = 3;
  35613. /**
  35614. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  35615. *
  35616. * @param aSourceMapConsumer The SourceMap.
  35617. */
  35618. SourceMapGenerator$5.fromSourceMap =
  35619. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  35620. var sourceRoot = aSourceMapConsumer.sourceRoot;
  35621. var generator = new SourceMapGenerator$5({
  35622. file: aSourceMapConsumer.file,
  35623. sourceRoot: sourceRoot
  35624. });
  35625. aSourceMapConsumer.eachMapping(function (mapping) {
  35626. var newMapping = {
  35627. generated: {
  35628. line: mapping.generatedLine,
  35629. column: mapping.generatedColumn
  35630. }
  35631. };
  35632. if (mapping.source != null) {
  35633. newMapping.source = mapping.source;
  35634. if (sourceRoot != null) {
  35635. newMapping.source = util$3.relative(sourceRoot, newMapping.source);
  35636. }
  35637. newMapping.original = {
  35638. line: mapping.originalLine,
  35639. column: mapping.originalColumn
  35640. };
  35641. if (mapping.name != null) {
  35642. newMapping.name = mapping.name;
  35643. }
  35644. }
  35645. generator.addMapping(newMapping);
  35646. });
  35647. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  35648. var sourceRelative = sourceFile;
  35649. if (sourceRoot !== null) {
  35650. sourceRelative = util$3.relative(sourceRoot, sourceFile);
  35651. }
  35652. if (!generator._sources.has(sourceRelative)) {
  35653. generator._sources.add(sourceRelative);
  35654. }
  35655. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  35656. if (content != null) {
  35657. generator.setSourceContent(sourceFile, content);
  35658. }
  35659. });
  35660. return generator;
  35661. };
  35662. /**
  35663. * Add a single mapping from original source line and column to the generated
  35664. * source's line and column for this source map being created. The mapping
  35665. * object should have the following properties:
  35666. *
  35667. * - generated: An object with the generated line and column positions.
  35668. * - original: An object with the original line and column positions.
  35669. * - source: The original source file (relative to the sourceRoot).
  35670. * - name: An optional original token name for this mapping.
  35671. */
  35672. SourceMapGenerator$5.prototype.addMapping =
  35673. function SourceMapGenerator_addMapping(aArgs) {
  35674. var generated = util$3.getArg(aArgs, 'generated');
  35675. var original = util$3.getArg(aArgs, 'original', null);
  35676. var source = util$3.getArg(aArgs, 'source', null);
  35677. var name = util$3.getArg(aArgs, 'name', null);
  35678. if (!this._skipValidation) {
  35679. this._validateMapping(generated, original, source, name);
  35680. }
  35681. if (source != null) {
  35682. source = String(source);
  35683. if (!this._sources.has(source)) {
  35684. this._sources.add(source);
  35685. }
  35686. }
  35687. if (name != null) {
  35688. name = String(name);
  35689. if (!this._names.has(name)) {
  35690. this._names.add(name);
  35691. }
  35692. }
  35693. this._mappings.add({
  35694. generatedLine: generated.line,
  35695. generatedColumn: generated.column,
  35696. originalLine: original != null && original.line,
  35697. originalColumn: original != null && original.column,
  35698. source: source,
  35699. name: name
  35700. });
  35701. };
  35702. /**
  35703. * Set the source content for a source file.
  35704. */
  35705. SourceMapGenerator$5.prototype.setSourceContent =
  35706. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  35707. var source = aSourceFile;
  35708. if (this._sourceRoot != null) {
  35709. source = util$3.relative(this._sourceRoot, source);
  35710. }
  35711. if (aSourceContent != null) {
  35712. // Add the source content to the _sourcesContents map.
  35713. // Create a new _sourcesContents map if the property is null.
  35714. if (!this._sourcesContents) {
  35715. this._sourcesContents = Object.create(null);
  35716. }
  35717. this._sourcesContents[util$3.toSetString(source)] = aSourceContent;
  35718. } else if (this._sourcesContents) {
  35719. // Remove the source file from the _sourcesContents map.
  35720. // If the _sourcesContents map is empty, set the property to null.
  35721. delete this._sourcesContents[util$3.toSetString(source)];
  35722. if (Object.keys(this._sourcesContents).length === 0) {
  35723. this._sourcesContents = null;
  35724. }
  35725. }
  35726. };
  35727. /**
  35728. * Applies the mappings of a sub-source-map for a specific source file to the
  35729. * source map being generated. Each mapping to the supplied source file is
  35730. * rewritten using the supplied source map. Note: The resolution for the
  35731. * resulting mappings is the minimium of this map and the supplied map.
  35732. *
  35733. * @param aSourceMapConsumer The source map to be applied.
  35734. * @param aSourceFile Optional. The filename of the source file.
  35735. * If omitted, SourceMapConsumer's file property will be used.
  35736. * @param aSourceMapPath Optional. The dirname of the path to the source map
  35737. * to be applied. If relative, it is relative to the SourceMapConsumer.
  35738. * This parameter is needed when the two source maps aren't in the same
  35739. * directory, and the source map to be applied contains relative source
  35740. * paths. If so, those relative source paths need to be rewritten
  35741. * relative to the SourceMapGenerator.
  35742. */
  35743. SourceMapGenerator$5.prototype.applySourceMap =
  35744. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  35745. var sourceFile = aSourceFile;
  35746. // If aSourceFile is omitted, we will use the file property of the SourceMap
  35747. if (aSourceFile == null) {
  35748. if (aSourceMapConsumer.file == null) {
  35749. throw new Error(
  35750. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  35751. 'or the source map\'s "file" property. Both were omitted.'
  35752. );
  35753. }
  35754. sourceFile = aSourceMapConsumer.file;
  35755. }
  35756. var sourceRoot = this._sourceRoot;
  35757. // Make "sourceFile" relative if an absolute Url is passed.
  35758. if (sourceRoot != null) {
  35759. sourceFile = util$3.relative(sourceRoot, sourceFile);
  35760. }
  35761. // Applying the SourceMap can add and remove items from the sources and
  35762. // the names array.
  35763. var newSources = new ArraySet$1();
  35764. var newNames = new ArraySet$1();
  35765. // Find mappings for the "sourceFile"
  35766. this._mappings.unsortedForEach(function (mapping) {
  35767. if (mapping.source === sourceFile && mapping.originalLine != null) {
  35768. // Check if it can be mapped by the source map, then update the mapping.
  35769. var original = aSourceMapConsumer.originalPositionFor({
  35770. line: mapping.originalLine,
  35771. column: mapping.originalColumn
  35772. });
  35773. if (original.source != null) {
  35774. // Copy mapping
  35775. mapping.source = original.source;
  35776. if (aSourceMapPath != null) {
  35777. mapping.source = util$3.join(aSourceMapPath, mapping.source);
  35778. }
  35779. if (sourceRoot != null) {
  35780. mapping.source = util$3.relative(sourceRoot, mapping.source);
  35781. }
  35782. mapping.originalLine = original.line;
  35783. mapping.originalColumn = original.column;
  35784. if (original.name != null) {
  35785. mapping.name = original.name;
  35786. }
  35787. }
  35788. }
  35789. var source = mapping.source;
  35790. if (source != null && !newSources.has(source)) {
  35791. newSources.add(source);
  35792. }
  35793. var name = mapping.name;
  35794. if (name != null && !newNames.has(name)) {
  35795. newNames.add(name);
  35796. }
  35797. }, this);
  35798. this._sources = newSources;
  35799. this._names = newNames;
  35800. // Copy sourcesContents of applied map.
  35801. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  35802. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  35803. if (content != null) {
  35804. if (aSourceMapPath != null) {
  35805. sourceFile = util$3.join(aSourceMapPath, sourceFile);
  35806. }
  35807. if (sourceRoot != null) {
  35808. sourceFile = util$3.relative(sourceRoot, sourceFile);
  35809. }
  35810. this.setSourceContent(sourceFile, content);
  35811. }
  35812. }, this);
  35813. };
  35814. /**
  35815. * A mapping can have one of the three levels of data:
  35816. *
  35817. * 1. Just the generated position.
  35818. * 2. The Generated position, original position, and original source.
  35819. * 3. Generated and original position, original source, as well as a name
  35820. * token.
  35821. *
  35822. * To maintain consistency, we validate that any new mapping being added falls
  35823. * in to one of these categories.
  35824. */
  35825. SourceMapGenerator$5.prototype._validateMapping =
  35826. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  35827. aName) {
  35828. // When aOriginal is truthy but has empty values for .line and .column,
  35829. // it is most likely a programmer error. In this case we throw a very
  35830. // specific error message to try to guide them the right way.
  35831. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  35832. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  35833. throw new Error(
  35834. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  35835. 'the original mapping entirely and only map the generated position. If so, pass ' +
  35836. 'null for the original mapping instead of an object with empty or null values.'
  35837. );
  35838. }
  35839. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  35840. && aGenerated.line > 0 && aGenerated.column >= 0
  35841. && !aOriginal && !aSource && !aName) {
  35842. // Case 1.
  35843. return;
  35844. }
  35845. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  35846. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  35847. && aGenerated.line > 0 && aGenerated.column >= 0
  35848. && aOriginal.line > 0 && aOriginal.column >= 0
  35849. && aSource) {
  35850. // Cases 2 and 3.
  35851. return;
  35852. }
  35853. else {
  35854. throw new Error('Invalid mapping: ' + JSON.stringify({
  35855. generated: aGenerated,
  35856. source: aSource,
  35857. original: aOriginal,
  35858. name: aName
  35859. }));
  35860. }
  35861. };
  35862. /**
  35863. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  35864. * specified by the source map format.
  35865. */
  35866. SourceMapGenerator$5.prototype._serializeMappings =
  35867. function SourceMapGenerator_serializeMappings() {
  35868. var previousGeneratedColumn = 0;
  35869. var previousGeneratedLine = 1;
  35870. var previousOriginalColumn = 0;
  35871. var previousOriginalLine = 0;
  35872. var previousName = 0;
  35873. var previousSource = 0;
  35874. var result = '';
  35875. var next;
  35876. var mapping;
  35877. var nameIdx;
  35878. var sourceIdx;
  35879. var mappings = this._mappings.toArray();
  35880. for (var i = 0, len = mappings.length; i < len; i++) {
  35881. mapping = mappings[i];
  35882. next = '';
  35883. if (mapping.generatedLine !== previousGeneratedLine) {
  35884. previousGeneratedColumn = 0;
  35885. while (mapping.generatedLine !== previousGeneratedLine) {
  35886. next += ';';
  35887. previousGeneratedLine++;
  35888. }
  35889. }
  35890. else {
  35891. if (i > 0) {
  35892. if (!util$3.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  35893. continue;
  35894. }
  35895. next += ',';
  35896. }
  35897. }
  35898. next += base64VLQ$1.encode(mapping.generatedColumn
  35899. - previousGeneratedColumn);
  35900. previousGeneratedColumn = mapping.generatedColumn;
  35901. if (mapping.source != null) {
  35902. sourceIdx = this._sources.indexOf(mapping.source);
  35903. next += base64VLQ$1.encode(sourceIdx - previousSource);
  35904. previousSource = sourceIdx;
  35905. // lines are stored 0-based in SourceMap spec version 3
  35906. next += base64VLQ$1.encode(mapping.originalLine - 1
  35907. - previousOriginalLine);
  35908. previousOriginalLine = mapping.originalLine - 1;
  35909. next += base64VLQ$1.encode(mapping.originalColumn
  35910. - previousOriginalColumn);
  35911. previousOriginalColumn = mapping.originalColumn;
  35912. if (mapping.name != null) {
  35913. nameIdx = this._names.indexOf(mapping.name);
  35914. next += base64VLQ$1.encode(nameIdx - previousName);
  35915. previousName = nameIdx;
  35916. }
  35917. }
  35918. result += next;
  35919. }
  35920. return result;
  35921. };
  35922. SourceMapGenerator$5.prototype._generateSourcesContent =
  35923. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  35924. return aSources.map(function (source) {
  35925. if (!this._sourcesContents) {
  35926. return null;
  35927. }
  35928. if (aSourceRoot != null) {
  35929. source = util$3.relative(aSourceRoot, source);
  35930. }
  35931. var key = util$3.toSetString(source);
  35932. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  35933. ? this._sourcesContents[key]
  35934. : null;
  35935. }, this);
  35936. };
  35937. /**
  35938. * Externalize the source map.
  35939. */
  35940. SourceMapGenerator$5.prototype.toJSON =
  35941. function SourceMapGenerator_toJSON() {
  35942. var map = {
  35943. version: this._version,
  35944. sources: this._sources.toArray(),
  35945. names: this._names.toArray(),
  35946. mappings: this._serializeMappings()
  35947. };
  35948. if (this._file != null) {
  35949. map.file = this._file;
  35950. }
  35951. if (this._sourceRoot != null) {
  35952. map.sourceRoot = this._sourceRoot;
  35953. }
  35954. if (this._sourcesContents) {
  35955. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  35956. }
  35957. return map;
  35958. };
  35959. /**
  35960. * Render the source map being generated to a string.
  35961. */
  35962. SourceMapGenerator$5.prototype.toString =
  35963. function SourceMapGenerator_toString() {
  35964. return JSON.stringify(this.toJSON());
  35965. };
  35966. sourceMapGenerator.SourceMapGenerator = SourceMapGenerator$5;
  35967. var sourceMapConsumer = {};
  35968. var binarySearch$1 = {};
  35969. /* -*- Mode: js; js-indent-level: 2; -*- */
  35970. (function (exports) {
  35971. /*
  35972. * Copyright 2011 Mozilla Foundation and contributors
  35973. * Licensed under the New BSD license. See LICENSE or:
  35974. * http://opensource.org/licenses/BSD-3-Clause
  35975. */
  35976. exports.GREATEST_LOWER_BOUND = 1;
  35977. exports.LEAST_UPPER_BOUND = 2;
  35978. /**
  35979. * Recursive implementation of binary search.
  35980. *
  35981. * @param aLow Indices here and lower do not contain the needle.
  35982. * @param aHigh Indices here and higher do not contain the needle.
  35983. * @param aNeedle The element being searched for.
  35984. * @param aHaystack The non-empty array being searched.
  35985. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  35986. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  35987. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  35988. * closest element that is smaller than or greater than the one we are
  35989. * searching for, respectively, if the exact element cannot be found.
  35990. */
  35991. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  35992. // This function terminates when one of the following is true:
  35993. //
  35994. // 1. We find the exact element we are looking for.
  35995. //
  35996. // 2. We did not find the exact element, but we can return the index of
  35997. // the next-closest element.
  35998. //
  35999. // 3. We did not find the exact element, and there is no next-closest
  36000. // element than the one we are searching for, so we return -1.
  36001. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  36002. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  36003. if (cmp === 0) {
  36004. // Found the element we are looking for.
  36005. return mid;
  36006. }
  36007. else if (cmp > 0) {
  36008. // Our needle is greater than aHaystack[mid].
  36009. if (aHigh - mid > 1) {
  36010. // The element is in the upper half.
  36011. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  36012. }
  36013. // The exact needle element was not found in this haystack. Determine if
  36014. // we are in termination case (3) or (2) and return the appropriate thing.
  36015. if (aBias == exports.LEAST_UPPER_BOUND) {
  36016. return aHigh < aHaystack.length ? aHigh : -1;
  36017. } else {
  36018. return mid;
  36019. }
  36020. }
  36021. else {
  36022. // Our needle is less than aHaystack[mid].
  36023. if (mid - aLow > 1) {
  36024. // The element is in the lower half.
  36025. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  36026. }
  36027. // we are in termination case (3) or (2) and return the appropriate thing.
  36028. if (aBias == exports.LEAST_UPPER_BOUND) {
  36029. return mid;
  36030. } else {
  36031. return aLow < 0 ? -1 : aLow;
  36032. }
  36033. }
  36034. }
  36035. /**
  36036. * This is an implementation of binary search which will always try and return
  36037. * the index of the closest element if there is no exact hit. This is because
  36038. * mappings between original and generated line/col pairs are single points,
  36039. * and there is an implicit region between each of them, so a miss just means
  36040. * that you aren't on the very start of a region.
  36041. *
  36042. * @param aNeedle The element you are looking for.
  36043. * @param aHaystack The array that is being searched.
  36044. * @param aCompare A function which takes the needle and an element in the
  36045. * array and returns -1, 0, or 1 depending on whether the needle is less
  36046. * than, equal to, or greater than the element, respectively.
  36047. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  36048. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  36049. * closest element that is smaller than or greater than the one we are
  36050. * searching for, respectively, if the exact element cannot be found.
  36051. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  36052. */
  36053. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  36054. if (aHaystack.length === 0) {
  36055. return -1;
  36056. }
  36057. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  36058. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  36059. if (index < 0) {
  36060. return -1;
  36061. }
  36062. // We have found either the exact element, or the next-closest element than
  36063. // the one we are searching for. However, there may be more than one such
  36064. // element. Make sure we always return the smallest of these.
  36065. while (index - 1 >= 0) {
  36066. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  36067. break;
  36068. }
  36069. --index;
  36070. }
  36071. return index;
  36072. };
  36073. } (binarySearch$1));
  36074. var quickSort$1 = {};
  36075. /* -*- Mode: js; js-indent-level: 2; -*- */
  36076. /*
  36077. * Copyright 2011 Mozilla Foundation and contributors
  36078. * Licensed under the New BSD license. See LICENSE or:
  36079. * http://opensource.org/licenses/BSD-3-Clause
  36080. */
  36081. // It turns out that some (most?) JavaScript engines don't self-host
  36082. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  36083. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  36084. // custom comparator function, calling back and forth between the VM's C++ and
  36085. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  36086. // worse generated code for the comparator function than would be optimal. In
  36087. // fact, when sorting with a comparator, these costs outweigh the benefits of
  36088. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  36089. // a ~3500ms mean speed-up in `bench/bench.html`.
  36090. function SortTemplate(comparator) {
  36091. /**
  36092. * Swap the elements indexed by `x` and `y` in the array `ary`.
  36093. *
  36094. * @param {Array} ary
  36095. * The array.
  36096. * @param {Number} x
  36097. * The index of the first item.
  36098. * @param {Number} y
  36099. * The index of the second item.
  36100. */
  36101. function swap(ary, x, y) {
  36102. var temp = ary[x];
  36103. ary[x] = ary[y];
  36104. ary[y] = temp;
  36105. }
  36106. /**
  36107. * Returns a random integer within the range `low .. high` inclusive.
  36108. *
  36109. * @param {Number} low
  36110. * The lower bound on the range.
  36111. * @param {Number} high
  36112. * The upper bound on the range.
  36113. */
  36114. function randomIntInRange(low, high) {
  36115. return Math.round(low + (Math.random() * (high - low)));
  36116. }
  36117. /**
  36118. * The Quick Sort algorithm.
  36119. *
  36120. * @param {Array} ary
  36121. * An array to sort.
  36122. * @param {function} comparator
  36123. * Function to use to compare two items.
  36124. * @param {Number} p
  36125. * Start index of the array
  36126. * @param {Number} r
  36127. * End index of the array
  36128. */
  36129. function doQuickSort(ary, comparator, p, r) {
  36130. // If our lower bound is less than our upper bound, we (1) partition the
  36131. // array into two pieces and (2) recurse on each half. If it is not, this is
  36132. // the empty array and our base case.
  36133. if (p < r) {
  36134. // (1) Partitioning.
  36135. //
  36136. // The partitioning chooses a pivot between `p` and `r` and moves all
  36137. // elements that are less than or equal to the pivot to the before it, and
  36138. // all the elements that are greater than it after it. The effect is that
  36139. // once partition is done, the pivot is in the exact place it will be when
  36140. // the array is put in sorted order, and it will not need to be moved
  36141. // again. This runs in O(n) time.
  36142. // Always choose a random pivot so that an input array which is reverse
  36143. // sorted does not cause O(n^2) running time.
  36144. var pivotIndex = randomIntInRange(p, r);
  36145. var i = p - 1;
  36146. swap(ary, pivotIndex, r);
  36147. var pivot = ary[r];
  36148. // Immediately after `j` is incremented in this loop, the following hold
  36149. // true:
  36150. //
  36151. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  36152. //
  36153. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  36154. for (var j = p; j < r; j++) {
  36155. if (comparator(ary[j], pivot, false) <= 0) {
  36156. i += 1;
  36157. swap(ary, i, j);
  36158. }
  36159. }
  36160. swap(ary, i + 1, j);
  36161. var q = i + 1;
  36162. // (2) Recurse on each half.
  36163. doQuickSort(ary, comparator, p, q - 1);
  36164. doQuickSort(ary, comparator, q + 1, r);
  36165. }
  36166. }
  36167. return doQuickSort;
  36168. }
  36169. function cloneSort(comparator) {
  36170. let template = SortTemplate.toString();
  36171. let templateFn = new Function(`return ${template}`)();
  36172. return templateFn(comparator);
  36173. }
  36174. /**
  36175. * Sort the given array in-place with the given comparator function.
  36176. *
  36177. * @param {Array} ary
  36178. * An array to sort.
  36179. * @param {function} comparator
  36180. * Function to use to compare two items.
  36181. */
  36182. let sortCache = new WeakMap();
  36183. quickSort$1.quickSort = function (ary, comparator, start = 0) {
  36184. let doQuickSort = sortCache.get(comparator);
  36185. if (doQuickSort === void 0) {
  36186. doQuickSort = cloneSort(comparator);
  36187. sortCache.set(comparator, doQuickSort);
  36188. }
  36189. doQuickSort(ary, comparator, start, ary.length - 1);
  36190. };
  36191. /* -*- Mode: js; js-indent-level: 2; -*- */
  36192. /*
  36193. * Copyright 2011 Mozilla Foundation and contributors
  36194. * Licensed under the New BSD license. See LICENSE or:
  36195. * http://opensource.org/licenses/BSD-3-Clause
  36196. */
  36197. var util$2 = util$6;
  36198. var binarySearch = binarySearch$1;
  36199. var ArraySet = arraySet.ArraySet;
  36200. var base64VLQ = base64Vlq;
  36201. var quickSort = quickSort$1.quickSort;
  36202. function SourceMapConsumer$4(aSourceMap, aSourceMapURL) {
  36203. var sourceMap = aSourceMap;
  36204. if (typeof aSourceMap === 'string') {
  36205. sourceMap = util$2.parseSourceMapInput(aSourceMap);
  36206. }
  36207. return sourceMap.sections != null
  36208. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  36209. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  36210. }
  36211. SourceMapConsumer$4.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  36212. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  36213. };
  36214. /**
  36215. * The version of the source mapping spec that we are consuming.
  36216. */
  36217. SourceMapConsumer$4.prototype._version = 3;
  36218. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  36219. // parsed mapping coordinates from the source map's "mappings" attribute. They
  36220. // are lazily instantiated, accessed via the `_generatedMappings` and
  36221. // `_originalMappings` getters respectively, and we only parse the mappings
  36222. // and create these arrays once queried for a source location. We jump through
  36223. // these hoops because there can be many thousands of mappings, and parsing
  36224. // them is expensive, so we only want to do it if we must.
  36225. //
  36226. // Each object in the arrays is of the form:
  36227. //
  36228. // {
  36229. // generatedLine: The line number in the generated code,
  36230. // generatedColumn: The column number in the generated code,
  36231. // source: The path to the original source file that generated this
  36232. // chunk of code,
  36233. // originalLine: The line number in the original source that
  36234. // corresponds to this chunk of generated code,
  36235. // originalColumn: The column number in the original source that
  36236. // corresponds to this chunk of generated code,
  36237. // name: The name of the original symbol which generated this chunk of
  36238. // code.
  36239. // }
  36240. //
  36241. // All properties except for `generatedLine` and `generatedColumn` can be
  36242. // `null`.
  36243. //
  36244. // `_generatedMappings` is ordered by the generated positions.
  36245. //
  36246. // `_originalMappings` is ordered by the original positions.
  36247. SourceMapConsumer$4.prototype.__generatedMappings = null;
  36248. Object.defineProperty(SourceMapConsumer$4.prototype, '_generatedMappings', {
  36249. configurable: true,
  36250. enumerable: true,
  36251. get: function () {
  36252. if (!this.__generatedMappings) {
  36253. this._parseMappings(this._mappings, this.sourceRoot);
  36254. }
  36255. return this.__generatedMappings;
  36256. }
  36257. });
  36258. SourceMapConsumer$4.prototype.__originalMappings = null;
  36259. Object.defineProperty(SourceMapConsumer$4.prototype, '_originalMappings', {
  36260. configurable: true,
  36261. enumerable: true,
  36262. get: function () {
  36263. if (!this.__originalMappings) {
  36264. this._parseMappings(this._mappings, this.sourceRoot);
  36265. }
  36266. return this.__originalMappings;
  36267. }
  36268. });
  36269. SourceMapConsumer$4.prototype._charIsMappingSeparator =
  36270. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  36271. var c = aStr.charAt(index);
  36272. return c === ";" || c === ",";
  36273. };
  36274. /**
  36275. * Parse the mappings in a string in to a data structure which we can easily
  36276. * query (the ordered arrays in the `this.__generatedMappings` and
  36277. * `this.__originalMappings` properties).
  36278. */
  36279. SourceMapConsumer$4.prototype._parseMappings =
  36280. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  36281. throw new Error("Subclasses must implement _parseMappings");
  36282. };
  36283. SourceMapConsumer$4.GENERATED_ORDER = 1;
  36284. SourceMapConsumer$4.ORIGINAL_ORDER = 2;
  36285. SourceMapConsumer$4.GREATEST_LOWER_BOUND = 1;
  36286. SourceMapConsumer$4.LEAST_UPPER_BOUND = 2;
  36287. /**
  36288. * Iterate over each mapping between an original source/line/column and a
  36289. * generated line/column in this source map.
  36290. *
  36291. * @param Function aCallback
  36292. * The function that is called with each mapping.
  36293. * @param Object aContext
  36294. * Optional. If specified, this object will be the value of `this` every
  36295. * time that `aCallback` is called.
  36296. * @param aOrder
  36297. * Either `SourceMapConsumer.GENERATED_ORDER` or
  36298. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  36299. * iterate over the mappings sorted by the generated file's line/column
  36300. * order or the original's source/line/column order, respectively. Defaults to
  36301. * `SourceMapConsumer.GENERATED_ORDER`.
  36302. */
  36303. SourceMapConsumer$4.prototype.eachMapping =
  36304. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  36305. var context = aContext || null;
  36306. var order = aOrder || SourceMapConsumer$4.GENERATED_ORDER;
  36307. var mappings;
  36308. switch (order) {
  36309. case SourceMapConsumer$4.GENERATED_ORDER:
  36310. mappings = this._generatedMappings;
  36311. break;
  36312. case SourceMapConsumer$4.ORIGINAL_ORDER:
  36313. mappings = this._originalMappings;
  36314. break;
  36315. default:
  36316. throw new Error("Unknown order of iteration.");
  36317. }
  36318. var sourceRoot = this.sourceRoot;
  36319. var boundCallback = aCallback.bind(context);
  36320. var names = this._names;
  36321. var sources = this._sources;
  36322. var sourceMapURL = this._sourceMapURL;
  36323. for (var i = 0, n = mappings.length; i < n; i++) {
  36324. var mapping = mappings[i];
  36325. var source = mapping.source === null ? null : sources.at(mapping.source);
  36326. source = util$2.computeSourceURL(sourceRoot, source, sourceMapURL);
  36327. boundCallback({
  36328. source: source,
  36329. generatedLine: mapping.generatedLine,
  36330. generatedColumn: mapping.generatedColumn,
  36331. originalLine: mapping.originalLine,
  36332. originalColumn: mapping.originalColumn,
  36333. name: mapping.name === null ? null : names.at(mapping.name)
  36334. });
  36335. }
  36336. };
  36337. /**
  36338. * Returns all generated line and column information for the original source,
  36339. * line, and column provided. If no column is provided, returns all mappings
  36340. * corresponding to a either the line we are searching for or the next
  36341. * closest line that has any mappings. Otherwise, returns all mappings
  36342. * corresponding to the given line and either the column we are searching for
  36343. * or the next closest column that has any offsets.
  36344. *
  36345. * The only argument is an object with the following properties:
  36346. *
  36347. * - source: The filename of the original source.
  36348. * - line: The line number in the original source. The line number is 1-based.
  36349. * - column: Optional. the column number in the original source.
  36350. * The column number is 0-based.
  36351. *
  36352. * and an array of objects is returned, each with the following properties:
  36353. *
  36354. * - line: The line number in the generated source, or null. The
  36355. * line number is 1-based.
  36356. * - column: The column number in the generated source, or null.
  36357. * The column number is 0-based.
  36358. */
  36359. SourceMapConsumer$4.prototype.allGeneratedPositionsFor =
  36360. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  36361. var line = util$2.getArg(aArgs, 'line');
  36362. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  36363. // returns the index of the closest mapping less than the needle. By
  36364. // setting needle.originalColumn to 0, we thus find the last mapping for
  36365. // the given line, provided such a mapping exists.
  36366. var needle = {
  36367. source: util$2.getArg(aArgs, 'source'),
  36368. originalLine: line,
  36369. originalColumn: util$2.getArg(aArgs, 'column', 0)
  36370. };
  36371. needle.source = this._findSourceIndex(needle.source);
  36372. if (needle.source < 0) {
  36373. return [];
  36374. }
  36375. var mappings = [];
  36376. var index = this._findMapping(needle,
  36377. this._originalMappings,
  36378. "originalLine",
  36379. "originalColumn",
  36380. util$2.compareByOriginalPositions,
  36381. binarySearch.LEAST_UPPER_BOUND);
  36382. if (index >= 0) {
  36383. var mapping = this._originalMappings[index];
  36384. if (aArgs.column === undefined) {
  36385. var originalLine = mapping.originalLine;
  36386. // Iterate until either we run out of mappings, or we run into
  36387. // a mapping for a different line than the one we found. Since
  36388. // mappings are sorted, this is guaranteed to find all mappings for
  36389. // the line we found.
  36390. while (mapping && mapping.originalLine === originalLine) {
  36391. mappings.push({
  36392. line: util$2.getArg(mapping, 'generatedLine', null),
  36393. column: util$2.getArg(mapping, 'generatedColumn', null),
  36394. lastColumn: util$2.getArg(mapping, 'lastGeneratedColumn', null)
  36395. });
  36396. mapping = this._originalMappings[++index];
  36397. }
  36398. } else {
  36399. var originalColumn = mapping.originalColumn;
  36400. // Iterate until either we run out of mappings, or we run into
  36401. // a mapping for a different line than the one we were searching for.
  36402. // Since mappings are sorted, this is guaranteed to find all mappings for
  36403. // the line we are searching for.
  36404. while (mapping &&
  36405. mapping.originalLine === line &&
  36406. mapping.originalColumn == originalColumn) {
  36407. mappings.push({
  36408. line: util$2.getArg(mapping, 'generatedLine', null),
  36409. column: util$2.getArg(mapping, 'generatedColumn', null),
  36410. lastColumn: util$2.getArg(mapping, 'lastGeneratedColumn', null)
  36411. });
  36412. mapping = this._originalMappings[++index];
  36413. }
  36414. }
  36415. }
  36416. return mappings;
  36417. };
  36418. sourceMapConsumer.SourceMapConsumer = SourceMapConsumer$4;
  36419. /**
  36420. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  36421. * query for information about the original file positions by giving it a file
  36422. * position in the generated source.
  36423. *
  36424. * The first parameter is the raw source map (either as a JSON string, or
  36425. * already parsed to an object). According to the spec, source maps have the
  36426. * following attributes:
  36427. *
  36428. * - version: Which version of the source map spec this map is following.
  36429. * - sources: An array of URLs to the original source files.
  36430. * - names: An array of identifiers which can be referrenced by individual mappings.
  36431. * - sourceRoot: Optional. The URL root from which all sources are relative.
  36432. * - sourcesContent: Optional. An array of contents of the original source files.
  36433. * - mappings: A string of base64 VLQs which contain the actual mappings.
  36434. * - file: Optional. The generated file this source map is associated with.
  36435. *
  36436. * Here is an example source map, taken from the source map spec[0]:
  36437. *
  36438. * {
  36439. * version : 3,
  36440. * file: "out.js",
  36441. * sourceRoot : "",
  36442. * sources: ["foo.js", "bar.js"],
  36443. * names: ["src", "maps", "are", "fun"],
  36444. * mappings: "AA,AB;;ABCDE;"
  36445. * }
  36446. *
  36447. * The second parameter, if given, is a string whose value is the URL
  36448. * at which the source map was found. This URL is used to compute the
  36449. * sources array.
  36450. *
  36451. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  36452. */
  36453. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  36454. var sourceMap = aSourceMap;
  36455. if (typeof aSourceMap === 'string') {
  36456. sourceMap = util$2.parseSourceMapInput(aSourceMap);
  36457. }
  36458. var version = util$2.getArg(sourceMap, 'version');
  36459. var sources = util$2.getArg(sourceMap, 'sources');
  36460. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  36461. // requires the array) to play nice here.
  36462. var names = util$2.getArg(sourceMap, 'names', []);
  36463. var sourceRoot = util$2.getArg(sourceMap, 'sourceRoot', null);
  36464. var sourcesContent = util$2.getArg(sourceMap, 'sourcesContent', null);
  36465. var mappings = util$2.getArg(sourceMap, 'mappings');
  36466. var file = util$2.getArg(sourceMap, 'file', null);
  36467. // Once again, Sass deviates from the spec and supplies the version as a
  36468. // string rather than a number, so we use loose equality checking here.
  36469. if (version != this._version) {
  36470. throw new Error('Unsupported version: ' + version);
  36471. }
  36472. if (sourceRoot) {
  36473. sourceRoot = util$2.normalize(sourceRoot);
  36474. }
  36475. sources = sources
  36476. .map(String)
  36477. // Some source maps produce relative source paths like "./foo.js" instead of
  36478. // "foo.js". Normalize these first so that future comparisons will succeed.
  36479. // See bugzil.la/1090768.
  36480. .map(util$2.normalize)
  36481. // Always ensure that absolute sources are internally stored relative to
  36482. // the source root, if the source root is absolute. Not doing this would
  36483. // be particularly problematic when the source root is a prefix of the
  36484. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  36485. .map(function (source) {
  36486. return sourceRoot && util$2.isAbsolute(sourceRoot) && util$2.isAbsolute(source)
  36487. ? util$2.relative(sourceRoot, source)
  36488. : source;
  36489. });
  36490. // Pass `true` below to allow duplicate names and sources. While source maps
  36491. // are intended to be compressed and deduplicated, the TypeScript compiler
  36492. // sometimes generates source maps with duplicates in them. See Github issue
  36493. // #72 and bugzil.la/889492.
  36494. this._names = ArraySet.fromArray(names.map(String), true);
  36495. this._sources = ArraySet.fromArray(sources, true);
  36496. this._absoluteSources = this._sources.toArray().map(function (s) {
  36497. return util$2.computeSourceURL(sourceRoot, s, aSourceMapURL);
  36498. });
  36499. this.sourceRoot = sourceRoot;
  36500. this.sourcesContent = sourcesContent;
  36501. this._mappings = mappings;
  36502. this._sourceMapURL = aSourceMapURL;
  36503. this.file = file;
  36504. }
  36505. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer$4.prototype);
  36506. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer$4;
  36507. /**
  36508. * Utility function to find the index of a source. Returns -1 if not
  36509. * found.
  36510. */
  36511. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  36512. var relativeSource = aSource;
  36513. if (this.sourceRoot != null) {
  36514. relativeSource = util$2.relative(this.sourceRoot, relativeSource);
  36515. }
  36516. if (this._sources.has(relativeSource)) {
  36517. return this._sources.indexOf(relativeSource);
  36518. }
  36519. // Maybe aSource is an absolute URL as returned by |sources|. In
  36520. // this case we can't simply undo the transform.
  36521. var i;
  36522. for (i = 0; i < this._absoluteSources.length; ++i) {
  36523. if (this._absoluteSources[i] == aSource) {
  36524. return i;
  36525. }
  36526. }
  36527. return -1;
  36528. };
  36529. /**
  36530. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  36531. *
  36532. * @param SourceMapGenerator aSourceMap
  36533. * The source map that will be consumed.
  36534. * @param String aSourceMapURL
  36535. * The URL at which the source map can be found (optional)
  36536. * @returns BasicSourceMapConsumer
  36537. */
  36538. BasicSourceMapConsumer.fromSourceMap =
  36539. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  36540. var smc = Object.create(BasicSourceMapConsumer.prototype);
  36541. var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  36542. var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  36543. smc.sourceRoot = aSourceMap._sourceRoot;
  36544. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  36545. smc.sourceRoot);
  36546. smc.file = aSourceMap._file;
  36547. smc._sourceMapURL = aSourceMapURL;
  36548. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  36549. return util$2.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  36550. });
  36551. // Because we are modifying the entries (by converting string sources and
  36552. // names to indices into the sources and names ArraySets), we have to make
  36553. // a copy of the entry or else bad things happen. Shared mutable state
  36554. // strikes again! See github issue #191.
  36555. var generatedMappings = aSourceMap._mappings.toArray().slice();
  36556. var destGeneratedMappings = smc.__generatedMappings = [];
  36557. var destOriginalMappings = smc.__originalMappings = [];
  36558. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  36559. var srcMapping = generatedMappings[i];
  36560. var destMapping = new Mapping;
  36561. destMapping.generatedLine = srcMapping.generatedLine;
  36562. destMapping.generatedColumn = srcMapping.generatedColumn;
  36563. if (srcMapping.source) {
  36564. destMapping.source = sources.indexOf(srcMapping.source);
  36565. destMapping.originalLine = srcMapping.originalLine;
  36566. destMapping.originalColumn = srcMapping.originalColumn;
  36567. if (srcMapping.name) {
  36568. destMapping.name = names.indexOf(srcMapping.name);
  36569. }
  36570. destOriginalMappings.push(destMapping);
  36571. }
  36572. destGeneratedMappings.push(destMapping);
  36573. }
  36574. quickSort(smc.__originalMappings, util$2.compareByOriginalPositions);
  36575. return smc;
  36576. };
  36577. /**
  36578. * The version of the source mapping spec that we are consuming.
  36579. */
  36580. BasicSourceMapConsumer.prototype._version = 3;
  36581. /**
  36582. * The list of original sources.
  36583. */
  36584. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  36585. get: function () {
  36586. return this._absoluteSources.slice();
  36587. }
  36588. });
  36589. /**
  36590. * Provide the JIT with a nice shape / hidden class.
  36591. */
  36592. function Mapping() {
  36593. this.generatedLine = 0;
  36594. this.generatedColumn = 0;
  36595. this.source = null;
  36596. this.originalLine = null;
  36597. this.originalColumn = null;
  36598. this.name = null;
  36599. }
  36600. /**
  36601. * Parse the mappings in a string in to a data structure which we can easily
  36602. * query (the ordered arrays in the `this.__generatedMappings` and
  36603. * `this.__originalMappings` properties).
  36604. */
  36605. const compareGenerated = util$2.compareByGeneratedPositionsDeflatedNoLine;
  36606. function sortGenerated(array, start) {
  36607. let l = array.length;
  36608. let n = array.length - start;
  36609. if (n <= 1) {
  36610. return;
  36611. } else if (n == 2) {
  36612. let a = array[start];
  36613. let b = array[start + 1];
  36614. if (compareGenerated(a, b) > 0) {
  36615. array[start] = b;
  36616. array[start + 1] = a;
  36617. }
  36618. } else if (n < 20) {
  36619. for (let i = start; i < l; i++) {
  36620. for (let j = i; j > start; j--) {
  36621. let a = array[j - 1];
  36622. let b = array[j];
  36623. if (compareGenerated(a, b) <= 0) {
  36624. break;
  36625. }
  36626. array[j - 1] = b;
  36627. array[j] = a;
  36628. }
  36629. }
  36630. } else {
  36631. quickSort(array, compareGenerated, start);
  36632. }
  36633. }
  36634. BasicSourceMapConsumer.prototype._parseMappings =
  36635. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  36636. var generatedLine = 1;
  36637. var previousGeneratedColumn = 0;
  36638. var previousOriginalLine = 0;
  36639. var previousOriginalColumn = 0;
  36640. var previousSource = 0;
  36641. var previousName = 0;
  36642. var length = aStr.length;
  36643. var index = 0;
  36644. var temp = {};
  36645. var originalMappings = [];
  36646. var generatedMappings = [];
  36647. var mapping, segment, end, value;
  36648. let subarrayStart = 0;
  36649. while (index < length) {
  36650. if (aStr.charAt(index) === ';') {
  36651. generatedLine++;
  36652. index++;
  36653. previousGeneratedColumn = 0;
  36654. sortGenerated(generatedMappings, subarrayStart);
  36655. subarrayStart = generatedMappings.length;
  36656. }
  36657. else if (aStr.charAt(index) === ',') {
  36658. index++;
  36659. }
  36660. else {
  36661. mapping = new Mapping();
  36662. mapping.generatedLine = generatedLine;
  36663. for (end = index; end < length; end++) {
  36664. if (this._charIsMappingSeparator(aStr, end)) {
  36665. break;
  36666. }
  36667. }
  36668. aStr.slice(index, end);
  36669. segment = [];
  36670. while (index < end) {
  36671. base64VLQ.decode(aStr, index, temp);
  36672. value = temp.value;
  36673. index = temp.rest;
  36674. segment.push(value);
  36675. }
  36676. if (segment.length === 2) {
  36677. throw new Error('Found a source, but no line and column');
  36678. }
  36679. if (segment.length === 3) {
  36680. throw new Error('Found a source and line, but no column');
  36681. }
  36682. // Generated column.
  36683. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  36684. previousGeneratedColumn = mapping.generatedColumn;
  36685. if (segment.length > 1) {
  36686. // Original source.
  36687. mapping.source = previousSource + segment[1];
  36688. previousSource += segment[1];
  36689. // Original line.
  36690. mapping.originalLine = previousOriginalLine + segment[2];
  36691. previousOriginalLine = mapping.originalLine;
  36692. // Lines are stored 0-based
  36693. mapping.originalLine += 1;
  36694. // Original column.
  36695. mapping.originalColumn = previousOriginalColumn + segment[3];
  36696. previousOriginalColumn = mapping.originalColumn;
  36697. if (segment.length > 4) {
  36698. // Original name.
  36699. mapping.name = previousName + segment[4];
  36700. previousName += segment[4];
  36701. }
  36702. }
  36703. generatedMappings.push(mapping);
  36704. if (typeof mapping.originalLine === 'number') {
  36705. let currentSource = mapping.source;
  36706. while (originalMappings.length <= currentSource) {
  36707. originalMappings.push(null);
  36708. }
  36709. if (originalMappings[currentSource] === null) {
  36710. originalMappings[currentSource] = [];
  36711. }
  36712. originalMappings[currentSource].push(mapping);
  36713. }
  36714. }
  36715. }
  36716. sortGenerated(generatedMappings, subarrayStart);
  36717. this.__generatedMappings = generatedMappings;
  36718. for (var i = 0; i < originalMappings.length; i++) {
  36719. if (originalMappings[i] != null) {
  36720. quickSort(originalMappings[i], util$2.compareByOriginalPositionsNoSource);
  36721. }
  36722. }
  36723. this.__originalMappings = [].concat(...originalMappings);
  36724. };
  36725. /**
  36726. * Find the mapping that best matches the hypothetical "needle" mapping that
  36727. * we are searching for in the given "haystack" of mappings.
  36728. */
  36729. BasicSourceMapConsumer.prototype._findMapping =
  36730. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  36731. aColumnName, aComparator, aBias) {
  36732. // To return the position we are searching for, we must first find the
  36733. // mapping for the given position and then return the opposite position it
  36734. // points to. Because the mappings are sorted, we can use binary search to
  36735. // find the best mapping.
  36736. if (aNeedle[aLineName] <= 0) {
  36737. throw new TypeError('Line must be greater than or equal to 1, got '
  36738. + aNeedle[aLineName]);
  36739. }
  36740. if (aNeedle[aColumnName] < 0) {
  36741. throw new TypeError('Column must be greater than or equal to 0, got '
  36742. + aNeedle[aColumnName]);
  36743. }
  36744. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  36745. };
  36746. /**
  36747. * Compute the last column for each generated mapping. The last column is
  36748. * inclusive.
  36749. */
  36750. BasicSourceMapConsumer.prototype.computeColumnSpans =
  36751. function SourceMapConsumer_computeColumnSpans() {
  36752. for (var index = 0; index < this._generatedMappings.length; ++index) {
  36753. var mapping = this._generatedMappings[index];
  36754. // Mappings do not contain a field for the last generated columnt. We
  36755. // can come up with an optimistic estimate, however, by assuming that
  36756. // mappings are contiguous (i.e. given two consecutive mappings, the
  36757. // first mapping ends where the second one starts).
  36758. if (index + 1 < this._generatedMappings.length) {
  36759. var nextMapping = this._generatedMappings[index + 1];
  36760. if (mapping.generatedLine === nextMapping.generatedLine) {
  36761. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  36762. continue;
  36763. }
  36764. }
  36765. // The last mapping for each line spans the entire line.
  36766. mapping.lastGeneratedColumn = Infinity;
  36767. }
  36768. };
  36769. /**
  36770. * Returns the original source, line, and column information for the generated
  36771. * source's line and column positions provided. The only argument is an object
  36772. * with the following properties:
  36773. *
  36774. * - line: The line number in the generated source. The line number
  36775. * is 1-based.
  36776. * - column: The column number in the generated source. The column
  36777. * number is 0-based.
  36778. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  36779. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  36780. * closest element that is smaller than or greater than the one we are
  36781. * searching for, respectively, if the exact element cannot be found.
  36782. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  36783. *
  36784. * and an object is returned with the following properties:
  36785. *
  36786. * - source: The original source file, or null.
  36787. * - line: The line number in the original source, or null. The
  36788. * line number is 1-based.
  36789. * - column: The column number in the original source, or null. The
  36790. * column number is 0-based.
  36791. * - name: The original identifier, or null.
  36792. */
  36793. BasicSourceMapConsumer.prototype.originalPositionFor =
  36794. function SourceMapConsumer_originalPositionFor(aArgs) {
  36795. var needle = {
  36796. generatedLine: util$2.getArg(aArgs, 'line'),
  36797. generatedColumn: util$2.getArg(aArgs, 'column')
  36798. };
  36799. var index = this._findMapping(
  36800. needle,
  36801. this._generatedMappings,
  36802. "generatedLine",
  36803. "generatedColumn",
  36804. util$2.compareByGeneratedPositionsDeflated,
  36805. util$2.getArg(aArgs, 'bias', SourceMapConsumer$4.GREATEST_LOWER_BOUND)
  36806. );
  36807. if (index >= 0) {
  36808. var mapping = this._generatedMappings[index];
  36809. if (mapping.generatedLine === needle.generatedLine) {
  36810. var source = util$2.getArg(mapping, 'source', null);
  36811. if (source !== null) {
  36812. source = this._sources.at(source);
  36813. source = util$2.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  36814. }
  36815. var name = util$2.getArg(mapping, 'name', null);
  36816. if (name !== null) {
  36817. name = this._names.at(name);
  36818. }
  36819. return {
  36820. source: source,
  36821. line: util$2.getArg(mapping, 'originalLine', null),
  36822. column: util$2.getArg(mapping, 'originalColumn', null),
  36823. name: name
  36824. };
  36825. }
  36826. }
  36827. return {
  36828. source: null,
  36829. line: null,
  36830. column: null,
  36831. name: null
  36832. };
  36833. };
  36834. /**
  36835. * Return true if we have the source content for every source in the source
  36836. * map, false otherwise.
  36837. */
  36838. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  36839. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  36840. if (!this.sourcesContent) {
  36841. return false;
  36842. }
  36843. return this.sourcesContent.length >= this._sources.size() &&
  36844. !this.sourcesContent.some(function (sc) { return sc == null; });
  36845. };
  36846. /**
  36847. * Returns the original source content. The only argument is the url of the
  36848. * original source file. Returns null if no original source content is
  36849. * available.
  36850. */
  36851. BasicSourceMapConsumer.prototype.sourceContentFor =
  36852. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  36853. if (!this.sourcesContent) {
  36854. return null;
  36855. }
  36856. var index = this._findSourceIndex(aSource);
  36857. if (index >= 0) {
  36858. return this.sourcesContent[index];
  36859. }
  36860. var relativeSource = aSource;
  36861. if (this.sourceRoot != null) {
  36862. relativeSource = util$2.relative(this.sourceRoot, relativeSource);
  36863. }
  36864. var url;
  36865. if (this.sourceRoot != null
  36866. && (url = util$2.urlParse(this.sourceRoot))) {
  36867. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  36868. // many users. We can help them out when they expect file:// URIs to
  36869. // behave like it would if they were running a local HTTP server. See
  36870. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  36871. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  36872. if (url.scheme == "file"
  36873. && this._sources.has(fileUriAbsPath)) {
  36874. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  36875. }
  36876. if ((!url.path || url.path == "/")
  36877. && this._sources.has("/" + relativeSource)) {
  36878. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  36879. }
  36880. }
  36881. // This function is used recursively from
  36882. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  36883. // don't want to throw if we can't find the source - we just want to
  36884. // return null, so we provide a flag to exit gracefully.
  36885. if (nullOnMissing) {
  36886. return null;
  36887. }
  36888. else {
  36889. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  36890. }
  36891. };
  36892. /**
  36893. * Returns the generated line and column information for the original source,
  36894. * line, and column positions provided. The only argument is an object with
  36895. * the following properties:
  36896. *
  36897. * - source: The filename of the original source.
  36898. * - line: The line number in the original source. The line number
  36899. * is 1-based.
  36900. * - column: The column number in the original source. The column
  36901. * number is 0-based.
  36902. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  36903. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  36904. * closest element that is smaller than or greater than the one we are
  36905. * searching for, respectively, if the exact element cannot be found.
  36906. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  36907. *
  36908. * and an object is returned with the following properties:
  36909. *
  36910. * - line: The line number in the generated source, or null. The
  36911. * line number is 1-based.
  36912. * - column: The column number in the generated source, or null.
  36913. * The column number is 0-based.
  36914. */
  36915. BasicSourceMapConsumer.prototype.generatedPositionFor =
  36916. function SourceMapConsumer_generatedPositionFor(aArgs) {
  36917. var source = util$2.getArg(aArgs, 'source');
  36918. source = this._findSourceIndex(source);
  36919. if (source < 0) {
  36920. return {
  36921. line: null,
  36922. column: null,
  36923. lastColumn: null
  36924. };
  36925. }
  36926. var needle = {
  36927. source: source,
  36928. originalLine: util$2.getArg(aArgs, 'line'),
  36929. originalColumn: util$2.getArg(aArgs, 'column')
  36930. };
  36931. var index = this._findMapping(
  36932. needle,
  36933. this._originalMappings,
  36934. "originalLine",
  36935. "originalColumn",
  36936. util$2.compareByOriginalPositions,
  36937. util$2.getArg(aArgs, 'bias', SourceMapConsumer$4.GREATEST_LOWER_BOUND)
  36938. );
  36939. if (index >= 0) {
  36940. var mapping = this._originalMappings[index];
  36941. if (mapping.source === needle.source) {
  36942. return {
  36943. line: util$2.getArg(mapping, 'generatedLine', null),
  36944. column: util$2.getArg(mapping, 'generatedColumn', null),
  36945. lastColumn: util$2.getArg(mapping, 'lastGeneratedColumn', null)
  36946. };
  36947. }
  36948. }
  36949. return {
  36950. line: null,
  36951. column: null,
  36952. lastColumn: null
  36953. };
  36954. };
  36955. sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer;
  36956. /**
  36957. * An IndexedSourceMapConsumer instance represents a parsed source map which
  36958. * we can query for information. It differs from BasicSourceMapConsumer in
  36959. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  36960. * input.
  36961. *
  36962. * The first parameter is a raw source map (either as a JSON string, or already
  36963. * parsed to an object). According to the spec for indexed source maps, they
  36964. * have the following attributes:
  36965. *
  36966. * - version: Which version of the source map spec this map is following.
  36967. * - file: Optional. The generated file this source map is associated with.
  36968. * - sections: A list of section definitions.
  36969. *
  36970. * Each value under the "sections" field has two fields:
  36971. * - offset: The offset into the original specified at which this section
  36972. * begins to apply, defined as an object with a "line" and "column"
  36973. * field.
  36974. * - map: A source map definition. This source map could also be indexed,
  36975. * but doesn't have to be.
  36976. *
  36977. * Instead of the "map" field, it's also possible to have a "url" field
  36978. * specifying a URL to retrieve a source map from, but that's currently
  36979. * unsupported.
  36980. *
  36981. * Here's an example source map, taken from the source map spec[0], but
  36982. * modified to omit a section which uses the "url" field.
  36983. *
  36984. * {
  36985. * version : 3,
  36986. * file: "app.js",
  36987. * sections: [{
  36988. * offset: {line:100, column:10},
  36989. * map: {
  36990. * version : 3,
  36991. * file: "section.js",
  36992. * sources: ["foo.js", "bar.js"],
  36993. * names: ["src", "maps", "are", "fun"],
  36994. * mappings: "AAAA,E;;ABCDE;"
  36995. * }
  36996. * }],
  36997. * }
  36998. *
  36999. * The second parameter, if given, is a string whose value is the URL
  37000. * at which the source map was found. This URL is used to compute the
  37001. * sources array.
  37002. *
  37003. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  37004. */
  37005. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  37006. var sourceMap = aSourceMap;
  37007. if (typeof aSourceMap === 'string') {
  37008. sourceMap = util$2.parseSourceMapInput(aSourceMap);
  37009. }
  37010. var version = util$2.getArg(sourceMap, 'version');
  37011. var sections = util$2.getArg(sourceMap, 'sections');
  37012. if (version != this._version) {
  37013. throw new Error('Unsupported version: ' + version);
  37014. }
  37015. this._sources = new ArraySet();
  37016. this._names = new ArraySet();
  37017. var lastOffset = {
  37018. line: -1,
  37019. column: 0
  37020. };
  37021. this._sections = sections.map(function (s) {
  37022. if (s.url) {
  37023. // The url field will require support for asynchronicity.
  37024. // See https://github.com/mozilla/source-map/issues/16
  37025. throw new Error('Support for url field in sections not implemented.');
  37026. }
  37027. var offset = util$2.getArg(s, 'offset');
  37028. var offsetLine = util$2.getArg(offset, 'line');
  37029. var offsetColumn = util$2.getArg(offset, 'column');
  37030. if (offsetLine < lastOffset.line ||
  37031. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  37032. throw new Error('Section offsets must be ordered and non-overlapping.');
  37033. }
  37034. lastOffset = offset;
  37035. return {
  37036. generatedOffset: {
  37037. // The offset fields are 0-based, but we use 1-based indices when
  37038. // encoding/decoding from VLQ.
  37039. generatedLine: offsetLine + 1,
  37040. generatedColumn: offsetColumn + 1
  37041. },
  37042. consumer: new SourceMapConsumer$4(util$2.getArg(s, 'map'), aSourceMapURL)
  37043. }
  37044. });
  37045. }
  37046. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer$4.prototype);
  37047. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer$4;
  37048. /**
  37049. * The version of the source mapping spec that we are consuming.
  37050. */
  37051. IndexedSourceMapConsumer.prototype._version = 3;
  37052. /**
  37053. * The list of original sources.
  37054. */
  37055. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  37056. get: function () {
  37057. var sources = [];
  37058. for (var i = 0; i < this._sections.length; i++) {
  37059. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  37060. sources.push(this._sections[i].consumer.sources[j]);
  37061. }
  37062. }
  37063. return sources;
  37064. }
  37065. });
  37066. /**
  37067. * Returns the original source, line, and column information for the generated
  37068. * source's line and column positions provided. The only argument is an object
  37069. * with the following properties:
  37070. *
  37071. * - line: The line number in the generated source. The line number
  37072. * is 1-based.
  37073. * - column: The column number in the generated source. The column
  37074. * number is 0-based.
  37075. *
  37076. * and an object is returned with the following properties:
  37077. *
  37078. * - source: The original source file, or null.
  37079. * - line: The line number in the original source, or null. The
  37080. * line number is 1-based.
  37081. * - column: The column number in the original source, or null. The
  37082. * column number is 0-based.
  37083. * - name: The original identifier, or null.
  37084. */
  37085. IndexedSourceMapConsumer.prototype.originalPositionFor =
  37086. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  37087. var needle = {
  37088. generatedLine: util$2.getArg(aArgs, 'line'),
  37089. generatedColumn: util$2.getArg(aArgs, 'column')
  37090. };
  37091. // Find the section containing the generated position we're trying to map
  37092. // to an original position.
  37093. var sectionIndex = binarySearch.search(needle, this._sections,
  37094. function(needle, section) {
  37095. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  37096. if (cmp) {
  37097. return cmp;
  37098. }
  37099. return (needle.generatedColumn -
  37100. section.generatedOffset.generatedColumn);
  37101. });
  37102. var section = this._sections[sectionIndex];
  37103. if (!section) {
  37104. return {
  37105. source: null,
  37106. line: null,
  37107. column: null,
  37108. name: null
  37109. };
  37110. }
  37111. return section.consumer.originalPositionFor({
  37112. line: needle.generatedLine -
  37113. (section.generatedOffset.generatedLine - 1),
  37114. column: needle.generatedColumn -
  37115. (section.generatedOffset.generatedLine === needle.generatedLine
  37116. ? section.generatedOffset.generatedColumn - 1
  37117. : 0),
  37118. bias: aArgs.bias
  37119. });
  37120. };
  37121. /**
  37122. * Return true if we have the source content for every source in the source
  37123. * map, false otherwise.
  37124. */
  37125. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  37126. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  37127. return this._sections.every(function (s) {
  37128. return s.consumer.hasContentsOfAllSources();
  37129. });
  37130. };
  37131. /**
  37132. * Returns the original source content. The only argument is the url of the
  37133. * original source file. Returns null if no original source content is
  37134. * available.
  37135. */
  37136. IndexedSourceMapConsumer.prototype.sourceContentFor =
  37137. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  37138. for (var i = 0; i < this._sections.length; i++) {
  37139. var section = this._sections[i];
  37140. var content = section.consumer.sourceContentFor(aSource, true);
  37141. if (content) {
  37142. return content;
  37143. }
  37144. }
  37145. if (nullOnMissing) {
  37146. return null;
  37147. }
  37148. else {
  37149. throw new Error('"' + aSource + '" is not in the SourceMap.');
  37150. }
  37151. };
  37152. /**
  37153. * Returns the generated line and column information for the original source,
  37154. * line, and column positions provided. The only argument is an object with
  37155. * the following properties:
  37156. *
  37157. * - source: The filename of the original source.
  37158. * - line: The line number in the original source. The line number
  37159. * is 1-based.
  37160. * - column: The column number in the original source. The column
  37161. * number is 0-based.
  37162. *
  37163. * and an object is returned with the following properties:
  37164. *
  37165. * - line: The line number in the generated source, or null. The
  37166. * line number is 1-based.
  37167. * - column: The column number in the generated source, or null.
  37168. * The column number is 0-based.
  37169. */
  37170. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  37171. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  37172. for (var i = 0; i < this._sections.length; i++) {
  37173. var section = this._sections[i];
  37174. // Only consider this section if the requested source is in the list of
  37175. // sources of the consumer.
  37176. if (section.consumer._findSourceIndex(util$2.getArg(aArgs, 'source')) === -1) {
  37177. continue;
  37178. }
  37179. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  37180. if (generatedPosition) {
  37181. var ret = {
  37182. line: generatedPosition.line +
  37183. (section.generatedOffset.generatedLine - 1),
  37184. column: generatedPosition.column +
  37185. (section.generatedOffset.generatedLine === generatedPosition.line
  37186. ? section.generatedOffset.generatedColumn - 1
  37187. : 0)
  37188. };
  37189. return ret;
  37190. }
  37191. }
  37192. return {
  37193. line: null,
  37194. column: null
  37195. };
  37196. };
  37197. /**
  37198. * Parse the mappings in a string in to a data structure which we can easily
  37199. * query (the ordered arrays in the `this.__generatedMappings` and
  37200. * `this.__originalMappings` properties).
  37201. */
  37202. IndexedSourceMapConsumer.prototype._parseMappings =
  37203. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  37204. this.__generatedMappings = [];
  37205. this.__originalMappings = [];
  37206. for (var i = 0; i < this._sections.length; i++) {
  37207. var section = this._sections[i];
  37208. var sectionMappings = section.consumer._generatedMappings;
  37209. for (var j = 0; j < sectionMappings.length; j++) {
  37210. var mapping = sectionMappings[j];
  37211. var source = section.consumer._sources.at(mapping.source);
  37212. source = util$2.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  37213. this._sources.add(source);
  37214. source = this._sources.indexOf(source);
  37215. var name = null;
  37216. if (mapping.name) {
  37217. name = section.consumer._names.at(mapping.name);
  37218. this._names.add(name);
  37219. name = this._names.indexOf(name);
  37220. }
  37221. // The mappings coming from the consumer for the section have
  37222. // generated positions relative to the start of the section, so we
  37223. // need to offset them to be relative to the start of the concatenated
  37224. // generated file.
  37225. var adjustedMapping = {
  37226. source: source,
  37227. generatedLine: mapping.generatedLine +
  37228. (section.generatedOffset.generatedLine - 1),
  37229. generatedColumn: mapping.generatedColumn +
  37230. (section.generatedOffset.generatedLine === mapping.generatedLine
  37231. ? section.generatedOffset.generatedColumn - 1
  37232. : 0),
  37233. originalLine: mapping.originalLine,
  37234. originalColumn: mapping.originalColumn,
  37235. name: name
  37236. };
  37237. this.__generatedMappings.push(adjustedMapping);
  37238. if (typeof adjustedMapping.originalLine === 'number') {
  37239. this.__originalMappings.push(adjustedMapping);
  37240. }
  37241. }
  37242. }
  37243. quickSort(this.__generatedMappings, util$2.compareByGeneratedPositionsDeflated);
  37244. quickSort(this.__originalMappings, util$2.compareByOriginalPositions);
  37245. };
  37246. sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  37247. var sourceNode = {};
  37248. /* -*- Mode: js; js-indent-level: 2; -*- */
  37249. /*
  37250. * Copyright 2011 Mozilla Foundation and contributors
  37251. * Licensed under the New BSD license. See LICENSE or:
  37252. * http://opensource.org/licenses/BSD-3-Clause
  37253. */
  37254. var SourceMapGenerator$4 = sourceMapGenerator.SourceMapGenerator;
  37255. var util$1 = util$6;
  37256. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  37257. // operating systems these days (capturing the result).
  37258. var REGEX_NEWLINE = /(\r?\n)/;
  37259. // Newline character code for charCodeAt() comparisons
  37260. var NEWLINE_CODE = 10;
  37261. // Private symbol for identifying `SourceNode`s when multiple versions of
  37262. // the source-map library are loaded. This MUST NOT CHANGE across
  37263. // versions!
  37264. var isSourceNode = "$$$isSourceNode$$$";
  37265. /**
  37266. * SourceNodes provide a way to abstract over interpolating/concatenating
  37267. * snippets of generated JavaScript source code while maintaining the line and
  37268. * column information associated with the original source code.
  37269. *
  37270. * @param aLine The original line number.
  37271. * @param aColumn The original column number.
  37272. * @param aSource The original source's filename.
  37273. * @param aChunks Optional. An array of strings which are snippets of
  37274. * generated JS, or other SourceNodes.
  37275. * @param aName The original identifier.
  37276. */
  37277. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  37278. this.children = [];
  37279. this.sourceContents = {};
  37280. this.line = aLine == null ? null : aLine;
  37281. this.column = aColumn == null ? null : aColumn;
  37282. this.source = aSource == null ? null : aSource;
  37283. this.name = aName == null ? null : aName;
  37284. this[isSourceNode] = true;
  37285. if (aChunks != null) this.add(aChunks);
  37286. }
  37287. /**
  37288. * Creates a SourceNode from generated code and a SourceMapConsumer.
  37289. *
  37290. * @param aGeneratedCode The generated code
  37291. * @param aSourceMapConsumer The SourceMap for the generated code
  37292. * @param aRelativePath Optional. The path that relative sources in the
  37293. * SourceMapConsumer should be relative to.
  37294. */
  37295. SourceNode.fromStringWithSourceMap =
  37296. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  37297. // The SourceNode we want to fill with the generated code
  37298. // and the SourceMap
  37299. var node = new SourceNode();
  37300. // All even indices of this array are one line of the generated code,
  37301. // while all odd indices are the newlines between two adjacent lines
  37302. // (since `REGEX_NEWLINE` captures its match).
  37303. // Processed fragments are accessed by calling `shiftNextLine`.
  37304. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  37305. var remainingLinesIndex = 0;
  37306. var shiftNextLine = function() {
  37307. var lineContents = getNextLine();
  37308. // The last line of a file might not have a newline.
  37309. var newLine = getNextLine() || "";
  37310. return lineContents + newLine;
  37311. function getNextLine() {
  37312. return remainingLinesIndex < remainingLines.length ?
  37313. remainingLines[remainingLinesIndex++] : undefined;
  37314. }
  37315. };
  37316. // We need to remember the position of "remainingLines"
  37317. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  37318. // The generate SourceNodes we need a code range.
  37319. // To extract it current and last mapping is used.
  37320. // Here we store the last mapping.
  37321. var lastMapping = null;
  37322. aSourceMapConsumer.eachMapping(function (mapping) {
  37323. if (lastMapping !== null) {
  37324. // We add the code from "lastMapping" to "mapping":
  37325. // First check if there is a new line in between.
  37326. if (lastGeneratedLine < mapping.generatedLine) {
  37327. // Associate first line with "lastMapping"
  37328. addMappingWithCode(lastMapping, shiftNextLine());
  37329. lastGeneratedLine++;
  37330. lastGeneratedColumn = 0;
  37331. // The remaining code is added without mapping
  37332. } else {
  37333. // There is no new line in between.
  37334. // Associate the code between "lastGeneratedColumn" and
  37335. // "mapping.generatedColumn" with "lastMapping"
  37336. var nextLine = remainingLines[remainingLinesIndex] || '';
  37337. var code = nextLine.substr(0, mapping.generatedColumn -
  37338. lastGeneratedColumn);
  37339. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  37340. lastGeneratedColumn);
  37341. lastGeneratedColumn = mapping.generatedColumn;
  37342. addMappingWithCode(lastMapping, code);
  37343. // No more remaining code, continue
  37344. lastMapping = mapping;
  37345. return;
  37346. }
  37347. }
  37348. // We add the generated code until the first mapping
  37349. // to the SourceNode without any mapping.
  37350. // Each line is added as separate string.
  37351. while (lastGeneratedLine < mapping.generatedLine) {
  37352. node.add(shiftNextLine());
  37353. lastGeneratedLine++;
  37354. }
  37355. if (lastGeneratedColumn < mapping.generatedColumn) {
  37356. var nextLine = remainingLines[remainingLinesIndex] || '';
  37357. node.add(nextLine.substr(0, mapping.generatedColumn));
  37358. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  37359. lastGeneratedColumn = mapping.generatedColumn;
  37360. }
  37361. lastMapping = mapping;
  37362. }, this);
  37363. // We have processed all mappings.
  37364. if (remainingLinesIndex < remainingLines.length) {
  37365. if (lastMapping) {
  37366. // Associate the remaining code in the current line with "lastMapping"
  37367. addMappingWithCode(lastMapping, shiftNextLine());
  37368. }
  37369. // and add the remaining lines without any mapping
  37370. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  37371. }
  37372. // Copy sourcesContent into SourceNode
  37373. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  37374. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  37375. if (content != null) {
  37376. if (aRelativePath != null) {
  37377. sourceFile = util$1.join(aRelativePath, sourceFile);
  37378. }
  37379. node.setSourceContent(sourceFile, content);
  37380. }
  37381. });
  37382. return node;
  37383. function addMappingWithCode(mapping, code) {
  37384. if (mapping === null || mapping.source === undefined) {
  37385. node.add(code);
  37386. } else {
  37387. var source = aRelativePath
  37388. ? util$1.join(aRelativePath, mapping.source)
  37389. : mapping.source;
  37390. node.add(new SourceNode(mapping.originalLine,
  37391. mapping.originalColumn,
  37392. source,
  37393. code,
  37394. mapping.name));
  37395. }
  37396. }
  37397. };
  37398. /**
  37399. * Add a chunk of generated JS to this source node.
  37400. *
  37401. * @param aChunk A string snippet of generated JS code, another instance of
  37402. * SourceNode, or an array where each member is one of those things.
  37403. */
  37404. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  37405. if (Array.isArray(aChunk)) {
  37406. aChunk.forEach(function (chunk) {
  37407. this.add(chunk);
  37408. }, this);
  37409. }
  37410. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  37411. if (aChunk) {
  37412. this.children.push(aChunk);
  37413. }
  37414. }
  37415. else {
  37416. throw new TypeError(
  37417. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  37418. );
  37419. }
  37420. return this;
  37421. };
  37422. /**
  37423. * Add a chunk of generated JS to the beginning of this source node.
  37424. *
  37425. * @param aChunk A string snippet of generated JS code, another instance of
  37426. * SourceNode, or an array where each member is one of those things.
  37427. */
  37428. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  37429. if (Array.isArray(aChunk)) {
  37430. for (var i = aChunk.length-1; i >= 0; i--) {
  37431. this.prepend(aChunk[i]);
  37432. }
  37433. }
  37434. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  37435. this.children.unshift(aChunk);
  37436. }
  37437. else {
  37438. throw new TypeError(
  37439. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  37440. );
  37441. }
  37442. return this;
  37443. };
  37444. /**
  37445. * Walk over the tree of JS snippets in this node and its children. The
  37446. * walking function is called once for each snippet of JS and is passed that
  37447. * snippet and the its original associated source's line/column location.
  37448. *
  37449. * @param aFn The traversal function.
  37450. */
  37451. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  37452. var chunk;
  37453. for (var i = 0, len = this.children.length; i < len; i++) {
  37454. chunk = this.children[i];
  37455. if (chunk[isSourceNode]) {
  37456. chunk.walk(aFn);
  37457. }
  37458. else {
  37459. if (chunk !== '') {
  37460. aFn(chunk, { source: this.source,
  37461. line: this.line,
  37462. column: this.column,
  37463. name: this.name });
  37464. }
  37465. }
  37466. }
  37467. };
  37468. /**
  37469. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  37470. * each of `this.children`.
  37471. *
  37472. * @param aSep The separator.
  37473. */
  37474. SourceNode.prototype.join = function SourceNode_join(aSep) {
  37475. var newChildren;
  37476. var i;
  37477. var len = this.children.length;
  37478. if (len > 0) {
  37479. newChildren = [];
  37480. for (i = 0; i < len-1; i++) {
  37481. newChildren.push(this.children[i]);
  37482. newChildren.push(aSep);
  37483. }
  37484. newChildren.push(this.children[i]);
  37485. this.children = newChildren;
  37486. }
  37487. return this;
  37488. };
  37489. /**
  37490. * Call String.prototype.replace on the very right-most source snippet. Useful
  37491. * for trimming whitespace from the end of a source node, etc.
  37492. *
  37493. * @param aPattern The pattern to replace.
  37494. * @param aReplacement The thing to replace the pattern with.
  37495. */
  37496. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  37497. var lastChild = this.children[this.children.length - 1];
  37498. if (lastChild[isSourceNode]) {
  37499. lastChild.replaceRight(aPattern, aReplacement);
  37500. }
  37501. else if (typeof lastChild === 'string') {
  37502. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  37503. }
  37504. else {
  37505. this.children.push(''.replace(aPattern, aReplacement));
  37506. }
  37507. return this;
  37508. };
  37509. /**
  37510. * Set the source content for a source file. This will be added to the SourceMapGenerator
  37511. * in the sourcesContent field.
  37512. *
  37513. * @param aSourceFile The filename of the source file
  37514. * @param aSourceContent The content of the source file
  37515. */
  37516. SourceNode.prototype.setSourceContent =
  37517. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  37518. this.sourceContents[util$1.toSetString(aSourceFile)] = aSourceContent;
  37519. };
  37520. /**
  37521. * Walk over the tree of SourceNodes. The walking function is called for each
  37522. * source file content and is passed the filename and source content.
  37523. *
  37524. * @param aFn The traversal function.
  37525. */
  37526. SourceNode.prototype.walkSourceContents =
  37527. function SourceNode_walkSourceContents(aFn) {
  37528. for (var i = 0, len = this.children.length; i < len; i++) {
  37529. if (this.children[i][isSourceNode]) {
  37530. this.children[i].walkSourceContents(aFn);
  37531. }
  37532. }
  37533. var sources = Object.keys(this.sourceContents);
  37534. for (var i = 0, len = sources.length; i < len; i++) {
  37535. aFn(util$1.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  37536. }
  37537. };
  37538. /**
  37539. * Return the string representation of this source node. Walks over the tree
  37540. * and concatenates all the various snippets together to one string.
  37541. */
  37542. SourceNode.prototype.toString = function SourceNode_toString() {
  37543. var str = "";
  37544. this.walk(function (chunk) {
  37545. str += chunk;
  37546. });
  37547. return str;
  37548. };
  37549. /**
  37550. * Returns the string representation of this source node along with a source
  37551. * map.
  37552. */
  37553. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  37554. var generated = {
  37555. code: "",
  37556. line: 1,
  37557. column: 0
  37558. };
  37559. var map = new SourceMapGenerator$4(aArgs);
  37560. var sourceMappingActive = false;
  37561. var lastOriginalSource = null;
  37562. var lastOriginalLine = null;
  37563. var lastOriginalColumn = null;
  37564. var lastOriginalName = null;
  37565. this.walk(function (chunk, original) {
  37566. generated.code += chunk;
  37567. if (original.source !== null
  37568. && original.line !== null
  37569. && original.column !== null) {
  37570. if(lastOriginalSource !== original.source
  37571. || lastOriginalLine !== original.line
  37572. || lastOriginalColumn !== original.column
  37573. || lastOriginalName !== original.name) {
  37574. map.addMapping({
  37575. source: original.source,
  37576. original: {
  37577. line: original.line,
  37578. column: original.column
  37579. },
  37580. generated: {
  37581. line: generated.line,
  37582. column: generated.column
  37583. },
  37584. name: original.name
  37585. });
  37586. }
  37587. lastOriginalSource = original.source;
  37588. lastOriginalLine = original.line;
  37589. lastOriginalColumn = original.column;
  37590. lastOriginalName = original.name;
  37591. sourceMappingActive = true;
  37592. } else if (sourceMappingActive) {
  37593. map.addMapping({
  37594. generated: {
  37595. line: generated.line,
  37596. column: generated.column
  37597. }
  37598. });
  37599. lastOriginalSource = null;
  37600. sourceMappingActive = false;
  37601. }
  37602. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  37603. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  37604. generated.line++;
  37605. generated.column = 0;
  37606. // Mappings end at eol
  37607. if (idx + 1 === length) {
  37608. lastOriginalSource = null;
  37609. sourceMappingActive = false;
  37610. } else if (sourceMappingActive) {
  37611. map.addMapping({
  37612. source: original.source,
  37613. original: {
  37614. line: original.line,
  37615. column: original.column
  37616. },
  37617. generated: {
  37618. line: generated.line,
  37619. column: generated.column
  37620. },
  37621. name: original.name
  37622. });
  37623. }
  37624. } else {
  37625. generated.column++;
  37626. }
  37627. }
  37628. });
  37629. this.walkSourceContents(function (sourceFile, sourceContent) {
  37630. map.setSourceContent(sourceFile, sourceContent);
  37631. });
  37632. return { code: generated.code, map: map };
  37633. };
  37634. sourceNode.SourceNode = SourceNode;
  37635. /*
  37636. * Copyright 2009-2011 Mozilla Foundation and contributors
  37637. * Licensed under the New BSD license. See LICENSE.txt or:
  37638. * http://opensource.org/licenses/BSD-3-Clause
  37639. */
  37640. sourceMap$1.SourceMapGenerator = sourceMapGenerator.SourceMapGenerator;
  37641. sourceMap$1.SourceMapConsumer = sourceMapConsumer.SourceMapConsumer;
  37642. sourceMap$1.SourceNode = sourceNode.SourceNode;
  37643. var require$$2 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_url$1);
  37644. let urlAlphabet =
  37645. 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
  37646. let customAlphabet = (alphabet, size) => {
  37647. return () => {
  37648. let id = '';
  37649. let i = size;
  37650. while (i--) {
  37651. id += alphabet[(Math.random() * alphabet.length) | 0];
  37652. }
  37653. return id
  37654. }
  37655. };
  37656. let nanoid$1 = (size = 21) => {
  37657. let id = '';
  37658. let i = size;
  37659. while (i--) {
  37660. id += urlAlphabet[(Math.random() * 64) | 0];
  37661. }
  37662. return id
  37663. };
  37664. var nonSecure = { nanoid: nanoid$1, customAlphabet };
  37665. let { SourceMapConsumer: SourceMapConsumer$3, SourceMapGenerator: SourceMapGenerator$3 } = sourceMap$1;
  37666. let { existsSync, readFileSync } = require$$0$2;
  37667. let { dirname: dirname$1, join } = require$$2$1;
  37668. function fromBase64(str) {
  37669. if (Buffer) {
  37670. return Buffer.from(str, 'base64').toString()
  37671. } else {
  37672. /* c8 ignore next 2 */
  37673. return window.atob(str)
  37674. }
  37675. }
  37676. let PreviousMap$2 = class PreviousMap {
  37677. constructor(css, opts) {
  37678. if (opts.map === false) return
  37679. this.loadAnnotation(css);
  37680. this.inline = this.startWith(this.annotation, 'data:');
  37681. let prev = opts.map ? opts.map.prev : undefined;
  37682. let text = this.loadMap(opts.from, prev);
  37683. if (!this.mapFile && opts.from) {
  37684. this.mapFile = opts.from;
  37685. }
  37686. if (this.mapFile) this.root = dirname$1(this.mapFile);
  37687. if (text) this.text = text;
  37688. }
  37689. consumer() {
  37690. if (!this.consumerCache) {
  37691. this.consumerCache = new SourceMapConsumer$3(this.text);
  37692. }
  37693. return this.consumerCache
  37694. }
  37695. withContent() {
  37696. return !!(
  37697. this.consumer().sourcesContent &&
  37698. this.consumer().sourcesContent.length > 0
  37699. )
  37700. }
  37701. startWith(string, start) {
  37702. if (!string) return false
  37703. return string.substr(0, start.length) === start
  37704. }
  37705. getAnnotationURL(sourceMapString) {
  37706. return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, '').trim()
  37707. }
  37708. loadAnnotation(css) {
  37709. let comments = css.match(/\/\*\s*# sourceMappingURL=/gm);
  37710. if (!comments) return
  37711. // sourceMappingURLs from comments, strings, etc.
  37712. let start = css.lastIndexOf(comments.pop());
  37713. let end = css.indexOf('*/', start);
  37714. if (start > -1 && end > -1) {
  37715. // Locate the last sourceMappingURL to avoid pickin
  37716. this.annotation = this.getAnnotationURL(css.substring(start, end));
  37717. }
  37718. }
  37719. decodeInline(text) {
  37720. let baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/;
  37721. let baseUri = /^data:application\/json;base64,/;
  37722. let charsetUri = /^data:application\/json;charset=utf-?8,/;
  37723. let uri = /^data:application\/json,/;
  37724. if (charsetUri.test(text) || uri.test(text)) {
  37725. return decodeURIComponent(text.substr(RegExp.lastMatch.length))
  37726. }
  37727. if (baseCharsetUri.test(text) || baseUri.test(text)) {
  37728. return fromBase64(text.substr(RegExp.lastMatch.length))
  37729. }
  37730. let encoding = text.match(/data:application\/json;([^,]+),/)[1];
  37731. throw new Error('Unsupported source map encoding ' + encoding)
  37732. }
  37733. loadFile(path) {
  37734. this.root = dirname$1(path);
  37735. if (existsSync(path)) {
  37736. this.mapFile = path;
  37737. return readFileSync(path, 'utf-8').toString().trim()
  37738. }
  37739. }
  37740. loadMap(file, prev) {
  37741. if (prev === false) return false
  37742. if (prev) {
  37743. if (typeof prev === 'string') {
  37744. return prev
  37745. } else if (typeof prev === 'function') {
  37746. let prevPath = prev(file);
  37747. if (prevPath) {
  37748. let map = this.loadFile(prevPath);
  37749. if (!map) {
  37750. throw new Error(
  37751. 'Unable to load previous source map: ' + prevPath.toString()
  37752. )
  37753. }
  37754. return map
  37755. }
  37756. } else if (prev instanceof SourceMapConsumer$3) {
  37757. return SourceMapGenerator$3.fromSourceMap(prev).toString()
  37758. } else if (prev instanceof SourceMapGenerator$3) {
  37759. return prev.toString()
  37760. } else if (this.isMap(prev)) {
  37761. return JSON.stringify(prev)
  37762. } else {
  37763. throw new Error(
  37764. 'Unsupported previous source map format: ' + prev.toString()
  37765. )
  37766. }
  37767. } else if (this.inline) {
  37768. return this.decodeInline(this.annotation)
  37769. } else if (this.annotation) {
  37770. let map = this.annotation;
  37771. if (file) map = join(dirname$1(file), map);
  37772. return this.loadFile(map)
  37773. }
  37774. }
  37775. isMap(map) {
  37776. if (typeof map !== 'object') return false
  37777. return (
  37778. typeof map.mappings === 'string' ||
  37779. typeof map._mappings === 'string' ||
  37780. Array.isArray(map.sections)
  37781. )
  37782. }
  37783. };
  37784. var previousMap = PreviousMap$2;
  37785. PreviousMap$2.default = PreviousMap$2;
  37786. let { SourceMapConsumer: SourceMapConsumer$2, SourceMapGenerator: SourceMapGenerator$2 } = sourceMap$1;
  37787. let { fileURLToPath, pathToFileURL: pathToFileURL$1 } = require$$2;
  37788. let { resolve: resolve$1, isAbsolute } = require$$2$1;
  37789. let { nanoid } = nonSecure;
  37790. let terminalHighlight = terminalHighlight_1;
  37791. let CssSyntaxError$1 = cssSyntaxError;
  37792. let PreviousMap$1 = previousMap;
  37793. let fromOffsetCache = Symbol('fromOffsetCache');
  37794. let sourceMapAvailable$1 = Boolean(SourceMapConsumer$2 && SourceMapGenerator$2);
  37795. let pathAvailable$1 = Boolean(resolve$1 && isAbsolute);
  37796. let Input$4 = class Input {
  37797. constructor(css, opts = {}) {
  37798. if (
  37799. css === null ||
  37800. typeof css === 'undefined' ||
  37801. (typeof css === 'object' && !css.toString)
  37802. ) {
  37803. throw new Error(`PostCSS received ${css} instead of CSS string`)
  37804. }
  37805. this.css = css.toString();
  37806. if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') {
  37807. this.hasBOM = true;
  37808. this.css = this.css.slice(1);
  37809. } else {
  37810. this.hasBOM = false;
  37811. }
  37812. if (opts.from) {
  37813. if (
  37814. !pathAvailable$1 ||
  37815. /^\w+:\/\//.test(opts.from) ||
  37816. isAbsolute(opts.from)
  37817. ) {
  37818. this.file = opts.from;
  37819. } else {
  37820. this.file = resolve$1(opts.from);
  37821. }
  37822. }
  37823. if (pathAvailable$1 && sourceMapAvailable$1) {
  37824. let map = new PreviousMap$1(this.css, opts);
  37825. if (map.text) {
  37826. this.map = map;
  37827. let file = map.consumer().file;
  37828. if (!this.file && file) this.file = this.mapResolve(file);
  37829. }
  37830. }
  37831. if (!this.file) {
  37832. this.id = '<input css ' + nanoid(6) + '>';
  37833. }
  37834. if (this.map) this.map.file = this.from;
  37835. }
  37836. fromOffset(offset) {
  37837. let lastLine, lineToIndex;
  37838. if (!this[fromOffsetCache]) {
  37839. let lines = this.css.split('\n');
  37840. lineToIndex = new Array(lines.length);
  37841. let prevIndex = 0;
  37842. for (let i = 0, l = lines.length; i < l; i++) {
  37843. lineToIndex[i] = prevIndex;
  37844. prevIndex += lines[i].length + 1;
  37845. }
  37846. this[fromOffsetCache] = lineToIndex;
  37847. } else {
  37848. lineToIndex = this[fromOffsetCache];
  37849. }
  37850. lastLine = lineToIndex[lineToIndex.length - 1];
  37851. let min = 0;
  37852. if (offset >= lastLine) {
  37853. min = lineToIndex.length - 1;
  37854. } else {
  37855. let max = lineToIndex.length - 2;
  37856. let mid;
  37857. while (min < max) {
  37858. mid = min + ((max - min) >> 1);
  37859. if (offset < lineToIndex[mid]) {
  37860. max = mid - 1;
  37861. } else if (offset >= lineToIndex[mid + 1]) {
  37862. min = mid + 1;
  37863. } else {
  37864. min = mid;
  37865. break
  37866. }
  37867. }
  37868. }
  37869. return {
  37870. line: min + 1,
  37871. col: offset - lineToIndex[min] + 1
  37872. }
  37873. }
  37874. error(message, line, column, opts = {}) {
  37875. let result, endLine, endColumn;
  37876. if (line && typeof line === 'object') {
  37877. let start = line;
  37878. let end = column;
  37879. if (typeof line.offset === 'number') {
  37880. let pos = this.fromOffset(start.offset);
  37881. line = pos.line;
  37882. column = pos.col;
  37883. } else {
  37884. line = start.line;
  37885. column = start.column;
  37886. }
  37887. if (typeof end.offset === 'number') {
  37888. let pos = this.fromOffset(end.offset);
  37889. endLine = pos.line;
  37890. endColumn = pos.col;
  37891. } else {
  37892. endLine = end.line;
  37893. endColumn = end.column;
  37894. }
  37895. } else if (!column) {
  37896. let pos = this.fromOffset(line);
  37897. line = pos.line;
  37898. column = pos.col;
  37899. }
  37900. let origin = this.origin(line, column, endLine, endColumn);
  37901. if (origin) {
  37902. result = new CssSyntaxError$1(
  37903. message,
  37904. origin.endLine === undefined
  37905. ? origin.line
  37906. : { line: origin.line, column: origin.column },
  37907. origin.endLine === undefined
  37908. ? origin.column
  37909. : { line: origin.endLine, column: origin.endColumn },
  37910. origin.source,
  37911. origin.file,
  37912. opts.plugin
  37913. );
  37914. } else {
  37915. result = new CssSyntaxError$1(
  37916. message,
  37917. endLine === undefined ? line : { line, column },
  37918. endLine === undefined ? column : { line: endLine, column: endColumn },
  37919. this.css,
  37920. this.file,
  37921. opts.plugin
  37922. );
  37923. }
  37924. result.input = { line, column, endLine, endColumn, source: this.css };
  37925. if (this.file) {
  37926. if (pathToFileURL$1) {
  37927. result.input.url = pathToFileURL$1(this.file).toString();
  37928. }
  37929. result.input.file = this.file;
  37930. }
  37931. return result
  37932. }
  37933. origin(line, column, endLine, endColumn) {
  37934. if (!this.map) return false
  37935. let consumer = this.map.consumer();
  37936. let from = consumer.originalPositionFor({ line, column });
  37937. if (!from.source) return false
  37938. let to;
  37939. if (typeof endLine === 'number') {
  37940. to = consumer.originalPositionFor({ line: endLine, column: endColumn });
  37941. }
  37942. let fromUrl;
  37943. if (isAbsolute(from.source)) {
  37944. fromUrl = pathToFileURL$1(from.source);
  37945. } else {
  37946. fromUrl = new URL(
  37947. from.source,
  37948. this.map.consumer().sourceRoot || pathToFileURL$1(this.map.mapFile)
  37949. );
  37950. }
  37951. let result = {
  37952. url: fromUrl.toString(),
  37953. line: from.line,
  37954. column: from.column,
  37955. endLine: to && to.line,
  37956. endColumn: to && to.column
  37957. };
  37958. if (fromUrl.protocol === 'file:') {
  37959. if (fileURLToPath) {
  37960. result.file = fileURLToPath(fromUrl);
  37961. } else {
  37962. /* c8 ignore next 2 */
  37963. throw new Error(`file: protocol is not available in this PostCSS build`)
  37964. }
  37965. }
  37966. let source = consumer.sourceContentFor(from.source);
  37967. if (source) result.source = source;
  37968. return result
  37969. }
  37970. mapResolve(file) {
  37971. if (/^\w+:\/\//.test(file)) {
  37972. return file
  37973. }
  37974. return resolve$1(this.map.consumer().sourceRoot || this.map.root || '.', file)
  37975. }
  37976. get from() {
  37977. return this.file || this.id
  37978. }
  37979. toJSON() {
  37980. let json = {};
  37981. for (let name of ['hasBOM', 'css', 'file', 'id']) {
  37982. if (this[name] != null) {
  37983. json[name] = this[name];
  37984. }
  37985. }
  37986. if (this.map) {
  37987. json.map = { ...this.map };
  37988. if (json.map.consumerCache) {
  37989. json.map.consumerCache = undefined;
  37990. }
  37991. }
  37992. return json
  37993. }
  37994. };
  37995. var input = Input$4;
  37996. Input$4.default = Input$4;
  37997. if (terminalHighlight && terminalHighlight.registerInput) {
  37998. terminalHighlight.registerInput(Input$4);
  37999. }
  38000. let { SourceMapConsumer: SourceMapConsumer$1, SourceMapGenerator: SourceMapGenerator$1 } = sourceMap$1;
  38001. let { dirname, resolve, relative, sep } = require$$2$1;
  38002. let { pathToFileURL } = require$$2;
  38003. let Input$3 = input;
  38004. let sourceMapAvailable = Boolean(SourceMapConsumer$1 && SourceMapGenerator$1);
  38005. let pathAvailable = Boolean(dirname && resolve && relative && sep);
  38006. let MapGenerator$2 = class MapGenerator {
  38007. constructor(stringify, root, opts, cssString) {
  38008. this.stringify = stringify;
  38009. this.mapOpts = opts.map || {};
  38010. this.root = root;
  38011. this.opts = opts;
  38012. this.css = cssString;
  38013. }
  38014. isMap() {
  38015. if (typeof this.opts.map !== 'undefined') {
  38016. return !!this.opts.map
  38017. }
  38018. return this.previous().length > 0
  38019. }
  38020. previous() {
  38021. if (!this.previousMaps) {
  38022. this.previousMaps = [];
  38023. if (this.root) {
  38024. this.root.walk(node => {
  38025. if (node.source && node.source.input.map) {
  38026. let map = node.source.input.map;
  38027. if (!this.previousMaps.includes(map)) {
  38028. this.previousMaps.push(map);
  38029. }
  38030. }
  38031. });
  38032. } else {
  38033. let input = new Input$3(this.css, this.opts);
  38034. if (input.map) this.previousMaps.push(input.map);
  38035. }
  38036. }
  38037. return this.previousMaps
  38038. }
  38039. isInline() {
  38040. if (typeof this.mapOpts.inline !== 'undefined') {
  38041. return this.mapOpts.inline
  38042. }
  38043. let annotation = this.mapOpts.annotation;
  38044. if (typeof annotation !== 'undefined' && annotation !== true) {
  38045. return false
  38046. }
  38047. if (this.previous().length) {
  38048. return this.previous().some(i => i.inline)
  38049. }
  38050. return true
  38051. }
  38052. isSourcesContent() {
  38053. if (typeof this.mapOpts.sourcesContent !== 'undefined') {
  38054. return this.mapOpts.sourcesContent
  38055. }
  38056. if (this.previous().length) {
  38057. return this.previous().some(i => i.withContent())
  38058. }
  38059. return true
  38060. }
  38061. clearAnnotation() {
  38062. if (this.mapOpts.annotation === false) return
  38063. if (this.root) {
  38064. let node;
  38065. for (let i = this.root.nodes.length - 1; i >= 0; i--) {
  38066. node = this.root.nodes[i];
  38067. if (node.type !== 'comment') continue
  38068. if (node.text.indexOf('# sourceMappingURL=') === 0) {
  38069. this.root.removeChild(i);
  38070. }
  38071. }
  38072. } else if (this.css) {
  38073. this.css = this.css.replace(/(\n)?\/\*#[\S\s]*?\*\/$/gm, '');
  38074. }
  38075. }
  38076. setSourcesContent() {
  38077. let already = {};
  38078. if (this.root) {
  38079. this.root.walk(node => {
  38080. if (node.source) {
  38081. let from = node.source.input.from;
  38082. if (from && !already[from]) {
  38083. already[from] = true;
  38084. this.map.setSourceContent(
  38085. this.toUrl(this.path(from)),
  38086. node.source.input.css
  38087. );
  38088. }
  38089. }
  38090. });
  38091. } else if (this.css) {
  38092. let from = this.opts.from
  38093. ? this.toUrl(this.path(this.opts.from))
  38094. : '<no source>';
  38095. this.map.setSourceContent(from, this.css);
  38096. }
  38097. }
  38098. applyPrevMaps() {
  38099. for (let prev of this.previous()) {
  38100. let from = this.toUrl(this.path(prev.file));
  38101. let root = prev.root || dirname(prev.file);
  38102. let map;
  38103. if (this.mapOpts.sourcesContent === false) {
  38104. map = new SourceMapConsumer$1(prev.text);
  38105. if (map.sourcesContent) {
  38106. map.sourcesContent = map.sourcesContent.map(() => null);
  38107. }
  38108. } else {
  38109. map = prev.consumer();
  38110. }
  38111. this.map.applySourceMap(map, from, this.toUrl(this.path(root)));
  38112. }
  38113. }
  38114. isAnnotation() {
  38115. if (this.isInline()) {
  38116. return true
  38117. }
  38118. if (typeof this.mapOpts.annotation !== 'undefined') {
  38119. return this.mapOpts.annotation
  38120. }
  38121. if (this.previous().length) {
  38122. return this.previous().some(i => i.annotation)
  38123. }
  38124. return true
  38125. }
  38126. toBase64(str) {
  38127. if (Buffer) {
  38128. return Buffer.from(str).toString('base64')
  38129. } else {
  38130. return window.btoa(unescape(encodeURIComponent(str)))
  38131. }
  38132. }
  38133. addAnnotation() {
  38134. let content;
  38135. if (this.isInline()) {
  38136. content =
  38137. 'data:application/json;base64,' + this.toBase64(this.map.toString());
  38138. } else if (typeof this.mapOpts.annotation === 'string') {
  38139. content = this.mapOpts.annotation;
  38140. } else if (typeof this.mapOpts.annotation === 'function') {
  38141. content = this.mapOpts.annotation(this.opts.to, this.root);
  38142. } else {
  38143. content = this.outputFile() + '.map';
  38144. }
  38145. let eol = '\n';
  38146. if (this.css.includes('\r\n')) eol = '\r\n';
  38147. this.css += eol + '/*# sourceMappingURL=' + content + ' */';
  38148. }
  38149. outputFile() {
  38150. if (this.opts.to) {
  38151. return this.path(this.opts.to)
  38152. } else if (this.opts.from) {
  38153. return this.path(this.opts.from)
  38154. } else {
  38155. return 'to.css'
  38156. }
  38157. }
  38158. generateMap() {
  38159. if (this.root) {
  38160. this.generateString();
  38161. } else if (this.previous().length === 1) {
  38162. let prev = this.previous()[0].consumer();
  38163. prev.file = this.outputFile();
  38164. this.map = SourceMapGenerator$1.fromSourceMap(prev);
  38165. } else {
  38166. this.map = new SourceMapGenerator$1({ file: this.outputFile() });
  38167. this.map.addMapping({
  38168. source: this.opts.from
  38169. ? this.toUrl(this.path(this.opts.from))
  38170. : '<no source>',
  38171. generated: { line: 1, column: 0 },
  38172. original: { line: 1, column: 0 }
  38173. });
  38174. }
  38175. if (this.isSourcesContent()) this.setSourcesContent();
  38176. if (this.root && this.previous().length > 0) this.applyPrevMaps();
  38177. if (this.isAnnotation()) this.addAnnotation();
  38178. if (this.isInline()) {
  38179. return [this.css]
  38180. } else {
  38181. return [this.css, this.map]
  38182. }
  38183. }
  38184. path(file) {
  38185. if (file.indexOf('<') === 0) return file
  38186. if (/^\w+:\/\//.test(file)) return file
  38187. if (this.mapOpts.absolute) return file
  38188. let from = this.opts.to ? dirname(this.opts.to) : '.';
  38189. if (typeof this.mapOpts.annotation === 'string') {
  38190. from = dirname(resolve(from, this.mapOpts.annotation));
  38191. }
  38192. file = relative(from, file);
  38193. return file
  38194. }
  38195. toUrl(path) {
  38196. if (sep === '\\') {
  38197. path = path.replace(/\\/g, '/');
  38198. }
  38199. return encodeURI(path).replace(/[#?]/g, encodeURIComponent)
  38200. }
  38201. sourcePath(node) {
  38202. if (this.mapOpts.from) {
  38203. return this.toUrl(this.mapOpts.from)
  38204. } else if (this.mapOpts.absolute) {
  38205. if (pathToFileURL) {
  38206. return pathToFileURL(node.source.input.from).toString()
  38207. } else {
  38208. throw new Error(
  38209. '`map.absolute` option is not available in this PostCSS build'
  38210. )
  38211. }
  38212. } else {
  38213. return this.toUrl(this.path(node.source.input.from))
  38214. }
  38215. }
  38216. generateString() {
  38217. this.css = '';
  38218. this.map = new SourceMapGenerator$1({ file: this.outputFile() });
  38219. let line = 1;
  38220. let column = 1;
  38221. let noSource = '<no source>';
  38222. let mapping = {
  38223. source: '',
  38224. generated: { line: 0, column: 0 },
  38225. original: { line: 0, column: 0 }
  38226. };
  38227. let lines, last;
  38228. this.stringify(this.root, (str, node, type) => {
  38229. this.css += str;
  38230. if (node && type !== 'end') {
  38231. mapping.generated.line = line;
  38232. mapping.generated.column = column - 1;
  38233. if (node.source && node.source.start) {
  38234. mapping.source = this.sourcePath(node);
  38235. mapping.original.line = node.source.start.line;
  38236. mapping.original.column = node.source.start.column - 1;
  38237. this.map.addMapping(mapping);
  38238. } else {
  38239. mapping.source = noSource;
  38240. mapping.original.line = 1;
  38241. mapping.original.column = 0;
  38242. this.map.addMapping(mapping);
  38243. }
  38244. }
  38245. lines = str.match(/\n/g);
  38246. if (lines) {
  38247. line += lines.length;
  38248. last = str.lastIndexOf('\n');
  38249. column = str.length - last;
  38250. } else {
  38251. column += str.length;
  38252. }
  38253. if (node && type !== 'start') {
  38254. let p = node.parent || { raws: {} };
  38255. if (node.type !== 'decl' || node !== p.last || p.raws.semicolon) {
  38256. if (node.source && node.source.end) {
  38257. mapping.source = this.sourcePath(node);
  38258. mapping.original.line = node.source.end.line;
  38259. mapping.original.column = node.source.end.column - 1;
  38260. mapping.generated.line = line;
  38261. mapping.generated.column = column - 2;
  38262. this.map.addMapping(mapping);
  38263. } else {
  38264. mapping.source = noSource;
  38265. mapping.original.line = 1;
  38266. mapping.original.column = 0;
  38267. mapping.generated.line = line;
  38268. mapping.generated.column = column - 1;
  38269. this.map.addMapping(mapping);
  38270. }
  38271. }
  38272. }
  38273. });
  38274. }
  38275. generate() {
  38276. this.clearAnnotation();
  38277. if (pathAvailable && sourceMapAvailable && this.isMap()) {
  38278. return this.generateMap()
  38279. } else {
  38280. let result = '';
  38281. this.stringify(this.root, i => {
  38282. result += i;
  38283. });
  38284. return [result]
  38285. }
  38286. }
  38287. };
  38288. var mapGenerator = MapGenerator$2;
  38289. let Node$2 = node$2;
  38290. let Comment$4 = class Comment extends Node$2 {
  38291. constructor(defaults) {
  38292. super(defaults);
  38293. this.type = 'comment';
  38294. }
  38295. };
  38296. var comment$3 = Comment$4;
  38297. Comment$4.default = Comment$4;
  38298. let { isClean: isClean$1, my: my$1 } = symbols;
  38299. let Declaration$3 = declaration;
  38300. let Comment$3 = comment$3;
  38301. let Node$1 = node$2;
  38302. let parse$4, Rule$4, AtRule$4;
  38303. function cleanSource(nodes) {
  38304. return nodes.map(i => {
  38305. if (i.nodes) i.nodes = cleanSource(i.nodes);
  38306. delete i.source;
  38307. return i
  38308. })
  38309. }
  38310. function markDirtyUp(node) {
  38311. node[isClean$1] = false;
  38312. if (node.proxyOf.nodes) {
  38313. for (let i of node.proxyOf.nodes) {
  38314. markDirtyUp(i);
  38315. }
  38316. }
  38317. }
  38318. let Container$7 = class Container extends Node$1 {
  38319. push(child) {
  38320. child.parent = this;
  38321. this.proxyOf.nodes.push(child);
  38322. return this
  38323. }
  38324. each(callback) {
  38325. if (!this.proxyOf.nodes) return undefined
  38326. let iterator = this.getIterator();
  38327. let index, result;
  38328. while (this.indexes[iterator] < this.proxyOf.nodes.length) {
  38329. index = this.indexes[iterator];
  38330. result = callback(this.proxyOf.nodes[index], index);
  38331. if (result === false) break
  38332. this.indexes[iterator] += 1;
  38333. }
  38334. delete this.indexes[iterator];
  38335. return result
  38336. }
  38337. walk(callback) {
  38338. return this.each((child, i) => {
  38339. let result;
  38340. try {
  38341. result = callback(child, i);
  38342. } catch (e) {
  38343. throw child.addToError(e)
  38344. }
  38345. if (result !== false && child.walk) {
  38346. result = child.walk(callback);
  38347. }
  38348. return result
  38349. })
  38350. }
  38351. walkDecls(prop, callback) {
  38352. if (!callback) {
  38353. callback = prop;
  38354. return this.walk((child, i) => {
  38355. if (child.type === 'decl') {
  38356. return callback(child, i)
  38357. }
  38358. })
  38359. }
  38360. if (prop instanceof RegExp) {
  38361. return this.walk((child, i) => {
  38362. if (child.type === 'decl' && prop.test(child.prop)) {
  38363. return callback(child, i)
  38364. }
  38365. })
  38366. }
  38367. return this.walk((child, i) => {
  38368. if (child.type === 'decl' && child.prop === prop) {
  38369. return callback(child, i)
  38370. }
  38371. })
  38372. }
  38373. walkRules(selector, callback) {
  38374. if (!callback) {
  38375. callback = selector;
  38376. return this.walk((child, i) => {
  38377. if (child.type === 'rule') {
  38378. return callback(child, i)
  38379. }
  38380. })
  38381. }
  38382. if (selector instanceof RegExp) {
  38383. return this.walk((child, i) => {
  38384. if (child.type === 'rule' && selector.test(child.selector)) {
  38385. return callback(child, i)
  38386. }
  38387. })
  38388. }
  38389. return this.walk((child, i) => {
  38390. if (child.type === 'rule' && child.selector === selector) {
  38391. return callback(child, i)
  38392. }
  38393. })
  38394. }
  38395. walkAtRules(name, callback) {
  38396. if (!callback) {
  38397. callback = name;
  38398. return this.walk((child, i) => {
  38399. if (child.type === 'atrule') {
  38400. return callback(child, i)
  38401. }
  38402. })
  38403. }
  38404. if (name instanceof RegExp) {
  38405. return this.walk((child, i) => {
  38406. if (child.type === 'atrule' && name.test(child.name)) {
  38407. return callback(child, i)
  38408. }
  38409. })
  38410. }
  38411. return this.walk((child, i) => {
  38412. if (child.type === 'atrule' && child.name === name) {
  38413. return callback(child, i)
  38414. }
  38415. })
  38416. }
  38417. walkComments(callback) {
  38418. return this.walk((child, i) => {
  38419. if (child.type === 'comment') {
  38420. return callback(child, i)
  38421. }
  38422. })
  38423. }
  38424. append(...children) {
  38425. for (let child of children) {
  38426. let nodes = this.normalize(child, this.last);
  38427. for (let node of nodes) this.proxyOf.nodes.push(node);
  38428. }
  38429. this.markDirty();
  38430. return this
  38431. }
  38432. prepend(...children) {
  38433. children = children.reverse();
  38434. for (let child of children) {
  38435. let nodes = this.normalize(child, this.first, 'prepend').reverse();
  38436. for (let node of nodes) this.proxyOf.nodes.unshift(node);
  38437. for (let id in this.indexes) {
  38438. this.indexes[id] = this.indexes[id] + nodes.length;
  38439. }
  38440. }
  38441. this.markDirty();
  38442. return this
  38443. }
  38444. cleanRaws(keepBetween) {
  38445. super.cleanRaws(keepBetween);
  38446. if (this.nodes) {
  38447. for (let node of this.nodes) node.cleanRaws(keepBetween);
  38448. }
  38449. }
  38450. insertBefore(exist, add) {
  38451. exist = this.index(exist);
  38452. let type = exist === 0 ? 'prepend' : false;
  38453. let nodes = this.normalize(add, this.proxyOf.nodes[exist], type).reverse();
  38454. for (let node of nodes) this.proxyOf.nodes.splice(exist, 0, node);
  38455. let index;
  38456. for (let id in this.indexes) {
  38457. index = this.indexes[id];
  38458. if (exist <= index) {
  38459. this.indexes[id] = index + nodes.length;
  38460. }
  38461. }
  38462. this.markDirty();
  38463. return this
  38464. }
  38465. insertAfter(exist, add) {
  38466. exist = this.index(exist);
  38467. let nodes = this.normalize(add, this.proxyOf.nodes[exist]).reverse();
  38468. for (let node of nodes) this.proxyOf.nodes.splice(exist + 1, 0, node);
  38469. let index;
  38470. for (let id in this.indexes) {
  38471. index = this.indexes[id];
  38472. if (exist < index) {
  38473. this.indexes[id] = index + nodes.length;
  38474. }
  38475. }
  38476. this.markDirty();
  38477. return this
  38478. }
  38479. removeChild(child) {
  38480. child = this.index(child);
  38481. this.proxyOf.nodes[child].parent = undefined;
  38482. this.proxyOf.nodes.splice(child, 1);
  38483. let index;
  38484. for (let id in this.indexes) {
  38485. index = this.indexes[id];
  38486. if (index >= child) {
  38487. this.indexes[id] = index - 1;
  38488. }
  38489. }
  38490. this.markDirty();
  38491. return this
  38492. }
  38493. removeAll() {
  38494. for (let node of this.proxyOf.nodes) node.parent = undefined;
  38495. this.proxyOf.nodes = [];
  38496. this.markDirty();
  38497. return this
  38498. }
  38499. replaceValues(pattern, opts, callback) {
  38500. if (!callback) {
  38501. callback = opts;
  38502. opts = {};
  38503. }
  38504. this.walkDecls(decl => {
  38505. if (opts.props && !opts.props.includes(decl.prop)) return
  38506. if (opts.fast && !decl.value.includes(opts.fast)) return
  38507. decl.value = decl.value.replace(pattern, callback);
  38508. });
  38509. this.markDirty();
  38510. return this
  38511. }
  38512. every(condition) {
  38513. return this.nodes.every(condition)
  38514. }
  38515. some(condition) {
  38516. return this.nodes.some(condition)
  38517. }
  38518. index(child) {
  38519. if (typeof child === 'number') return child
  38520. if (child.proxyOf) child = child.proxyOf;
  38521. return this.proxyOf.nodes.indexOf(child)
  38522. }
  38523. get first() {
  38524. if (!this.proxyOf.nodes) return undefined
  38525. return this.proxyOf.nodes[0]
  38526. }
  38527. get last() {
  38528. if (!this.proxyOf.nodes) return undefined
  38529. return this.proxyOf.nodes[this.proxyOf.nodes.length - 1]
  38530. }
  38531. normalize(nodes, sample) {
  38532. if (typeof nodes === 'string') {
  38533. nodes = cleanSource(parse$4(nodes).nodes);
  38534. } else if (Array.isArray(nodes)) {
  38535. nodes = nodes.slice(0);
  38536. for (let i of nodes) {
  38537. if (i.parent) i.parent.removeChild(i, 'ignore');
  38538. }
  38539. } else if (nodes.type === 'root' && this.type !== 'document') {
  38540. nodes = nodes.nodes.slice(0);
  38541. for (let i of nodes) {
  38542. if (i.parent) i.parent.removeChild(i, 'ignore');
  38543. }
  38544. } else if (nodes.type) {
  38545. nodes = [nodes];
  38546. } else if (nodes.prop) {
  38547. if (typeof nodes.value === 'undefined') {
  38548. throw new Error('Value field is missed in node creation')
  38549. } else if (typeof nodes.value !== 'string') {
  38550. nodes.value = String(nodes.value);
  38551. }
  38552. nodes = [new Declaration$3(nodes)];
  38553. } else if (nodes.selector) {
  38554. nodes = [new Rule$4(nodes)];
  38555. } else if (nodes.name) {
  38556. nodes = [new AtRule$4(nodes)];
  38557. } else if (nodes.text) {
  38558. nodes = [new Comment$3(nodes)];
  38559. } else {
  38560. throw new Error('Unknown node type in node creation')
  38561. }
  38562. let processed = nodes.map(i => {
  38563. /* c8 ignore next */
  38564. if (!i[my$1]) Container$7.rebuild(i);
  38565. i = i.proxyOf;
  38566. if (i.parent) i.parent.removeChild(i);
  38567. if (i[isClean$1]) markDirtyUp(i);
  38568. if (typeof i.raws.before === 'undefined') {
  38569. if (sample && typeof sample.raws.before !== 'undefined') {
  38570. i.raws.before = sample.raws.before.replace(/\S/g, '');
  38571. }
  38572. }
  38573. i.parent = this;
  38574. return i
  38575. });
  38576. return processed
  38577. }
  38578. getProxyProcessor() {
  38579. return {
  38580. set(node, prop, value) {
  38581. if (node[prop] === value) return true
  38582. node[prop] = value;
  38583. if (prop === 'name' || prop === 'params' || prop === 'selector') {
  38584. node.markDirty();
  38585. }
  38586. return true
  38587. },
  38588. get(node, prop) {
  38589. if (prop === 'proxyOf') {
  38590. return node
  38591. } else if (!node[prop]) {
  38592. return node[prop]
  38593. } else if (
  38594. prop === 'each' ||
  38595. (typeof prop === 'string' && prop.startsWith('walk'))
  38596. ) {
  38597. return (...args) => {
  38598. return node[prop](
  38599. ...args.map(i => {
  38600. if (typeof i === 'function') {
  38601. return (child, index) => i(child.toProxy(), index)
  38602. } else {
  38603. return i
  38604. }
  38605. })
  38606. )
  38607. }
  38608. } else if (prop === 'every' || prop === 'some') {
  38609. return cb => {
  38610. return node[prop]((child, ...other) =>
  38611. cb(child.toProxy(), ...other)
  38612. )
  38613. }
  38614. } else if (prop === 'root') {
  38615. return () => node.root().toProxy()
  38616. } else if (prop === 'nodes') {
  38617. return node.nodes.map(i => i.toProxy())
  38618. } else if (prop === 'first' || prop === 'last') {
  38619. return node[prop].toProxy()
  38620. } else {
  38621. return node[prop]
  38622. }
  38623. }
  38624. }
  38625. }
  38626. getIterator() {
  38627. if (!this.lastEach) this.lastEach = 0;
  38628. if (!this.indexes) this.indexes = {};
  38629. this.lastEach += 1;
  38630. let iterator = this.lastEach;
  38631. this.indexes[iterator] = 0;
  38632. return iterator
  38633. }
  38634. };
  38635. Container$7.registerParse = dependant => {
  38636. parse$4 = dependant;
  38637. };
  38638. Container$7.registerRule = dependant => {
  38639. Rule$4 = dependant;
  38640. };
  38641. Container$7.registerAtRule = dependant => {
  38642. AtRule$4 = dependant;
  38643. };
  38644. var container$1 = Container$7;
  38645. Container$7.default = Container$7;
  38646. /* c8 ignore start */
  38647. Container$7.rebuild = node => {
  38648. if (node.type === 'atrule') {
  38649. Object.setPrototypeOf(node, AtRule$4.prototype);
  38650. } else if (node.type === 'rule') {
  38651. Object.setPrototypeOf(node, Rule$4.prototype);
  38652. } else if (node.type === 'decl') {
  38653. Object.setPrototypeOf(node, Declaration$3.prototype);
  38654. } else if (node.type === 'comment') {
  38655. Object.setPrototypeOf(node, Comment$3.prototype);
  38656. }
  38657. node[my$1] = true;
  38658. if (node.nodes) {
  38659. node.nodes.forEach(child => {
  38660. Container$7.rebuild(child);
  38661. });
  38662. }
  38663. };
  38664. let Container$6 = container$1;
  38665. let LazyResult$4, Processor$3;
  38666. let Document$3 = class Document extends Container$6 {
  38667. constructor(defaults) {
  38668. // type needs to be passed to super, otherwise child roots won't be normalized correctly
  38669. super({ type: 'document', ...defaults });
  38670. if (!this.nodes) {
  38671. this.nodes = [];
  38672. }
  38673. }
  38674. toResult(opts = {}) {
  38675. let lazy = new LazyResult$4(new Processor$3(), this, opts);
  38676. return lazy.stringify()
  38677. }
  38678. };
  38679. Document$3.registerLazyResult = dependant => {
  38680. LazyResult$4 = dependant;
  38681. };
  38682. Document$3.registerProcessor = dependant => {
  38683. Processor$3 = dependant;
  38684. };
  38685. var document = Document$3;
  38686. Document$3.default = Document$3;
  38687. /* eslint-disable no-console */
  38688. let printed = {};
  38689. var warnOnce$2 = function warnOnce(message) {
  38690. if (printed[message]) return
  38691. printed[message] = true;
  38692. if (typeof console !== 'undefined' && console.warn) {
  38693. console.warn(message);
  38694. }
  38695. };
  38696. let Warning$2 = class Warning {
  38697. constructor(text, opts = {}) {
  38698. this.type = 'warning';
  38699. this.text = text;
  38700. if (opts.node && opts.node.source) {
  38701. let range = opts.node.rangeBy(opts);
  38702. this.line = range.start.line;
  38703. this.column = range.start.column;
  38704. this.endLine = range.end.line;
  38705. this.endColumn = range.end.column;
  38706. }
  38707. for (let opt in opts) this[opt] = opts[opt];
  38708. }
  38709. toString() {
  38710. if (this.node) {
  38711. return this.node.error(this.text, {
  38712. plugin: this.plugin,
  38713. index: this.index,
  38714. word: this.word
  38715. }).message
  38716. }
  38717. if (this.plugin) {
  38718. return this.plugin + ': ' + this.text
  38719. }
  38720. return this.text
  38721. }
  38722. };
  38723. var warning = Warning$2;
  38724. Warning$2.default = Warning$2;
  38725. let Warning$1 = warning;
  38726. let Result$3 = class Result {
  38727. constructor(processor, root, opts) {
  38728. this.processor = processor;
  38729. this.messages = [];
  38730. this.root = root;
  38731. this.opts = opts;
  38732. this.css = undefined;
  38733. this.map = undefined;
  38734. }
  38735. toString() {
  38736. return this.css
  38737. }
  38738. warn(text, opts = {}) {
  38739. if (!opts.plugin) {
  38740. if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
  38741. opts.plugin = this.lastPlugin.postcssPlugin;
  38742. }
  38743. }
  38744. let warning = new Warning$1(text, opts);
  38745. this.messages.push(warning);
  38746. return warning
  38747. }
  38748. warnings() {
  38749. return this.messages.filter(i => i.type === 'warning')
  38750. }
  38751. get content() {
  38752. return this.css
  38753. }
  38754. };
  38755. var result = Result$3;
  38756. Result$3.default = Result$3;
  38757. let Container$5 = container$1;
  38758. let AtRule$3 = class AtRule extends Container$5 {
  38759. constructor(defaults) {
  38760. super(defaults);
  38761. this.type = 'atrule';
  38762. }
  38763. append(...children) {
  38764. if (!this.proxyOf.nodes) this.nodes = [];
  38765. return super.append(...children)
  38766. }
  38767. prepend(...children) {
  38768. if (!this.proxyOf.nodes) this.nodes = [];
  38769. return super.prepend(...children)
  38770. }
  38771. };
  38772. var atRule = AtRule$3;
  38773. AtRule$3.default = AtRule$3;
  38774. Container$5.registerAtRule(AtRule$3);
  38775. let Container$4 = container$1;
  38776. let LazyResult$3, Processor$2;
  38777. let Root$5 = class Root extends Container$4 {
  38778. constructor(defaults) {
  38779. super(defaults);
  38780. this.type = 'root';
  38781. if (!this.nodes) this.nodes = [];
  38782. }
  38783. removeChild(child, ignore) {
  38784. let index = this.index(child);
  38785. if (!ignore && index === 0 && this.nodes.length > 1) {
  38786. this.nodes[1].raws.before = this.nodes[index].raws.before;
  38787. }
  38788. return super.removeChild(child)
  38789. }
  38790. normalize(child, sample, type) {
  38791. let nodes = super.normalize(child);
  38792. if (sample) {
  38793. if (type === 'prepend') {
  38794. if (this.nodes.length > 1) {
  38795. sample.raws.before = this.nodes[1].raws.before;
  38796. } else {
  38797. delete sample.raws.before;
  38798. }
  38799. } else if (this.first !== sample) {
  38800. for (let node of nodes) {
  38801. node.raws.before = sample.raws.before;
  38802. }
  38803. }
  38804. }
  38805. return nodes
  38806. }
  38807. toResult(opts = {}) {
  38808. let lazy = new LazyResult$3(new Processor$2(), this, opts);
  38809. return lazy.stringify()
  38810. }
  38811. };
  38812. Root$5.registerLazyResult = dependant => {
  38813. LazyResult$3 = dependant;
  38814. };
  38815. Root$5.registerProcessor = dependant => {
  38816. Processor$2 = dependant;
  38817. };
  38818. var root$2 = Root$5;
  38819. Root$5.default = Root$5;
  38820. let list$2 = {
  38821. split(string, separators, last) {
  38822. let array = [];
  38823. let current = '';
  38824. let split = false;
  38825. let func = 0;
  38826. let quote = false;
  38827. let escape = false;
  38828. for (let letter of string) {
  38829. if (escape) {
  38830. escape = false;
  38831. } else if (letter === '\\') {
  38832. escape = true;
  38833. } else if (quote) {
  38834. if (letter === quote) {
  38835. quote = false;
  38836. }
  38837. } else if (letter === '"' || letter === "'") {
  38838. quote = letter;
  38839. } else if (letter === '(') {
  38840. func += 1;
  38841. } else if (letter === ')') {
  38842. if (func > 0) func -= 1;
  38843. } else if (func === 0) {
  38844. if (separators.includes(letter)) split = true;
  38845. }
  38846. if (split) {
  38847. if (current !== '') array.push(current.trim());
  38848. current = '';
  38849. split = false;
  38850. } else {
  38851. current += letter;
  38852. }
  38853. }
  38854. if (last || current !== '') array.push(current.trim());
  38855. return array
  38856. },
  38857. space(string) {
  38858. let spaces = [' ', '\n', '\t'];
  38859. return list$2.split(string, spaces)
  38860. },
  38861. comma(string) {
  38862. return list$2.split(string, [','], true)
  38863. }
  38864. };
  38865. var list_1 = list$2;
  38866. list$2.default = list$2;
  38867. let Container$3 = container$1;
  38868. let list$1 = list_1;
  38869. let Rule$3 = class Rule extends Container$3 {
  38870. constructor(defaults) {
  38871. super(defaults);
  38872. this.type = 'rule';
  38873. if (!this.nodes) this.nodes = [];
  38874. }
  38875. get selectors() {
  38876. return list$1.comma(this.selector)
  38877. }
  38878. set selectors(values) {
  38879. let match = this.selector ? this.selector.match(/,\s*/) : null;
  38880. let sep = match ? match[0] : ',' + this.raw('between', 'beforeOpen');
  38881. this.selector = values.join(sep);
  38882. }
  38883. };
  38884. var rule = Rule$3;
  38885. Rule$3.default = Rule$3;
  38886. Container$3.registerRule(Rule$3);
  38887. let Declaration$2 = declaration;
  38888. let tokenizer = tokenize$1;
  38889. let Comment$2 = comment$3;
  38890. let AtRule$2 = atRule;
  38891. let Root$4 = root$2;
  38892. let Rule$2 = rule;
  38893. let Parser$1 = class Parser {
  38894. constructor(input) {
  38895. this.input = input;
  38896. this.root = new Root$4();
  38897. this.current = this.root;
  38898. this.spaces = '';
  38899. this.semicolon = false;
  38900. this.customProperty = false;
  38901. this.createTokenizer();
  38902. this.root.source = { input, start: { offset: 0, line: 1, column: 1 } };
  38903. }
  38904. createTokenizer() {
  38905. this.tokenizer = tokenizer(this.input);
  38906. }
  38907. parse() {
  38908. let token;
  38909. while (!this.tokenizer.endOfFile()) {
  38910. token = this.tokenizer.nextToken();
  38911. switch (token[0]) {
  38912. case 'space':
  38913. this.spaces += token[1];
  38914. break
  38915. case ';':
  38916. this.freeSemicolon(token);
  38917. break
  38918. case '}':
  38919. this.end(token);
  38920. break
  38921. case 'comment':
  38922. this.comment(token);
  38923. break
  38924. case 'at-word':
  38925. this.atrule(token);
  38926. break
  38927. case '{':
  38928. this.emptyRule(token);
  38929. break
  38930. default:
  38931. this.other(token);
  38932. break
  38933. }
  38934. }
  38935. this.endFile();
  38936. }
  38937. comment(token) {
  38938. let node = new Comment$2();
  38939. this.init(node, token[2]);
  38940. node.source.end = this.getPosition(token[3] || token[2]);
  38941. let text = token[1].slice(2, -2);
  38942. if (/^\s*$/.test(text)) {
  38943. node.text = '';
  38944. node.raws.left = text;
  38945. node.raws.right = '';
  38946. } else {
  38947. let match = text.match(/^(\s*)([^]*\S)(\s*)$/);
  38948. node.text = match[2];
  38949. node.raws.left = match[1];
  38950. node.raws.right = match[3];
  38951. }
  38952. }
  38953. emptyRule(token) {
  38954. let node = new Rule$2();
  38955. this.init(node, token[2]);
  38956. node.selector = '';
  38957. node.raws.between = '';
  38958. this.current = node;
  38959. }
  38960. other(start) {
  38961. let end = false;
  38962. let type = null;
  38963. let colon = false;
  38964. let bracket = null;
  38965. let brackets = [];
  38966. let customProperty = start[1].startsWith('--');
  38967. let tokens = [];
  38968. let token = start;
  38969. while (token) {
  38970. type = token[0];
  38971. tokens.push(token);
  38972. if (type === '(' || type === '[') {
  38973. if (!bracket) bracket = token;
  38974. brackets.push(type === '(' ? ')' : ']');
  38975. } else if (customProperty && colon && type === '{') {
  38976. if (!bracket) bracket = token;
  38977. brackets.push('}');
  38978. } else if (brackets.length === 0) {
  38979. if (type === ';') {
  38980. if (colon) {
  38981. this.decl(tokens, customProperty);
  38982. return
  38983. } else {
  38984. break
  38985. }
  38986. } else if (type === '{') {
  38987. this.rule(tokens);
  38988. return
  38989. } else if (type === '}') {
  38990. this.tokenizer.back(tokens.pop());
  38991. end = true;
  38992. break
  38993. } else if (type === ':') {
  38994. colon = true;
  38995. }
  38996. } else if (type === brackets[brackets.length - 1]) {
  38997. brackets.pop();
  38998. if (brackets.length === 0) bracket = null;
  38999. }
  39000. token = this.tokenizer.nextToken();
  39001. }
  39002. if (this.tokenizer.endOfFile()) end = true;
  39003. if (brackets.length > 0) this.unclosedBracket(bracket);
  39004. if (end && colon) {
  39005. while (tokens.length) {
  39006. token = tokens[tokens.length - 1][0];
  39007. if (token !== 'space' && token !== 'comment') break
  39008. this.tokenizer.back(tokens.pop());
  39009. }
  39010. this.decl(tokens, customProperty);
  39011. } else {
  39012. this.unknownWord(tokens);
  39013. }
  39014. }
  39015. rule(tokens) {
  39016. tokens.pop();
  39017. let node = new Rule$2();
  39018. this.init(node, tokens[0][2]);
  39019. node.raws.between = this.spacesAndCommentsFromEnd(tokens);
  39020. this.raw(node, 'selector', tokens);
  39021. this.current = node;
  39022. }
  39023. decl(tokens, customProperty) {
  39024. let node = new Declaration$2();
  39025. this.init(node, tokens[0][2]);
  39026. let last = tokens[tokens.length - 1];
  39027. if (last[0] === ';') {
  39028. this.semicolon = true;
  39029. tokens.pop();
  39030. }
  39031. node.source.end = this.getPosition(last[3] || last[2]);
  39032. while (tokens[0][0] !== 'word') {
  39033. if (tokens.length === 1) this.unknownWord(tokens);
  39034. node.raws.before += tokens.shift()[1];
  39035. }
  39036. node.source.start = this.getPosition(tokens[0][2]);
  39037. node.prop = '';
  39038. while (tokens.length) {
  39039. let type = tokens[0][0];
  39040. if (type === ':' || type === 'space' || type === 'comment') {
  39041. break
  39042. }
  39043. node.prop += tokens.shift()[1];
  39044. }
  39045. node.raws.between = '';
  39046. let token;
  39047. while (tokens.length) {
  39048. token = tokens.shift();
  39049. if (token[0] === ':') {
  39050. node.raws.between += token[1];
  39051. break
  39052. } else {
  39053. if (token[0] === 'word' && /\w/.test(token[1])) {
  39054. this.unknownWord([token]);
  39055. }
  39056. node.raws.between += token[1];
  39057. }
  39058. }
  39059. if (node.prop[0] === '_' || node.prop[0] === '*') {
  39060. node.raws.before += node.prop[0];
  39061. node.prop = node.prop.slice(1);
  39062. }
  39063. let firstSpaces = this.spacesAndCommentsFromStart(tokens);
  39064. this.precheckMissedSemicolon(tokens);
  39065. for (let i = tokens.length - 1; i >= 0; i--) {
  39066. token = tokens[i];
  39067. if (token[1].toLowerCase() === '!important') {
  39068. node.important = true;
  39069. let string = this.stringFrom(tokens, i);
  39070. string = this.spacesFromEnd(tokens) + string;
  39071. if (string !== ' !important') node.raws.important = string;
  39072. break
  39073. } else if (token[1].toLowerCase() === 'important') {
  39074. let cache = tokens.slice(0);
  39075. let str = '';
  39076. for (let j = i; j > 0; j--) {
  39077. let type = cache[j][0];
  39078. if (str.trim().indexOf('!') === 0 && type !== 'space') {
  39079. break
  39080. }
  39081. str = cache.pop()[1] + str;
  39082. }
  39083. if (str.trim().indexOf('!') === 0) {
  39084. node.important = true;
  39085. node.raws.important = str;
  39086. tokens = cache;
  39087. }
  39088. }
  39089. if (token[0] !== 'space' && token[0] !== 'comment') {
  39090. break
  39091. }
  39092. }
  39093. let hasWord = tokens.some(i => i[0] !== 'space' && i[0] !== 'comment');
  39094. this.raw(node, 'value', tokens);
  39095. if (hasWord) {
  39096. node.raws.between += firstSpaces;
  39097. } else {
  39098. node.value = firstSpaces + node.value;
  39099. }
  39100. if (node.value.includes(':') && !customProperty) {
  39101. this.checkMissedSemicolon(tokens);
  39102. }
  39103. }
  39104. atrule(token) {
  39105. let node = new AtRule$2();
  39106. node.name = token[1].slice(1);
  39107. if (node.name === '') {
  39108. this.unnamedAtrule(node, token);
  39109. }
  39110. this.init(node, token[2]);
  39111. let type;
  39112. let prev;
  39113. let shift;
  39114. let last = false;
  39115. let open = false;
  39116. let params = [];
  39117. let brackets = [];
  39118. while (!this.tokenizer.endOfFile()) {
  39119. token = this.tokenizer.nextToken();
  39120. type = token[0];
  39121. if (type === '(' || type === '[') {
  39122. brackets.push(type === '(' ? ')' : ']');
  39123. } else if (type === '{' && brackets.length > 0) {
  39124. brackets.push('}');
  39125. } else if (type === brackets[brackets.length - 1]) {
  39126. brackets.pop();
  39127. }
  39128. if (brackets.length === 0) {
  39129. if (type === ';') {
  39130. node.source.end = this.getPosition(token[2]);
  39131. this.semicolon = true;
  39132. break
  39133. } else if (type === '{') {
  39134. open = true;
  39135. break
  39136. } else if (type === '}') {
  39137. if (params.length > 0) {
  39138. shift = params.length - 1;
  39139. prev = params[shift];
  39140. while (prev && prev[0] === 'space') {
  39141. prev = params[--shift];
  39142. }
  39143. if (prev) {
  39144. node.source.end = this.getPosition(prev[3] || prev[2]);
  39145. }
  39146. }
  39147. this.end(token);
  39148. break
  39149. } else {
  39150. params.push(token);
  39151. }
  39152. } else {
  39153. params.push(token);
  39154. }
  39155. if (this.tokenizer.endOfFile()) {
  39156. last = true;
  39157. break
  39158. }
  39159. }
  39160. node.raws.between = this.spacesAndCommentsFromEnd(params);
  39161. if (params.length) {
  39162. node.raws.afterName = this.spacesAndCommentsFromStart(params);
  39163. this.raw(node, 'params', params);
  39164. if (last) {
  39165. token = params[params.length - 1];
  39166. node.source.end = this.getPosition(token[3] || token[2]);
  39167. this.spaces = node.raws.between;
  39168. node.raws.between = '';
  39169. }
  39170. } else {
  39171. node.raws.afterName = '';
  39172. node.params = '';
  39173. }
  39174. if (open) {
  39175. node.nodes = [];
  39176. this.current = node;
  39177. }
  39178. }
  39179. end(token) {
  39180. if (this.current.nodes && this.current.nodes.length) {
  39181. this.current.raws.semicolon = this.semicolon;
  39182. }
  39183. this.semicolon = false;
  39184. this.current.raws.after = (this.current.raws.after || '') + this.spaces;
  39185. this.spaces = '';
  39186. if (this.current.parent) {
  39187. this.current.source.end = this.getPosition(token[2]);
  39188. this.current = this.current.parent;
  39189. } else {
  39190. this.unexpectedClose(token);
  39191. }
  39192. }
  39193. endFile() {
  39194. if (this.current.parent) this.unclosedBlock();
  39195. if (this.current.nodes && this.current.nodes.length) {
  39196. this.current.raws.semicolon = this.semicolon;
  39197. }
  39198. this.current.raws.after = (this.current.raws.after || '') + this.spaces;
  39199. }
  39200. freeSemicolon(token) {
  39201. this.spaces += token[1];
  39202. if (this.current.nodes) {
  39203. let prev = this.current.nodes[this.current.nodes.length - 1];
  39204. if (prev && prev.type === 'rule' && !prev.raws.ownSemicolon) {
  39205. prev.raws.ownSemicolon = this.spaces;
  39206. this.spaces = '';
  39207. }
  39208. }
  39209. }
  39210. // Helpers
  39211. getPosition(offset) {
  39212. let pos = this.input.fromOffset(offset);
  39213. return {
  39214. offset,
  39215. line: pos.line,
  39216. column: pos.col
  39217. }
  39218. }
  39219. init(node, offset) {
  39220. this.current.push(node);
  39221. node.source = {
  39222. start: this.getPosition(offset),
  39223. input: this.input
  39224. };
  39225. node.raws.before = this.spaces;
  39226. this.spaces = '';
  39227. if (node.type !== 'comment') this.semicolon = false;
  39228. }
  39229. raw(node, prop, tokens) {
  39230. let token, type;
  39231. let length = tokens.length;
  39232. let value = '';
  39233. let clean = true;
  39234. let next, prev;
  39235. let pattern = /^([#.|])?(\w)+/i;
  39236. for (let i = 0; i < length; i += 1) {
  39237. token = tokens[i];
  39238. type = token[0];
  39239. if (type === 'comment' && node.type === 'rule') {
  39240. prev = tokens[i - 1];
  39241. next = tokens[i + 1];
  39242. if (
  39243. prev[0] !== 'space' &&
  39244. next[0] !== 'space' &&
  39245. pattern.test(prev[1]) &&
  39246. pattern.test(next[1])
  39247. ) {
  39248. value += token[1];
  39249. } else {
  39250. clean = false;
  39251. }
  39252. continue
  39253. }
  39254. if (type === 'comment' || (type === 'space' && i === length - 1)) {
  39255. clean = false;
  39256. } else {
  39257. value += token[1];
  39258. }
  39259. }
  39260. if (!clean) {
  39261. let raw = tokens.reduce((all, i) => all + i[1], '');
  39262. node.raws[prop] = { value, raw };
  39263. }
  39264. node[prop] = value;
  39265. }
  39266. spacesAndCommentsFromEnd(tokens) {
  39267. let lastTokenType;
  39268. let spaces = '';
  39269. while (tokens.length) {
  39270. lastTokenType = tokens[tokens.length - 1][0];
  39271. if (lastTokenType !== 'space' && lastTokenType !== 'comment') break
  39272. spaces = tokens.pop()[1] + spaces;
  39273. }
  39274. return spaces
  39275. }
  39276. spacesAndCommentsFromStart(tokens) {
  39277. let next;
  39278. let spaces = '';
  39279. while (tokens.length) {
  39280. next = tokens[0][0];
  39281. if (next !== 'space' && next !== 'comment') break
  39282. spaces += tokens.shift()[1];
  39283. }
  39284. return spaces
  39285. }
  39286. spacesFromEnd(tokens) {
  39287. let lastTokenType;
  39288. let spaces = '';
  39289. while (tokens.length) {
  39290. lastTokenType = tokens[tokens.length - 1][0];
  39291. if (lastTokenType !== 'space') break
  39292. spaces = tokens.pop()[1] + spaces;
  39293. }
  39294. return spaces
  39295. }
  39296. stringFrom(tokens, from) {
  39297. let result = '';
  39298. for (let i = from; i < tokens.length; i++) {
  39299. result += tokens[i][1];
  39300. }
  39301. tokens.splice(from, tokens.length - from);
  39302. return result
  39303. }
  39304. colon(tokens) {
  39305. let brackets = 0;
  39306. let token, type, prev;
  39307. for (let [i, element] of tokens.entries()) {
  39308. token = element;
  39309. type = token[0];
  39310. if (type === '(') {
  39311. brackets += 1;
  39312. }
  39313. if (type === ')') {
  39314. brackets -= 1;
  39315. }
  39316. if (brackets === 0 && type === ':') {
  39317. if (!prev) {
  39318. this.doubleColon(token);
  39319. } else if (prev[0] === 'word' && prev[1] === 'progid') {
  39320. continue
  39321. } else {
  39322. return i
  39323. }
  39324. }
  39325. prev = token;
  39326. }
  39327. return false
  39328. }
  39329. // Errors
  39330. unclosedBracket(bracket) {
  39331. throw this.input.error(
  39332. 'Unclosed bracket',
  39333. { offset: bracket[2] },
  39334. { offset: bracket[2] + 1 }
  39335. )
  39336. }
  39337. unknownWord(tokens) {
  39338. throw this.input.error(
  39339. 'Unknown word',
  39340. { offset: tokens[0][2] },
  39341. { offset: tokens[0][2] + tokens[0][1].length }
  39342. )
  39343. }
  39344. unexpectedClose(token) {
  39345. throw this.input.error(
  39346. 'Unexpected }',
  39347. { offset: token[2] },
  39348. { offset: token[2] + 1 }
  39349. )
  39350. }
  39351. unclosedBlock() {
  39352. let pos = this.current.source.start;
  39353. throw this.input.error('Unclosed block', pos.line, pos.column)
  39354. }
  39355. doubleColon(token) {
  39356. throw this.input.error(
  39357. 'Double colon',
  39358. { offset: token[2] },
  39359. { offset: token[2] + token[1].length }
  39360. )
  39361. }
  39362. unnamedAtrule(node, token) {
  39363. throw this.input.error(
  39364. 'At-rule without name',
  39365. { offset: token[2] },
  39366. { offset: token[2] + token[1].length }
  39367. )
  39368. }
  39369. precheckMissedSemicolon(/* tokens */) {
  39370. // Hook for Safe Parser
  39371. }
  39372. checkMissedSemicolon(tokens) {
  39373. let colon = this.colon(tokens);
  39374. if (colon === false) return
  39375. let founded = 0;
  39376. let token;
  39377. for (let j = colon - 1; j >= 0; j--) {
  39378. token = tokens[j];
  39379. if (token[0] !== 'space') {
  39380. founded += 1;
  39381. if (founded === 2) break
  39382. }
  39383. }
  39384. // If the token is a word, e.g. `!important`, `red` or any other valid property's value.
  39385. // Then we need to return the colon after that word token. [3] is the "end" colon of that word.
  39386. // And because we need it after that one we do +1 to get the next one.
  39387. throw this.input.error(
  39388. 'Missed semicolon',
  39389. token[0] === 'word' ? token[3] + 1 : token[2]
  39390. )
  39391. }
  39392. };
  39393. var parser$1 = Parser$1;
  39394. let Container$2 = container$1;
  39395. let Parser = parser$1;
  39396. let Input$2 = input;
  39397. function parse$3(css, opts) {
  39398. let input = new Input$2(css, opts);
  39399. let parser = new Parser(input);
  39400. try {
  39401. parser.parse();
  39402. } catch (e) {
  39403. if (browser$1.env.NODE_ENV !== 'production') {
  39404. if (e.name === 'CssSyntaxError' && opts && opts.from) {
  39405. if (/\.scss$/i.test(opts.from)) {
  39406. e.message +=
  39407. '\nYou tried to parse SCSS with ' +
  39408. 'the standard CSS parser; ' +
  39409. 'try again with the postcss-scss parser';
  39410. } else if (/\.sass/i.test(opts.from)) {
  39411. e.message +=
  39412. '\nYou tried to parse Sass with ' +
  39413. 'the standard CSS parser; ' +
  39414. 'try again with the postcss-sass parser';
  39415. } else if (/\.less$/i.test(opts.from)) {
  39416. e.message +=
  39417. '\nYou tried to parse Less with ' +
  39418. 'the standard CSS parser; ' +
  39419. 'try again with the postcss-less parser';
  39420. }
  39421. }
  39422. }
  39423. throw e
  39424. }
  39425. return parser.root
  39426. }
  39427. var parse_1 = parse$3;
  39428. parse$3.default = parse$3;
  39429. Container$2.registerParse(parse$3);
  39430. let { isClean, my } = symbols;
  39431. let MapGenerator$1 = mapGenerator;
  39432. let stringify$2 = stringify_1;
  39433. let Container$1 = container$1;
  39434. let Document$2 = document;
  39435. let warnOnce$1 = warnOnce$2;
  39436. let Result$2 = result;
  39437. let parse$2 = parse_1;
  39438. let Root$3 = root$2;
  39439. const TYPE_TO_CLASS_NAME = {
  39440. document: 'Document',
  39441. root: 'Root',
  39442. atrule: 'AtRule',
  39443. rule: 'Rule',
  39444. decl: 'Declaration',
  39445. comment: 'Comment'
  39446. };
  39447. const PLUGIN_PROPS = {
  39448. postcssPlugin: true,
  39449. prepare: true,
  39450. Once: true,
  39451. Document: true,
  39452. Root: true,
  39453. Declaration: true,
  39454. Rule: true,
  39455. AtRule: true,
  39456. Comment: true,
  39457. DeclarationExit: true,
  39458. RuleExit: true,
  39459. AtRuleExit: true,
  39460. CommentExit: true,
  39461. RootExit: true,
  39462. DocumentExit: true,
  39463. OnceExit: true
  39464. };
  39465. const NOT_VISITORS = {
  39466. postcssPlugin: true,
  39467. prepare: true,
  39468. Once: true
  39469. };
  39470. const CHILDREN = 0;
  39471. function isPromise(obj) {
  39472. return typeof obj === 'object' && typeof obj.then === 'function'
  39473. }
  39474. function getEvents(node) {
  39475. let key = false;
  39476. let type = TYPE_TO_CLASS_NAME[node.type];
  39477. if (node.type === 'decl') {
  39478. key = node.prop.toLowerCase();
  39479. } else if (node.type === 'atrule') {
  39480. key = node.name.toLowerCase();
  39481. }
  39482. if (key && node.append) {
  39483. return [
  39484. type,
  39485. type + '-' + key,
  39486. CHILDREN,
  39487. type + 'Exit',
  39488. type + 'Exit-' + key
  39489. ]
  39490. } else if (key) {
  39491. return [type, type + '-' + key, type + 'Exit', type + 'Exit-' + key]
  39492. } else if (node.append) {
  39493. return [type, CHILDREN, type + 'Exit']
  39494. } else {
  39495. return [type, type + 'Exit']
  39496. }
  39497. }
  39498. function toStack(node) {
  39499. let events;
  39500. if (node.type === 'document') {
  39501. events = ['Document', CHILDREN, 'DocumentExit'];
  39502. } else if (node.type === 'root') {
  39503. events = ['Root', CHILDREN, 'RootExit'];
  39504. } else {
  39505. events = getEvents(node);
  39506. }
  39507. return {
  39508. node,
  39509. events,
  39510. eventIndex: 0,
  39511. visitors: [],
  39512. visitorIndex: 0,
  39513. iterator: 0
  39514. }
  39515. }
  39516. function cleanMarks(node) {
  39517. node[isClean] = false;
  39518. if (node.nodes) node.nodes.forEach(i => cleanMarks(i));
  39519. return node
  39520. }
  39521. let postcss$2 = {};
  39522. let LazyResult$2 = class LazyResult {
  39523. constructor(processor, css, opts) {
  39524. this.stringified = false;
  39525. this.processed = false;
  39526. let root;
  39527. if (
  39528. typeof css === 'object' &&
  39529. css !== null &&
  39530. (css.type === 'root' || css.type === 'document')
  39531. ) {
  39532. root = cleanMarks(css);
  39533. } else if (css instanceof LazyResult$2 || css instanceof Result$2) {
  39534. root = cleanMarks(css.root);
  39535. if (css.map) {
  39536. if (typeof opts.map === 'undefined') opts.map = {};
  39537. if (!opts.map.inline) opts.map.inline = false;
  39538. opts.map.prev = css.map;
  39539. }
  39540. } else {
  39541. let parser = parse$2;
  39542. if (opts.syntax) parser = opts.syntax.parse;
  39543. if (opts.parser) parser = opts.parser;
  39544. if (parser.parse) parser = parser.parse;
  39545. try {
  39546. root = parser(css, opts);
  39547. } catch (error) {
  39548. this.processed = true;
  39549. this.error = error;
  39550. }
  39551. if (root && !root[my]) {
  39552. /* c8 ignore next 2 */
  39553. Container$1.rebuild(root);
  39554. }
  39555. }
  39556. this.result = new Result$2(processor, root, opts);
  39557. this.helpers = { ...postcss$2, result: this.result, postcss: postcss$2 };
  39558. this.plugins = this.processor.plugins.map(plugin => {
  39559. if (typeof plugin === 'object' && plugin.prepare) {
  39560. return { ...plugin, ...plugin.prepare(this.result) }
  39561. } else {
  39562. return plugin
  39563. }
  39564. });
  39565. }
  39566. get [Symbol.toStringTag]() {
  39567. return 'LazyResult'
  39568. }
  39569. get processor() {
  39570. return this.result.processor
  39571. }
  39572. get opts() {
  39573. return this.result.opts
  39574. }
  39575. get css() {
  39576. return this.stringify().css
  39577. }
  39578. get content() {
  39579. return this.stringify().content
  39580. }
  39581. get map() {
  39582. return this.stringify().map
  39583. }
  39584. get root() {
  39585. return this.sync().root
  39586. }
  39587. get messages() {
  39588. return this.sync().messages
  39589. }
  39590. warnings() {
  39591. return this.sync().warnings()
  39592. }
  39593. toString() {
  39594. return this.css
  39595. }
  39596. then(onFulfilled, onRejected) {
  39597. if (browser$1.env.NODE_ENV !== 'production') {
  39598. if (!('from' in this.opts)) {
  39599. warnOnce$1(
  39600. 'Without `from` option PostCSS could generate wrong source map ' +
  39601. 'and will not find Browserslist config. Set it to CSS file path ' +
  39602. 'or to `undefined` to prevent this warning.'
  39603. );
  39604. }
  39605. }
  39606. return this.async().then(onFulfilled, onRejected)
  39607. }
  39608. catch(onRejected) {
  39609. return this.async().catch(onRejected)
  39610. }
  39611. finally(onFinally) {
  39612. return this.async().then(onFinally, onFinally)
  39613. }
  39614. async() {
  39615. if (this.error) return Promise.reject(this.error)
  39616. if (this.processed) return Promise.resolve(this.result)
  39617. if (!this.processing) {
  39618. this.processing = this.runAsync();
  39619. }
  39620. return this.processing
  39621. }
  39622. sync() {
  39623. if (this.error) throw this.error
  39624. if (this.processed) return this.result
  39625. this.processed = true;
  39626. if (this.processing) {
  39627. throw this.getAsyncError()
  39628. }
  39629. for (let plugin of this.plugins) {
  39630. let promise = this.runOnRoot(plugin);
  39631. if (isPromise(promise)) {
  39632. throw this.getAsyncError()
  39633. }
  39634. }
  39635. this.prepareVisitors();
  39636. if (this.hasListener) {
  39637. let root = this.result.root;
  39638. while (!root[isClean]) {
  39639. root[isClean] = true;
  39640. this.walkSync(root);
  39641. }
  39642. if (this.listeners.OnceExit) {
  39643. if (root.type === 'document') {
  39644. for (let subRoot of root.nodes) {
  39645. this.visitSync(this.listeners.OnceExit, subRoot);
  39646. }
  39647. } else {
  39648. this.visitSync(this.listeners.OnceExit, root);
  39649. }
  39650. }
  39651. }
  39652. return this.result
  39653. }
  39654. stringify() {
  39655. if (this.error) throw this.error
  39656. if (this.stringified) return this.result
  39657. this.stringified = true;
  39658. this.sync();
  39659. let opts = this.result.opts;
  39660. let str = stringify$2;
  39661. if (opts.syntax) str = opts.syntax.stringify;
  39662. if (opts.stringifier) str = opts.stringifier;
  39663. if (str.stringify) str = str.stringify;
  39664. let map = new MapGenerator$1(str, this.result.root, this.result.opts);
  39665. let data = map.generate();
  39666. this.result.css = data[0];
  39667. this.result.map = data[1];
  39668. return this.result
  39669. }
  39670. walkSync(node) {
  39671. node[isClean] = true;
  39672. let events = getEvents(node);
  39673. for (let event of events) {
  39674. if (event === CHILDREN) {
  39675. if (node.nodes) {
  39676. node.each(child => {
  39677. if (!child[isClean]) this.walkSync(child);
  39678. });
  39679. }
  39680. } else {
  39681. let visitors = this.listeners[event];
  39682. if (visitors) {
  39683. if (this.visitSync(visitors, node.toProxy())) return
  39684. }
  39685. }
  39686. }
  39687. }
  39688. visitSync(visitors, node) {
  39689. for (let [plugin, visitor] of visitors) {
  39690. this.result.lastPlugin = plugin;
  39691. let promise;
  39692. try {
  39693. promise = visitor(node, this.helpers);
  39694. } catch (e) {
  39695. throw this.handleError(e, node.proxyOf)
  39696. }
  39697. if (node.type !== 'root' && node.type !== 'document' && !node.parent) {
  39698. return true
  39699. }
  39700. if (isPromise(promise)) {
  39701. throw this.getAsyncError()
  39702. }
  39703. }
  39704. }
  39705. runOnRoot(plugin) {
  39706. this.result.lastPlugin = plugin;
  39707. try {
  39708. if (typeof plugin === 'object' && plugin.Once) {
  39709. if (this.result.root.type === 'document') {
  39710. let roots = this.result.root.nodes.map(root =>
  39711. plugin.Once(root, this.helpers)
  39712. );
  39713. if (isPromise(roots[0])) {
  39714. return Promise.all(roots)
  39715. }
  39716. return roots
  39717. }
  39718. return plugin.Once(this.result.root, this.helpers)
  39719. } else if (typeof plugin === 'function') {
  39720. return plugin(this.result.root, this.result)
  39721. }
  39722. } catch (error) {
  39723. throw this.handleError(error)
  39724. }
  39725. }
  39726. getAsyncError() {
  39727. throw new Error('Use process(css).then(cb) to work with async plugins')
  39728. }
  39729. handleError(error, node) {
  39730. let plugin = this.result.lastPlugin;
  39731. try {
  39732. if (node) node.addToError(error);
  39733. this.error = error;
  39734. if (error.name === 'CssSyntaxError' && !error.plugin) {
  39735. error.plugin = plugin.postcssPlugin;
  39736. error.setMessage();
  39737. } else if (plugin.postcssVersion) {
  39738. if (browser$1.env.NODE_ENV !== 'production') {
  39739. let pluginName = plugin.postcssPlugin;
  39740. let pluginVer = plugin.postcssVersion;
  39741. let runtimeVer = this.result.processor.version;
  39742. let a = pluginVer.split('.');
  39743. let b = runtimeVer.split('.');
  39744. if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) {
  39745. // eslint-disable-next-line no-console
  39746. console.error(
  39747. 'Unknown error from PostCSS plugin. Your current PostCSS ' +
  39748. 'version is ' +
  39749. runtimeVer +
  39750. ', but ' +
  39751. pluginName +
  39752. ' uses ' +
  39753. pluginVer +
  39754. '. Perhaps this is the source of the error below.'
  39755. );
  39756. }
  39757. }
  39758. }
  39759. } catch (err) {
  39760. /* c8 ignore next 3 */
  39761. // eslint-disable-next-line no-console
  39762. if (console && console.error) console.error(err);
  39763. }
  39764. return error
  39765. }
  39766. async runAsync() {
  39767. this.plugin = 0;
  39768. for (let i = 0; i < this.plugins.length; i++) {
  39769. let plugin = this.plugins[i];
  39770. let promise = this.runOnRoot(plugin);
  39771. if (isPromise(promise)) {
  39772. try {
  39773. await promise;
  39774. } catch (error) {
  39775. throw this.handleError(error)
  39776. }
  39777. }
  39778. }
  39779. this.prepareVisitors();
  39780. if (this.hasListener) {
  39781. let root = this.result.root;
  39782. while (!root[isClean]) {
  39783. root[isClean] = true;
  39784. let stack = [toStack(root)];
  39785. while (stack.length > 0) {
  39786. let promise = this.visitTick(stack);
  39787. if (isPromise(promise)) {
  39788. try {
  39789. await promise;
  39790. } catch (e) {
  39791. let node = stack[stack.length - 1].node;
  39792. throw this.handleError(e, node)
  39793. }
  39794. }
  39795. }
  39796. }
  39797. if (this.listeners.OnceExit) {
  39798. for (let [plugin, visitor] of this.listeners.OnceExit) {
  39799. this.result.lastPlugin = plugin;
  39800. try {
  39801. if (root.type === 'document') {
  39802. let roots = root.nodes.map(subRoot =>
  39803. visitor(subRoot, this.helpers)
  39804. );
  39805. await Promise.all(roots);
  39806. } else {
  39807. await visitor(root, this.helpers);
  39808. }
  39809. } catch (e) {
  39810. throw this.handleError(e)
  39811. }
  39812. }
  39813. }
  39814. }
  39815. this.processed = true;
  39816. return this.stringify()
  39817. }
  39818. prepareVisitors() {
  39819. this.listeners = {};
  39820. let add = (plugin, type, cb) => {
  39821. if (!this.listeners[type]) this.listeners[type] = [];
  39822. this.listeners[type].push([plugin, cb]);
  39823. };
  39824. for (let plugin of this.plugins) {
  39825. if (typeof plugin === 'object') {
  39826. for (let event in plugin) {
  39827. if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) {
  39828. throw new Error(
  39829. `Unknown event ${event} in ${plugin.postcssPlugin}. ` +
  39830. `Try to update PostCSS (${this.processor.version} now).`
  39831. )
  39832. }
  39833. if (!NOT_VISITORS[event]) {
  39834. if (typeof plugin[event] === 'object') {
  39835. for (let filter in plugin[event]) {
  39836. if (filter === '*') {
  39837. add(plugin, event, plugin[event][filter]);
  39838. } else {
  39839. add(
  39840. plugin,
  39841. event + '-' + filter.toLowerCase(),
  39842. plugin[event][filter]
  39843. );
  39844. }
  39845. }
  39846. } else if (typeof plugin[event] === 'function') {
  39847. add(plugin, event, plugin[event]);
  39848. }
  39849. }
  39850. }
  39851. }
  39852. }
  39853. this.hasListener = Object.keys(this.listeners).length > 0;
  39854. }
  39855. visitTick(stack) {
  39856. let visit = stack[stack.length - 1];
  39857. let { node, visitors } = visit;
  39858. if (node.type !== 'root' && node.type !== 'document' && !node.parent) {
  39859. stack.pop();
  39860. return
  39861. }
  39862. if (visitors.length > 0 && visit.visitorIndex < visitors.length) {
  39863. let [plugin, visitor] = visitors[visit.visitorIndex];
  39864. visit.visitorIndex += 1;
  39865. if (visit.visitorIndex === visitors.length) {
  39866. visit.visitors = [];
  39867. visit.visitorIndex = 0;
  39868. }
  39869. this.result.lastPlugin = plugin;
  39870. try {
  39871. return visitor(node.toProxy(), this.helpers)
  39872. } catch (e) {
  39873. throw this.handleError(e, node)
  39874. }
  39875. }
  39876. if (visit.iterator !== 0) {
  39877. let iterator = visit.iterator;
  39878. let child;
  39879. while ((child = node.nodes[node.indexes[iterator]])) {
  39880. node.indexes[iterator] += 1;
  39881. if (!child[isClean]) {
  39882. child[isClean] = true;
  39883. stack.push(toStack(child));
  39884. return
  39885. }
  39886. }
  39887. visit.iterator = 0;
  39888. delete node.indexes[iterator];
  39889. }
  39890. let events = visit.events;
  39891. while (visit.eventIndex < events.length) {
  39892. let event = events[visit.eventIndex];
  39893. visit.eventIndex += 1;
  39894. if (event === CHILDREN) {
  39895. if (node.nodes && node.nodes.length) {
  39896. node[isClean] = true;
  39897. visit.iterator = node.getIterator();
  39898. }
  39899. return
  39900. } else if (this.listeners[event]) {
  39901. visit.visitors = this.listeners[event];
  39902. return
  39903. }
  39904. }
  39905. stack.pop();
  39906. }
  39907. };
  39908. LazyResult$2.registerPostcss = dependant => {
  39909. postcss$2 = dependant;
  39910. };
  39911. var lazyResult = LazyResult$2;
  39912. LazyResult$2.default = LazyResult$2;
  39913. Root$3.registerLazyResult(LazyResult$2);
  39914. Document$2.registerLazyResult(LazyResult$2);
  39915. let MapGenerator = mapGenerator;
  39916. let stringify$1 = stringify_1;
  39917. let warnOnce = warnOnce$2;
  39918. let parse$1 = parse_1;
  39919. const Result$1 = result;
  39920. let NoWorkResult$1 = class NoWorkResult {
  39921. constructor(processor, css, opts) {
  39922. css = css.toString();
  39923. this.stringified = false;
  39924. this._processor = processor;
  39925. this._css = css;
  39926. this._opts = opts;
  39927. this._map = undefined;
  39928. let root;
  39929. let str = stringify$1;
  39930. this.result = new Result$1(this._processor, root, this._opts);
  39931. this.result.css = css;
  39932. let self = this;
  39933. Object.defineProperty(this.result, 'root', {
  39934. get() {
  39935. return self.root
  39936. }
  39937. });
  39938. let map = new MapGenerator(str, root, this._opts, css);
  39939. if (map.isMap()) {
  39940. let [generatedCSS, generatedMap] = map.generate();
  39941. if (generatedCSS) {
  39942. this.result.css = generatedCSS;
  39943. }
  39944. if (generatedMap) {
  39945. this.result.map = generatedMap;
  39946. }
  39947. }
  39948. }
  39949. get [Symbol.toStringTag]() {
  39950. return 'NoWorkResult'
  39951. }
  39952. get processor() {
  39953. return this.result.processor
  39954. }
  39955. get opts() {
  39956. return this.result.opts
  39957. }
  39958. get css() {
  39959. return this.result.css
  39960. }
  39961. get content() {
  39962. return this.result.css
  39963. }
  39964. get map() {
  39965. return this.result.map
  39966. }
  39967. get root() {
  39968. if (this._root) {
  39969. return this._root
  39970. }
  39971. let root;
  39972. let parser = parse$1;
  39973. try {
  39974. root = parser(this._css, this._opts);
  39975. } catch (error) {
  39976. this.error = error;
  39977. }
  39978. this._root = root;
  39979. return root
  39980. }
  39981. get messages() {
  39982. return []
  39983. }
  39984. warnings() {
  39985. return []
  39986. }
  39987. toString() {
  39988. return this._css
  39989. }
  39990. then(onFulfilled, onRejected) {
  39991. if (browser$1.env.NODE_ENV !== 'production') {
  39992. if (!('from' in this._opts)) {
  39993. warnOnce(
  39994. 'Without `from` option PostCSS could generate wrong source map ' +
  39995. 'and will not find Browserslist config. Set it to CSS file path ' +
  39996. 'or to `undefined` to prevent this warning.'
  39997. );
  39998. }
  39999. }
  40000. return this.async().then(onFulfilled, onRejected)
  40001. }
  40002. catch(onRejected) {
  40003. return this.async().catch(onRejected)
  40004. }
  40005. finally(onFinally) {
  40006. return this.async().then(onFinally, onFinally)
  40007. }
  40008. async() {
  40009. if (this.error) return Promise.reject(this.error)
  40010. return Promise.resolve(this.result)
  40011. }
  40012. sync() {
  40013. if (this.error) throw this.error
  40014. return this.result
  40015. }
  40016. };
  40017. var noWorkResult = NoWorkResult$1;
  40018. NoWorkResult$1.default = NoWorkResult$1;
  40019. let NoWorkResult = noWorkResult;
  40020. let LazyResult$1 = lazyResult;
  40021. let Document$1 = document;
  40022. let Root$2 = root$2;
  40023. let Processor$1 = class Processor {
  40024. constructor(plugins = []) {
  40025. this.version = '8.4.4';
  40026. this.plugins = this.normalize(plugins);
  40027. }
  40028. use(plugin) {
  40029. this.plugins = this.plugins.concat(this.normalize([plugin]));
  40030. return this
  40031. }
  40032. process(css, opts = {}) {
  40033. if (
  40034. this.plugins.length === 0 &&
  40035. typeof opts.parser === 'undefined' &&
  40036. typeof opts.stringifier === 'undefined' &&
  40037. typeof opts.syntax === 'undefined'
  40038. ) {
  40039. return new NoWorkResult(this, css, opts)
  40040. } else {
  40041. return new LazyResult$1(this, css, opts)
  40042. }
  40043. }
  40044. normalize(plugins) {
  40045. let normalized = [];
  40046. for (let i of plugins) {
  40047. if (i.postcss === true) {
  40048. i = i();
  40049. } else if (i.postcss) {
  40050. i = i.postcss;
  40051. }
  40052. if (typeof i === 'object' && Array.isArray(i.plugins)) {
  40053. normalized = normalized.concat(i.plugins);
  40054. } else if (typeof i === 'object' && i.postcssPlugin) {
  40055. normalized.push(i);
  40056. } else if (typeof i === 'function') {
  40057. normalized.push(i);
  40058. } else if (typeof i === 'object' && (i.parse || i.stringify)) {
  40059. if (browser$1.env.NODE_ENV !== 'production') {
  40060. throw new Error(
  40061. 'PostCSS syntaxes cannot be used as plugins. Instead, please use ' +
  40062. 'one of the syntax/parser/stringifier options as outlined ' +
  40063. 'in your PostCSS runner documentation.'
  40064. )
  40065. }
  40066. } else {
  40067. throw new Error(i + ' is not a PostCSS plugin')
  40068. }
  40069. }
  40070. return normalized
  40071. }
  40072. };
  40073. var processor$1 = Processor$1;
  40074. Processor$1.default = Processor$1;
  40075. Root$2.registerProcessor(Processor$1);
  40076. Document$1.registerProcessor(Processor$1);
  40077. let Declaration$1 = declaration;
  40078. let PreviousMap = previousMap;
  40079. let Comment$1 = comment$3;
  40080. let AtRule$1 = atRule;
  40081. let Input$1 = input;
  40082. let Root$1 = root$2;
  40083. let Rule$1 = rule;
  40084. function fromJSON$1(json, inputs) {
  40085. if (Array.isArray(json)) return json.map(n => fromJSON$1(n))
  40086. let { inputs: ownInputs, ...defaults } = json;
  40087. if (ownInputs) {
  40088. inputs = [];
  40089. for (let input of ownInputs) {
  40090. let inputHydrated = { ...input, __proto__: Input$1.prototype };
  40091. if (inputHydrated.map) {
  40092. inputHydrated.map = {
  40093. ...inputHydrated.map,
  40094. __proto__: PreviousMap.prototype
  40095. };
  40096. }
  40097. inputs.push(inputHydrated);
  40098. }
  40099. }
  40100. if (defaults.nodes) {
  40101. defaults.nodes = json.nodes.map(n => fromJSON$1(n, inputs));
  40102. }
  40103. if (defaults.source) {
  40104. let { inputId, ...source } = defaults.source;
  40105. defaults.source = source;
  40106. if (inputId != null) {
  40107. defaults.source.input = inputs[inputId];
  40108. }
  40109. }
  40110. if (defaults.type === 'root') {
  40111. return new Root$1(defaults)
  40112. } else if (defaults.type === 'decl') {
  40113. return new Declaration$1(defaults)
  40114. } else if (defaults.type === 'rule') {
  40115. return new Rule$1(defaults)
  40116. } else if (defaults.type === 'comment') {
  40117. return new Comment$1(defaults)
  40118. } else if (defaults.type === 'atrule') {
  40119. return new AtRule$1(defaults)
  40120. } else {
  40121. throw new Error('Unknown node type: ' + json.type)
  40122. }
  40123. }
  40124. var fromJSON_1 = fromJSON$1;
  40125. fromJSON$1.default = fromJSON$1;
  40126. let CssSyntaxError = cssSyntaxError;
  40127. let Declaration = declaration;
  40128. let LazyResult = lazyResult;
  40129. let Container = container$1;
  40130. let Processor = processor$1;
  40131. let stringify = stringify_1;
  40132. let fromJSON = fromJSON_1;
  40133. let Document = document;
  40134. let Warning = warning;
  40135. let Comment = comment$3;
  40136. let AtRule = atRule;
  40137. let Result = result;
  40138. let Input = input;
  40139. let parse = parse_1;
  40140. let list = list_1;
  40141. let Rule = rule;
  40142. let Root = root$2;
  40143. let Node = node$2;
  40144. function postcss(...plugins) {
  40145. if (plugins.length === 1 && Array.isArray(plugins[0])) {
  40146. plugins = plugins[0];
  40147. }
  40148. return new Processor(plugins)
  40149. }
  40150. postcss.plugin = function plugin(name, initializer) {
  40151. // eslint-disable-next-line no-console
  40152. if (console && console.warn) {
  40153. // eslint-disable-next-line no-console
  40154. console.warn(
  40155. name +
  40156. ': postcss.plugin was deprecated. Migration guide:\n' +
  40157. 'https://evilmartians.com/chronicles/postcss-8-plugin-migration'
  40158. );
  40159. if (browser$1.env.LANG && browser$1.env.LANG.startsWith('cn')) {
  40160. /* c8 ignore next 7 */
  40161. // eslint-disable-next-line no-console
  40162. console.warn(
  40163. name +
  40164. ': 里面 postcss.plugin 被弃用. 迁移指南:\n' +
  40165. 'https://www.w3ctech.com/topic/2226'
  40166. );
  40167. }
  40168. }
  40169. function creator(...args) {
  40170. let transformer = initializer(...args);
  40171. transformer.postcssPlugin = name;
  40172. transformer.postcssVersion = new Processor().version;
  40173. return transformer
  40174. }
  40175. let cache;
  40176. Object.defineProperty(creator, 'postcss', {
  40177. get() {
  40178. if (!cache) cache = creator();
  40179. return cache
  40180. }
  40181. });
  40182. creator.process = function (css, processOpts, pluginOpts) {
  40183. return postcss([creator(pluginOpts)]).process(css, processOpts)
  40184. };
  40185. return creator
  40186. };
  40187. postcss.stringify = stringify;
  40188. postcss.parse = parse;
  40189. postcss.fromJSON = fromJSON;
  40190. postcss.list = list;
  40191. postcss.comment = defaults => new Comment(defaults);
  40192. postcss.atRule = defaults => new AtRule(defaults);
  40193. postcss.decl = defaults => new Declaration(defaults);
  40194. postcss.rule = defaults => new Rule(defaults);
  40195. postcss.root = defaults => new Root(defaults);
  40196. postcss.document = defaults => new Document(defaults);
  40197. postcss.CssSyntaxError = CssSyntaxError;
  40198. postcss.Declaration = Declaration;
  40199. postcss.Container = Container;
  40200. postcss.Processor = Processor;
  40201. postcss.Document = Document;
  40202. postcss.Comment = Comment;
  40203. postcss.Warning = Warning;
  40204. postcss.AtRule = AtRule;
  40205. postcss.Result = Result;
  40206. postcss.Input = Input;
  40207. postcss.Rule = Rule;
  40208. postcss.Root = Root;
  40209. postcss.Node = Node;
  40210. LazyResult.registerPostcss(postcss);
  40211. var postcss_1 = postcss;
  40212. postcss.default = postcss;
  40213. var postcss$1 = postcss_1;
  40214. postcss$1.stringify;
  40215. postcss$1.fromJSON;
  40216. postcss$1.plugin;
  40217. postcss$1.parse;
  40218. postcss$1.list;
  40219. postcss$1.document;
  40220. postcss$1.comment;
  40221. postcss$1.atRule;
  40222. postcss$1.rule;
  40223. postcss$1.decl;
  40224. postcss$1.root;
  40225. postcss$1.CssSyntaxError;
  40226. postcss$1.Declaration;
  40227. postcss$1.Container;
  40228. postcss$1.Processor;
  40229. postcss$1.Document;
  40230. postcss$1.Comment;
  40231. postcss$1.Warning;
  40232. postcss$1.AtRule;
  40233. postcss$1.Result;
  40234. postcss$1.Input;
  40235. postcss$1.Rule;
  40236. postcss$1.Root;
  40237. postcss$1.Node;
  40238. const trimPlugin = () => {
  40239. return {
  40240. postcssPlugin: 'vue-sfc-trim',
  40241. Once(root) {
  40242. root.walk(({ type, raws }) => {
  40243. if (type === 'rule' || type === 'atrule') {
  40244. if (raws.before)
  40245. raws.before = '\n';
  40246. if ('after' in raws && raws.after)
  40247. raws.after = '\n';
  40248. }
  40249. });
  40250. }
  40251. };
  40252. };
  40253. trimPlugin.postcss = true;
  40254. var trimPlugin$1 = trimPlugin;
  40255. var dist = {exports: {}};
  40256. var processor = {exports: {}};
  40257. var parser = {exports: {}};
  40258. var root$1 = {exports: {}};
  40259. var container = {exports: {}};
  40260. var node$1 = {exports: {}};
  40261. var util = {};
  40262. var unesc = {exports: {}};
  40263. (function (module, exports) {
  40264. exports.__esModule = true;
  40265. exports["default"] = unesc;
  40266. // Many thanks for this post which made this migration much easier.
  40267. // https://mathiasbynens.be/notes/css-escapes
  40268. /**
  40269. *
  40270. * @param {string} str
  40271. * @returns {[string, number]|undefined}
  40272. */
  40273. function gobbleHex(str) {
  40274. var lower = str.toLowerCase();
  40275. var hex = '';
  40276. var spaceTerminated = false;
  40277. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  40278. var code = lower.charCodeAt(i); // check to see if we are dealing with a valid hex char [a-f|0-9]
  40279. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57; // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  40280. spaceTerminated = code === 32;
  40281. if (!valid) {
  40282. break;
  40283. }
  40284. hex += lower[i];
  40285. }
  40286. if (hex.length === 0) {
  40287. return undefined;
  40288. }
  40289. var codePoint = parseInt(hex, 16);
  40290. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF; // Add special case for
  40291. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  40292. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  40293. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  40294. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  40295. }
  40296. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  40297. }
  40298. var CONTAINS_ESCAPE = /\\/;
  40299. function unesc(str) {
  40300. var needToProcess = CONTAINS_ESCAPE.test(str);
  40301. if (!needToProcess) {
  40302. return str;
  40303. }
  40304. var ret = "";
  40305. for (var i = 0; i < str.length; i++) {
  40306. if (str[i] === "\\") {
  40307. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  40308. if (gobbled !== undefined) {
  40309. ret += gobbled[0];
  40310. i += gobbled[1];
  40311. continue;
  40312. } // Retain a pair of \\ if double escaped `\\\\`
  40313. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  40314. if (str[i + 1] === "\\") {
  40315. ret += "\\";
  40316. i++;
  40317. continue;
  40318. } // if \\ is at the end of the string retain it
  40319. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  40320. if (str.length === i + 1) {
  40321. ret += str[i];
  40322. }
  40323. continue;
  40324. }
  40325. ret += str[i];
  40326. }
  40327. return ret;
  40328. }
  40329. module.exports = exports.default;
  40330. } (unesc, unesc.exports));
  40331. var getProp = {exports: {}};
  40332. (function (module, exports) {
  40333. exports.__esModule = true;
  40334. exports["default"] = getProp;
  40335. function getProp(obj) {
  40336. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  40337. props[_key - 1] = arguments[_key];
  40338. }
  40339. while (props.length > 0) {
  40340. var prop = props.shift();
  40341. if (!obj[prop]) {
  40342. return undefined;
  40343. }
  40344. obj = obj[prop];
  40345. }
  40346. return obj;
  40347. }
  40348. module.exports = exports.default;
  40349. } (getProp, getProp.exports));
  40350. var ensureObject = {exports: {}};
  40351. (function (module, exports) {
  40352. exports.__esModule = true;
  40353. exports["default"] = ensureObject;
  40354. function ensureObject(obj) {
  40355. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  40356. props[_key - 1] = arguments[_key];
  40357. }
  40358. while (props.length > 0) {
  40359. var prop = props.shift();
  40360. if (!obj[prop]) {
  40361. obj[prop] = {};
  40362. }
  40363. obj = obj[prop];
  40364. }
  40365. }
  40366. module.exports = exports.default;
  40367. } (ensureObject, ensureObject.exports));
  40368. var stripComments = {exports: {}};
  40369. (function (module, exports) {
  40370. exports.__esModule = true;
  40371. exports["default"] = stripComments;
  40372. function stripComments(str) {
  40373. var s = "";
  40374. var commentStart = str.indexOf("/*");
  40375. var lastEnd = 0;
  40376. while (commentStart >= 0) {
  40377. s = s + str.slice(lastEnd, commentStart);
  40378. var commentEnd = str.indexOf("*/", commentStart + 2);
  40379. if (commentEnd < 0) {
  40380. return s;
  40381. }
  40382. lastEnd = commentEnd + 2;
  40383. commentStart = str.indexOf("/*", lastEnd);
  40384. }
  40385. s = s + str.slice(lastEnd);
  40386. return s;
  40387. }
  40388. module.exports = exports.default;
  40389. } (stripComments, stripComments.exports));
  40390. util.__esModule = true;
  40391. util.stripComments = util.ensureObject = util.getProp = util.unesc = void 0;
  40392. var _unesc = _interopRequireDefault$1(unesc.exports);
  40393. util.unesc = _unesc["default"];
  40394. var _getProp = _interopRequireDefault$1(getProp.exports);
  40395. util.getProp = _getProp["default"];
  40396. var _ensureObject = _interopRequireDefault$1(ensureObject.exports);
  40397. util.ensureObject = _ensureObject["default"];
  40398. var _stripComments = _interopRequireDefault$1(stripComments.exports);
  40399. util.stripComments = _stripComments["default"];
  40400. function _interopRequireDefault$1(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40401. (function (module, exports) {
  40402. exports.__esModule = true;
  40403. exports["default"] = void 0;
  40404. var _util = util;
  40405. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  40406. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  40407. var cloneNode = function cloneNode(obj, parent) {
  40408. if (typeof obj !== 'object' || obj === null) {
  40409. return obj;
  40410. }
  40411. var cloned = new obj.constructor();
  40412. for (var i in obj) {
  40413. if (!obj.hasOwnProperty(i)) {
  40414. continue;
  40415. }
  40416. var value = obj[i];
  40417. var type = typeof value;
  40418. if (i === 'parent' && type === 'object') {
  40419. if (parent) {
  40420. cloned[i] = parent;
  40421. }
  40422. } else if (value instanceof Array) {
  40423. cloned[i] = value.map(function (j) {
  40424. return cloneNode(j, cloned);
  40425. });
  40426. } else {
  40427. cloned[i] = cloneNode(value, cloned);
  40428. }
  40429. }
  40430. return cloned;
  40431. };
  40432. var Node = /*#__PURE__*/function () {
  40433. function Node(opts) {
  40434. if (opts === void 0) {
  40435. opts = {};
  40436. }
  40437. Object.assign(this, opts);
  40438. this.spaces = this.spaces || {};
  40439. this.spaces.before = this.spaces.before || '';
  40440. this.spaces.after = this.spaces.after || '';
  40441. }
  40442. var _proto = Node.prototype;
  40443. _proto.remove = function remove() {
  40444. if (this.parent) {
  40445. this.parent.removeChild(this);
  40446. }
  40447. this.parent = undefined;
  40448. return this;
  40449. };
  40450. _proto.replaceWith = function replaceWith() {
  40451. if (this.parent) {
  40452. for (var index in arguments) {
  40453. this.parent.insertBefore(this, arguments[index]);
  40454. }
  40455. this.remove();
  40456. }
  40457. return this;
  40458. };
  40459. _proto.next = function next() {
  40460. return this.parent.at(this.parent.index(this) + 1);
  40461. };
  40462. _proto.prev = function prev() {
  40463. return this.parent.at(this.parent.index(this) - 1);
  40464. };
  40465. _proto.clone = function clone(overrides) {
  40466. if (overrides === void 0) {
  40467. overrides = {};
  40468. }
  40469. var cloned = cloneNode(this);
  40470. for (var name in overrides) {
  40471. cloned[name] = overrides[name];
  40472. }
  40473. return cloned;
  40474. }
  40475. /**
  40476. * Some non-standard syntax doesn't follow normal escaping rules for css.
  40477. * This allows non standard syntax to be appended to an existing property
  40478. * by specifying the escaped value. By specifying the escaped value,
  40479. * illegal characters are allowed to be directly inserted into css output.
  40480. * @param {string} name the property to set
  40481. * @param {any} value the unescaped value of the property
  40482. * @param {string} valueEscaped optional. the escaped value of the property.
  40483. */
  40484. ;
  40485. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  40486. if (!this.raws) {
  40487. this.raws = {};
  40488. }
  40489. var originalValue = this[name];
  40490. var originalEscaped = this.raws[name];
  40491. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  40492. if (originalEscaped || valueEscaped !== value) {
  40493. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  40494. } else {
  40495. delete this.raws[name]; // delete any escaped value that was created by the setter.
  40496. }
  40497. }
  40498. /**
  40499. * Some non-standard syntax doesn't follow normal escaping rules for css.
  40500. * This allows the escaped value to be specified directly, allowing illegal
  40501. * characters to be directly inserted into css output.
  40502. * @param {string} name the property to set
  40503. * @param {any} value the unescaped value of the property
  40504. * @param {string} valueEscaped the escaped value of the property.
  40505. */
  40506. ;
  40507. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  40508. if (!this.raws) {
  40509. this.raws = {};
  40510. }
  40511. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  40512. this.raws[name] = valueEscaped;
  40513. }
  40514. /**
  40515. * When you want a value to passed through to CSS directly. This method
  40516. * deletes the corresponding raw value causing the stringifier to fallback
  40517. * to the unescaped value.
  40518. * @param {string} name the property to set.
  40519. * @param {any} value The value that is both escaped and unescaped.
  40520. */
  40521. ;
  40522. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  40523. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  40524. if (this.raws) {
  40525. delete this.raws[name];
  40526. }
  40527. }
  40528. /**
  40529. *
  40530. * @param {number} line The number (starting with 1)
  40531. * @param {number} column The column number (starting with 1)
  40532. */
  40533. ;
  40534. _proto.isAtPosition = function isAtPosition(line, column) {
  40535. if (this.source && this.source.start && this.source.end) {
  40536. if (this.source.start.line > line) {
  40537. return false;
  40538. }
  40539. if (this.source.end.line < line) {
  40540. return false;
  40541. }
  40542. if (this.source.start.line === line && this.source.start.column > column) {
  40543. return false;
  40544. }
  40545. if (this.source.end.line === line && this.source.end.column < column) {
  40546. return false;
  40547. }
  40548. return true;
  40549. }
  40550. return undefined;
  40551. };
  40552. _proto.stringifyProperty = function stringifyProperty(name) {
  40553. return this.raws && this.raws[name] || this[name];
  40554. };
  40555. _proto.valueToString = function valueToString() {
  40556. return String(this.stringifyProperty("value"));
  40557. };
  40558. _proto.toString = function toString() {
  40559. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  40560. };
  40561. _createClass(Node, [{
  40562. key: "rawSpaceBefore",
  40563. get: function get() {
  40564. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  40565. if (rawSpace === undefined) {
  40566. rawSpace = this.spaces && this.spaces.before;
  40567. }
  40568. return rawSpace || "";
  40569. },
  40570. set: function set(raw) {
  40571. (0, _util.ensureObject)(this, "raws", "spaces");
  40572. this.raws.spaces.before = raw;
  40573. }
  40574. }, {
  40575. key: "rawSpaceAfter",
  40576. get: function get() {
  40577. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  40578. if (rawSpace === undefined) {
  40579. rawSpace = this.spaces.after;
  40580. }
  40581. return rawSpace || "";
  40582. },
  40583. set: function set(raw) {
  40584. (0, _util.ensureObject)(this, "raws", "spaces");
  40585. this.raws.spaces.after = raw;
  40586. }
  40587. }]);
  40588. return Node;
  40589. }();
  40590. exports["default"] = Node;
  40591. module.exports = exports.default;
  40592. } (node$1, node$1.exports));
  40593. var types = {};
  40594. types.__esModule = true;
  40595. types.UNIVERSAL = types.ATTRIBUTE = types.CLASS = types.COMBINATOR = types.COMMENT = types.ID = types.NESTING = types.PSEUDO = types.ROOT = types.SELECTOR = types.STRING = types.TAG = void 0;
  40596. var TAG = 'tag';
  40597. types.TAG = TAG;
  40598. var STRING = 'string';
  40599. types.STRING = STRING;
  40600. var SELECTOR = 'selector';
  40601. types.SELECTOR = SELECTOR;
  40602. var ROOT = 'root';
  40603. types.ROOT = ROOT;
  40604. var PSEUDO = 'pseudo';
  40605. types.PSEUDO = PSEUDO;
  40606. var NESTING = 'nesting';
  40607. types.NESTING = NESTING;
  40608. var ID = 'id';
  40609. types.ID = ID;
  40610. var COMMENT = 'comment';
  40611. types.COMMENT = COMMENT;
  40612. var COMBINATOR = 'combinator';
  40613. types.COMBINATOR = COMBINATOR;
  40614. var CLASS = 'class';
  40615. types.CLASS = CLASS;
  40616. var ATTRIBUTE = 'attribute';
  40617. types.ATTRIBUTE = ATTRIBUTE;
  40618. var UNIVERSAL = 'universal';
  40619. types.UNIVERSAL = UNIVERSAL;
  40620. (function (module, exports) {
  40621. exports.__esModule = true;
  40622. exports["default"] = void 0;
  40623. var _node = _interopRequireDefault(node$1.exports);
  40624. var types$1 = _interopRequireWildcard(types);
  40625. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  40626. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  40627. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40628. function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } it = o[Symbol.iterator](); return it.next.bind(it); }
  40629. function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
  40630. function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
  40631. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  40632. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  40633. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  40634. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  40635. var Container = /*#__PURE__*/function (_Node) {
  40636. _inheritsLoose(Container, _Node);
  40637. function Container(opts) {
  40638. var _this;
  40639. _this = _Node.call(this, opts) || this;
  40640. if (!_this.nodes) {
  40641. _this.nodes = [];
  40642. }
  40643. return _this;
  40644. }
  40645. var _proto = Container.prototype;
  40646. _proto.append = function append(selector) {
  40647. selector.parent = this;
  40648. this.nodes.push(selector);
  40649. return this;
  40650. };
  40651. _proto.prepend = function prepend(selector) {
  40652. selector.parent = this;
  40653. this.nodes.unshift(selector);
  40654. return this;
  40655. };
  40656. _proto.at = function at(index) {
  40657. return this.nodes[index];
  40658. };
  40659. _proto.index = function index(child) {
  40660. if (typeof child === 'number') {
  40661. return child;
  40662. }
  40663. return this.nodes.indexOf(child);
  40664. };
  40665. _proto.removeChild = function removeChild(child) {
  40666. child = this.index(child);
  40667. this.at(child).parent = undefined;
  40668. this.nodes.splice(child, 1);
  40669. var index;
  40670. for (var id in this.indexes) {
  40671. index = this.indexes[id];
  40672. if (index >= child) {
  40673. this.indexes[id] = index - 1;
  40674. }
  40675. }
  40676. return this;
  40677. };
  40678. _proto.removeAll = function removeAll() {
  40679. for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
  40680. var node = _step.value;
  40681. node.parent = undefined;
  40682. }
  40683. this.nodes = [];
  40684. return this;
  40685. };
  40686. _proto.empty = function empty() {
  40687. return this.removeAll();
  40688. };
  40689. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  40690. newNode.parent = this;
  40691. var oldIndex = this.index(oldNode);
  40692. this.nodes.splice(oldIndex + 1, 0, newNode);
  40693. newNode.parent = this;
  40694. var index;
  40695. for (var id in this.indexes) {
  40696. index = this.indexes[id];
  40697. if (oldIndex <= index) {
  40698. this.indexes[id] = index + 1;
  40699. }
  40700. }
  40701. return this;
  40702. };
  40703. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  40704. newNode.parent = this;
  40705. var oldIndex = this.index(oldNode);
  40706. this.nodes.splice(oldIndex, 0, newNode);
  40707. newNode.parent = this;
  40708. var index;
  40709. for (var id in this.indexes) {
  40710. index = this.indexes[id];
  40711. if (index <= oldIndex) {
  40712. this.indexes[id] = index + 1;
  40713. }
  40714. }
  40715. return this;
  40716. };
  40717. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  40718. var found = undefined;
  40719. this.each(function (node) {
  40720. if (node.atPosition) {
  40721. var foundChild = node.atPosition(line, col);
  40722. if (foundChild) {
  40723. found = foundChild;
  40724. return false;
  40725. }
  40726. } else if (node.isAtPosition(line, col)) {
  40727. found = node;
  40728. return false;
  40729. }
  40730. });
  40731. return found;
  40732. }
  40733. /**
  40734. * Return the most specific node at the line and column number given.
  40735. * The source location is based on the original parsed location, locations aren't
  40736. * updated as selector nodes are mutated.
  40737. *
  40738. * Note that this location is relative to the location of the first character
  40739. * of the selector, and not the location of the selector in the overall document
  40740. * when used in conjunction with postcss.
  40741. *
  40742. * If not found, returns undefined.
  40743. * @param {number} line The line number of the node to find. (1-based index)
  40744. * @param {number} col The column number of the node to find. (1-based index)
  40745. */
  40746. ;
  40747. _proto.atPosition = function atPosition(line, col) {
  40748. if (this.isAtPosition(line, col)) {
  40749. return this._findChildAtPosition(line, col) || this;
  40750. } else {
  40751. return undefined;
  40752. }
  40753. };
  40754. _proto._inferEndPosition = function _inferEndPosition() {
  40755. if (this.last && this.last.source && this.last.source.end) {
  40756. this.source = this.source || {};
  40757. this.source.end = this.source.end || {};
  40758. Object.assign(this.source.end, this.last.source.end);
  40759. }
  40760. };
  40761. _proto.each = function each(callback) {
  40762. if (!this.lastEach) {
  40763. this.lastEach = 0;
  40764. }
  40765. if (!this.indexes) {
  40766. this.indexes = {};
  40767. }
  40768. this.lastEach++;
  40769. var id = this.lastEach;
  40770. this.indexes[id] = 0;
  40771. if (!this.length) {
  40772. return undefined;
  40773. }
  40774. var index, result;
  40775. while (this.indexes[id] < this.length) {
  40776. index = this.indexes[id];
  40777. result = callback(this.at(index), index);
  40778. if (result === false) {
  40779. break;
  40780. }
  40781. this.indexes[id] += 1;
  40782. }
  40783. delete this.indexes[id];
  40784. if (result === false) {
  40785. return false;
  40786. }
  40787. };
  40788. _proto.walk = function walk(callback) {
  40789. return this.each(function (node, i) {
  40790. var result = callback(node, i);
  40791. if (result !== false && node.length) {
  40792. result = node.walk(callback);
  40793. }
  40794. if (result === false) {
  40795. return false;
  40796. }
  40797. });
  40798. };
  40799. _proto.walkAttributes = function walkAttributes(callback) {
  40800. var _this2 = this;
  40801. return this.walk(function (selector) {
  40802. if (selector.type === types$1.ATTRIBUTE) {
  40803. return callback.call(_this2, selector);
  40804. }
  40805. });
  40806. };
  40807. _proto.walkClasses = function walkClasses(callback) {
  40808. var _this3 = this;
  40809. return this.walk(function (selector) {
  40810. if (selector.type === types$1.CLASS) {
  40811. return callback.call(_this3, selector);
  40812. }
  40813. });
  40814. };
  40815. _proto.walkCombinators = function walkCombinators(callback) {
  40816. var _this4 = this;
  40817. return this.walk(function (selector) {
  40818. if (selector.type === types$1.COMBINATOR) {
  40819. return callback.call(_this4, selector);
  40820. }
  40821. });
  40822. };
  40823. _proto.walkComments = function walkComments(callback) {
  40824. var _this5 = this;
  40825. return this.walk(function (selector) {
  40826. if (selector.type === types$1.COMMENT) {
  40827. return callback.call(_this5, selector);
  40828. }
  40829. });
  40830. };
  40831. _proto.walkIds = function walkIds(callback) {
  40832. var _this6 = this;
  40833. return this.walk(function (selector) {
  40834. if (selector.type === types$1.ID) {
  40835. return callback.call(_this6, selector);
  40836. }
  40837. });
  40838. };
  40839. _proto.walkNesting = function walkNesting(callback) {
  40840. var _this7 = this;
  40841. return this.walk(function (selector) {
  40842. if (selector.type === types$1.NESTING) {
  40843. return callback.call(_this7, selector);
  40844. }
  40845. });
  40846. };
  40847. _proto.walkPseudos = function walkPseudos(callback) {
  40848. var _this8 = this;
  40849. return this.walk(function (selector) {
  40850. if (selector.type === types$1.PSEUDO) {
  40851. return callback.call(_this8, selector);
  40852. }
  40853. });
  40854. };
  40855. _proto.walkTags = function walkTags(callback) {
  40856. var _this9 = this;
  40857. return this.walk(function (selector) {
  40858. if (selector.type === types$1.TAG) {
  40859. return callback.call(_this9, selector);
  40860. }
  40861. });
  40862. };
  40863. _proto.walkUniversals = function walkUniversals(callback) {
  40864. var _this10 = this;
  40865. return this.walk(function (selector) {
  40866. if (selector.type === types$1.UNIVERSAL) {
  40867. return callback.call(_this10, selector);
  40868. }
  40869. });
  40870. };
  40871. _proto.split = function split(callback) {
  40872. var _this11 = this;
  40873. var current = [];
  40874. return this.reduce(function (memo, node, index) {
  40875. var split = callback.call(_this11, node);
  40876. current.push(node);
  40877. if (split) {
  40878. memo.push(current);
  40879. current = [];
  40880. } else if (index === _this11.length - 1) {
  40881. memo.push(current);
  40882. }
  40883. return memo;
  40884. }, []);
  40885. };
  40886. _proto.map = function map(callback) {
  40887. return this.nodes.map(callback);
  40888. };
  40889. _proto.reduce = function reduce(callback, memo) {
  40890. return this.nodes.reduce(callback, memo);
  40891. };
  40892. _proto.every = function every(callback) {
  40893. return this.nodes.every(callback);
  40894. };
  40895. _proto.some = function some(callback) {
  40896. return this.nodes.some(callback);
  40897. };
  40898. _proto.filter = function filter(callback) {
  40899. return this.nodes.filter(callback);
  40900. };
  40901. _proto.sort = function sort(callback) {
  40902. return this.nodes.sort(callback);
  40903. };
  40904. _proto.toString = function toString() {
  40905. return this.map(String).join('');
  40906. };
  40907. _createClass(Container, [{
  40908. key: "first",
  40909. get: function get() {
  40910. return this.at(0);
  40911. }
  40912. }, {
  40913. key: "last",
  40914. get: function get() {
  40915. return this.at(this.length - 1);
  40916. }
  40917. }, {
  40918. key: "length",
  40919. get: function get() {
  40920. return this.nodes.length;
  40921. }
  40922. }]);
  40923. return Container;
  40924. }(_node["default"]);
  40925. exports["default"] = Container;
  40926. module.exports = exports.default;
  40927. } (container, container.exports));
  40928. (function (module, exports) {
  40929. exports.__esModule = true;
  40930. exports["default"] = void 0;
  40931. var _container = _interopRequireDefault(container.exports);
  40932. var _types = types;
  40933. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40934. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  40935. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  40936. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  40937. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  40938. var Root = /*#__PURE__*/function (_Container) {
  40939. _inheritsLoose(Root, _Container);
  40940. function Root(opts) {
  40941. var _this;
  40942. _this = _Container.call(this, opts) || this;
  40943. _this.type = _types.ROOT;
  40944. return _this;
  40945. }
  40946. var _proto = Root.prototype;
  40947. _proto.toString = function toString() {
  40948. var str = this.reduce(function (memo, selector) {
  40949. memo.push(String(selector));
  40950. return memo;
  40951. }, []).join(',');
  40952. return this.trailingComma ? str + ',' : str;
  40953. };
  40954. _proto.error = function error(message, options) {
  40955. if (this._error) {
  40956. return this._error(message, options);
  40957. } else {
  40958. return new Error(message);
  40959. }
  40960. };
  40961. _createClass(Root, [{
  40962. key: "errorGenerator",
  40963. set: function set(handler) {
  40964. this._error = handler;
  40965. }
  40966. }]);
  40967. return Root;
  40968. }(_container["default"]);
  40969. exports["default"] = Root;
  40970. module.exports = exports.default;
  40971. } (root$1, root$1.exports));
  40972. var selector$1 = {exports: {}};
  40973. (function (module, exports) {
  40974. exports.__esModule = true;
  40975. exports["default"] = void 0;
  40976. var _container = _interopRequireDefault(container.exports);
  40977. var _types = types;
  40978. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40979. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  40980. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  40981. var Selector = /*#__PURE__*/function (_Container) {
  40982. _inheritsLoose(Selector, _Container);
  40983. function Selector(opts) {
  40984. var _this;
  40985. _this = _Container.call(this, opts) || this;
  40986. _this.type = _types.SELECTOR;
  40987. return _this;
  40988. }
  40989. return Selector;
  40990. }(_container["default"]);
  40991. exports["default"] = Selector;
  40992. module.exports = exports.default;
  40993. } (selector$1, selector$1.exports));
  40994. var className$1 = {exports: {}};
  40995. /*! https://mths.be/cssesc v3.0.0 by @mathias */
  40996. var object = {};
  40997. var hasOwnProperty = object.hasOwnProperty;
  40998. var merge$2 = function merge(options, defaults) {
  40999. if (!options) {
  41000. return defaults;
  41001. }
  41002. var result = {};
  41003. for (var key in defaults) {
  41004. // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
  41005. // only recognized option names are used.
  41006. result[key] = hasOwnProperty.call(options, key) ? options[key] : defaults[key];
  41007. }
  41008. return result;
  41009. };
  41010. var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
  41011. var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
  41012. var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
  41013. // https://mathiasbynens.be/notes/css-escapes#css
  41014. var cssesc = function cssesc(string, options) {
  41015. options = merge$2(options, cssesc.options);
  41016. if (options.quotes != 'single' && options.quotes != 'double') {
  41017. options.quotes = 'single';
  41018. }
  41019. var quote = options.quotes == 'double' ? '"' : '\'';
  41020. var isIdentifier = options.isIdentifier;
  41021. var firstChar = string.charAt(0);
  41022. var output = '';
  41023. var counter = 0;
  41024. var length = string.length;
  41025. while (counter < length) {
  41026. var character = string.charAt(counter++);
  41027. var codePoint = character.charCodeAt();
  41028. var value = void 0;
  41029. // If it’s not a printable ASCII character…
  41030. if (codePoint < 0x20 || codePoint > 0x7E) {
  41031. if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
  41032. // It’s a high surrogate, and there is a next character.
  41033. var extra = string.charCodeAt(counter++);
  41034. if ((extra & 0xFC00) == 0xDC00) {
  41035. // next character is low surrogate
  41036. codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
  41037. } else {
  41038. // It’s an unmatched surrogate; only append this code unit, in case
  41039. // the next code unit is the high surrogate of a surrogate pair.
  41040. counter--;
  41041. }
  41042. }
  41043. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  41044. } else {
  41045. if (options.escapeEverything) {
  41046. if (regexAnySingleEscape.test(character)) {
  41047. value = '\\' + character;
  41048. } else {
  41049. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  41050. }
  41051. } else if (/[\t\n\f\r\x0B]/.test(character)) {
  41052. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  41053. } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
  41054. value = '\\' + character;
  41055. } else {
  41056. value = character;
  41057. }
  41058. }
  41059. output += value;
  41060. }
  41061. if (isIdentifier) {
  41062. if (/^-[-\d]/.test(output)) {
  41063. output = '\\-' + output.slice(1);
  41064. } else if (/\d/.test(firstChar)) {
  41065. output = '\\3' + firstChar + ' ' + output.slice(1);
  41066. }
  41067. }
  41068. // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
  41069. // since they’re redundant. Note that this is only possible if the escape
  41070. // sequence isn’t preceded by an odd number of backslashes.
  41071. output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
  41072. if ($1 && $1.length % 2) {
  41073. // It’s not safe to remove the space, so don’t.
  41074. return $0;
  41075. }
  41076. // Strip the space.
  41077. return ($1 || '') + $2;
  41078. });
  41079. if (!isIdentifier && options.wrap) {
  41080. return quote + output + quote;
  41081. }
  41082. return output;
  41083. };
  41084. // Expose default options (so they can be overridden globally).
  41085. cssesc.options = {
  41086. 'escapeEverything': false,
  41087. 'isIdentifier': false,
  41088. 'quotes': 'single',
  41089. 'wrap': false
  41090. };
  41091. cssesc.version = '3.0.0';
  41092. var cssesc_1 = cssesc;
  41093. (function (module, exports) {
  41094. exports.__esModule = true;
  41095. exports["default"] = void 0;
  41096. var _cssesc = _interopRequireDefault(cssesc_1);
  41097. var _util = util;
  41098. var _node = _interopRequireDefault(node$1.exports);
  41099. var _types = types;
  41100. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41101. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  41102. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  41103. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41104. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41105. var ClassName = /*#__PURE__*/function (_Node) {
  41106. _inheritsLoose(ClassName, _Node);
  41107. function ClassName(opts) {
  41108. var _this;
  41109. _this = _Node.call(this, opts) || this;
  41110. _this.type = _types.CLASS;
  41111. _this._constructed = true;
  41112. return _this;
  41113. }
  41114. var _proto = ClassName.prototype;
  41115. _proto.valueToString = function valueToString() {
  41116. return '.' + _Node.prototype.valueToString.call(this);
  41117. };
  41118. _createClass(ClassName, [{
  41119. key: "value",
  41120. get: function get() {
  41121. return this._value;
  41122. },
  41123. set: function set(v) {
  41124. if (this._constructed) {
  41125. var escaped = (0, _cssesc["default"])(v, {
  41126. isIdentifier: true
  41127. });
  41128. if (escaped !== v) {
  41129. (0, _util.ensureObject)(this, "raws");
  41130. this.raws.value = escaped;
  41131. } else if (this.raws) {
  41132. delete this.raws.value;
  41133. }
  41134. }
  41135. this._value = v;
  41136. }
  41137. }]);
  41138. return ClassName;
  41139. }(_node["default"]);
  41140. exports["default"] = ClassName;
  41141. module.exports = exports.default;
  41142. } (className$1, className$1.exports));
  41143. var comment$2 = {exports: {}};
  41144. (function (module, exports) {
  41145. exports.__esModule = true;
  41146. exports["default"] = void 0;
  41147. var _node = _interopRequireDefault(node$1.exports);
  41148. var _types = types;
  41149. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41150. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41151. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41152. var Comment = /*#__PURE__*/function (_Node) {
  41153. _inheritsLoose(Comment, _Node);
  41154. function Comment(opts) {
  41155. var _this;
  41156. _this = _Node.call(this, opts) || this;
  41157. _this.type = _types.COMMENT;
  41158. return _this;
  41159. }
  41160. return Comment;
  41161. }(_node["default"]);
  41162. exports["default"] = Comment;
  41163. module.exports = exports.default;
  41164. } (comment$2, comment$2.exports));
  41165. var id$1 = {exports: {}};
  41166. (function (module, exports) {
  41167. exports.__esModule = true;
  41168. exports["default"] = void 0;
  41169. var _node = _interopRequireDefault(node$1.exports);
  41170. var _types = types;
  41171. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41172. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41173. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41174. var ID = /*#__PURE__*/function (_Node) {
  41175. _inheritsLoose(ID, _Node);
  41176. function ID(opts) {
  41177. var _this;
  41178. _this = _Node.call(this, opts) || this;
  41179. _this.type = _types.ID;
  41180. return _this;
  41181. }
  41182. var _proto = ID.prototype;
  41183. _proto.valueToString = function valueToString() {
  41184. return '#' + _Node.prototype.valueToString.call(this);
  41185. };
  41186. return ID;
  41187. }(_node["default"]);
  41188. exports["default"] = ID;
  41189. module.exports = exports.default;
  41190. } (id$1, id$1.exports));
  41191. var tag$1 = {exports: {}};
  41192. var namespace = {exports: {}};
  41193. (function (module, exports) {
  41194. exports.__esModule = true;
  41195. exports["default"] = void 0;
  41196. var _cssesc = _interopRequireDefault(cssesc_1);
  41197. var _util = util;
  41198. var _node = _interopRequireDefault(node$1.exports);
  41199. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41200. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  41201. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  41202. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41203. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41204. var Namespace = /*#__PURE__*/function (_Node) {
  41205. _inheritsLoose(Namespace, _Node);
  41206. function Namespace() {
  41207. return _Node.apply(this, arguments) || this;
  41208. }
  41209. var _proto = Namespace.prototype;
  41210. _proto.qualifiedName = function qualifiedName(value) {
  41211. if (this.namespace) {
  41212. return this.namespaceString + "|" + value;
  41213. } else {
  41214. return value;
  41215. }
  41216. };
  41217. _proto.valueToString = function valueToString() {
  41218. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  41219. };
  41220. _createClass(Namespace, [{
  41221. key: "namespace",
  41222. get: function get() {
  41223. return this._namespace;
  41224. },
  41225. set: function set(namespace) {
  41226. if (namespace === true || namespace === "*" || namespace === "&") {
  41227. this._namespace = namespace;
  41228. if (this.raws) {
  41229. delete this.raws.namespace;
  41230. }
  41231. return;
  41232. }
  41233. var escaped = (0, _cssesc["default"])(namespace, {
  41234. isIdentifier: true
  41235. });
  41236. this._namespace = namespace;
  41237. if (escaped !== namespace) {
  41238. (0, _util.ensureObject)(this, "raws");
  41239. this.raws.namespace = escaped;
  41240. } else if (this.raws) {
  41241. delete this.raws.namespace;
  41242. }
  41243. }
  41244. }, {
  41245. key: "ns",
  41246. get: function get() {
  41247. return this._namespace;
  41248. },
  41249. set: function set(namespace) {
  41250. this.namespace = namespace;
  41251. }
  41252. }, {
  41253. key: "namespaceString",
  41254. get: function get() {
  41255. if (this.namespace) {
  41256. var ns = this.stringifyProperty("namespace");
  41257. if (ns === true) {
  41258. return '';
  41259. } else {
  41260. return ns;
  41261. }
  41262. } else {
  41263. return '';
  41264. }
  41265. }
  41266. }]);
  41267. return Namespace;
  41268. }(_node["default"]);
  41269. exports["default"] = Namespace;
  41270. module.exports = exports.default;
  41271. } (namespace, namespace.exports));
  41272. (function (module, exports) {
  41273. exports.__esModule = true;
  41274. exports["default"] = void 0;
  41275. var _namespace = _interopRequireDefault(namespace.exports);
  41276. var _types = types;
  41277. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41278. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41279. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41280. var Tag = /*#__PURE__*/function (_Namespace) {
  41281. _inheritsLoose(Tag, _Namespace);
  41282. function Tag(opts) {
  41283. var _this;
  41284. _this = _Namespace.call(this, opts) || this;
  41285. _this.type = _types.TAG;
  41286. return _this;
  41287. }
  41288. return Tag;
  41289. }(_namespace["default"]);
  41290. exports["default"] = Tag;
  41291. module.exports = exports.default;
  41292. } (tag$1, tag$1.exports));
  41293. var string$1 = {exports: {}};
  41294. (function (module, exports) {
  41295. exports.__esModule = true;
  41296. exports["default"] = void 0;
  41297. var _node = _interopRequireDefault(node$1.exports);
  41298. var _types = types;
  41299. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41300. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41301. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41302. var String = /*#__PURE__*/function (_Node) {
  41303. _inheritsLoose(String, _Node);
  41304. function String(opts) {
  41305. var _this;
  41306. _this = _Node.call(this, opts) || this;
  41307. _this.type = _types.STRING;
  41308. return _this;
  41309. }
  41310. return String;
  41311. }(_node["default"]);
  41312. exports["default"] = String;
  41313. module.exports = exports.default;
  41314. } (string$1, string$1.exports));
  41315. var pseudo$1 = {exports: {}};
  41316. (function (module, exports) {
  41317. exports.__esModule = true;
  41318. exports["default"] = void 0;
  41319. var _container = _interopRequireDefault(container.exports);
  41320. var _types = types;
  41321. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41322. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41323. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41324. var Pseudo = /*#__PURE__*/function (_Container) {
  41325. _inheritsLoose(Pseudo, _Container);
  41326. function Pseudo(opts) {
  41327. var _this;
  41328. _this = _Container.call(this, opts) || this;
  41329. _this.type = _types.PSEUDO;
  41330. return _this;
  41331. }
  41332. var _proto = Pseudo.prototype;
  41333. _proto.toString = function toString() {
  41334. var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
  41335. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  41336. };
  41337. return Pseudo;
  41338. }(_container["default"]);
  41339. exports["default"] = Pseudo;
  41340. module.exports = exports.default;
  41341. } (pseudo$1, pseudo$1.exports));
  41342. var attribute$1 = {};
  41343. /**
  41344. * For Node.js, simply re-export the core `util.deprecate` function.
  41345. */
  41346. var node = require$$0$1.deprecate;
  41347. (function (exports) {
  41348. exports.__esModule = true;
  41349. exports.unescapeValue = unescapeValue;
  41350. exports["default"] = void 0;
  41351. var _cssesc = _interopRequireDefault(cssesc_1);
  41352. var _unesc = _interopRequireDefault(unesc.exports);
  41353. var _namespace = _interopRequireDefault(namespace.exports);
  41354. var _types = types;
  41355. var _CSSESC_QUOTE_OPTIONS;
  41356. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41357. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  41358. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  41359. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41360. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41361. var deprecate = node;
  41362. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  41363. var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  41364. var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  41365. var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  41366. function unescapeValue(value) {
  41367. var deprecatedUsage = false;
  41368. var quoteMark = null;
  41369. var unescaped = value;
  41370. var m = unescaped.match(WRAPPED_IN_QUOTES);
  41371. if (m) {
  41372. quoteMark = m[1];
  41373. unescaped = m[2];
  41374. }
  41375. unescaped = (0, _unesc["default"])(unescaped);
  41376. if (unescaped !== value) {
  41377. deprecatedUsage = true;
  41378. }
  41379. return {
  41380. deprecatedUsage: deprecatedUsage,
  41381. unescaped: unescaped,
  41382. quoteMark: quoteMark
  41383. };
  41384. }
  41385. function handleDeprecatedContructorOpts(opts) {
  41386. if (opts.quoteMark !== undefined) {
  41387. return opts;
  41388. }
  41389. if (opts.value === undefined) {
  41390. return opts;
  41391. }
  41392. warnOfDeprecatedConstructor();
  41393. var _unescapeValue = unescapeValue(opts.value),
  41394. quoteMark = _unescapeValue.quoteMark,
  41395. unescaped = _unescapeValue.unescaped;
  41396. if (!opts.raws) {
  41397. opts.raws = {};
  41398. }
  41399. if (opts.raws.value === undefined) {
  41400. opts.raws.value = opts.value;
  41401. }
  41402. opts.value = unescaped;
  41403. opts.quoteMark = quoteMark;
  41404. return opts;
  41405. }
  41406. var Attribute = /*#__PURE__*/function (_Namespace) {
  41407. _inheritsLoose(Attribute, _Namespace);
  41408. function Attribute(opts) {
  41409. var _this;
  41410. if (opts === void 0) {
  41411. opts = {};
  41412. }
  41413. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  41414. _this.type = _types.ATTRIBUTE;
  41415. _this.raws = _this.raws || {};
  41416. Object.defineProperty(_this.raws, 'unquoted', {
  41417. get: deprecate(function () {
  41418. return _this.value;
  41419. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  41420. set: deprecate(function () {
  41421. return _this.value;
  41422. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  41423. });
  41424. _this._constructed = true;
  41425. return _this;
  41426. }
  41427. /**
  41428. * Returns the Attribute's value quoted such that it would be legal to use
  41429. * in the value of a css file. The original value's quotation setting
  41430. * used for stringification is left unchanged. See `setValue(value, options)`
  41431. * if you want to control the quote settings of a new value for the attribute.
  41432. *
  41433. * You can also change the quotation used for the current value by setting quoteMark.
  41434. *
  41435. * Options:
  41436. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  41437. * option is not set, the original value for quoteMark will be used. If
  41438. * indeterminate, a double quote is used. The legal values are:
  41439. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  41440. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  41441. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  41442. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  41443. * over the quoteMark option value.
  41444. * * smart {boolean} - if true, will select a quote mark based on the value
  41445. * and the other options specified here. See the `smartQuoteMark()`
  41446. * method.
  41447. **/
  41448. var _proto = Attribute.prototype;
  41449. _proto.getQuotedValue = function getQuotedValue(options) {
  41450. if (options === void 0) {
  41451. options = {};
  41452. }
  41453. var quoteMark = this._determineQuoteMark(options);
  41454. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  41455. var escaped = (0, _cssesc["default"])(this._value, cssescopts);
  41456. return escaped;
  41457. };
  41458. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  41459. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  41460. }
  41461. /**
  41462. * Set the unescaped value with the specified quotation options. The value
  41463. * provided must not include any wrapping quote marks -- those quotes will
  41464. * be interpreted as part of the value and escaped accordingly.
  41465. */
  41466. ;
  41467. _proto.setValue = function setValue(value, options) {
  41468. if (options === void 0) {
  41469. options = {};
  41470. }
  41471. this._value = value;
  41472. this._quoteMark = this._determineQuoteMark(options);
  41473. this._syncRawValue();
  41474. }
  41475. /**
  41476. * Intelligently select a quoteMark value based on the value's contents. If
  41477. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  41478. * mark will be picked that minimizes the number of escapes.
  41479. *
  41480. * If there's no clear winner, the quote mark from these options is used,
  41481. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  41482. * true). If the quoteMark is unspecified, a double quote is used.
  41483. *
  41484. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  41485. * from the quoteValue method.
  41486. */
  41487. ;
  41488. _proto.smartQuoteMark = function smartQuoteMark(options) {
  41489. var v = this.value;
  41490. var numSingleQuotes = v.replace(/[^']/g, '').length;
  41491. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  41492. if (numSingleQuotes + numDoubleQuotes === 0) {
  41493. var escaped = (0, _cssesc["default"])(v, {
  41494. isIdentifier: true
  41495. });
  41496. if (escaped === v) {
  41497. return Attribute.NO_QUOTE;
  41498. } else {
  41499. var pref = this.preferredQuoteMark(options);
  41500. if (pref === Attribute.NO_QUOTE) {
  41501. // pick a quote mark that isn't none and see if it's smaller
  41502. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  41503. var opts = CSSESC_QUOTE_OPTIONS[quote];
  41504. var quoteValue = (0, _cssesc["default"])(v, opts);
  41505. if (quoteValue.length < escaped.length) {
  41506. return quote;
  41507. }
  41508. }
  41509. return pref;
  41510. }
  41511. } else if (numDoubleQuotes === numSingleQuotes) {
  41512. return this.preferredQuoteMark(options);
  41513. } else if (numDoubleQuotes < numSingleQuotes) {
  41514. return Attribute.DOUBLE_QUOTE;
  41515. } else {
  41516. return Attribute.SINGLE_QUOTE;
  41517. }
  41518. }
  41519. /**
  41520. * Selects the preferred quote mark based on the options and the current quote mark value.
  41521. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  41522. * instead.
  41523. */
  41524. ;
  41525. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  41526. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  41527. if (quoteMark === undefined) {
  41528. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  41529. }
  41530. if (quoteMark === undefined) {
  41531. quoteMark = Attribute.DOUBLE_QUOTE;
  41532. }
  41533. return quoteMark;
  41534. };
  41535. _proto._syncRawValue = function _syncRawValue() {
  41536. var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  41537. if (rawValue === this._value) {
  41538. if (this.raws) {
  41539. delete this.raws.value;
  41540. }
  41541. } else {
  41542. this.raws.value = rawValue;
  41543. }
  41544. };
  41545. _proto._handleEscapes = function _handleEscapes(prop, value) {
  41546. if (this._constructed) {
  41547. var escaped = (0, _cssesc["default"])(value, {
  41548. isIdentifier: true
  41549. });
  41550. if (escaped !== value) {
  41551. this.raws[prop] = escaped;
  41552. } else {
  41553. delete this.raws[prop];
  41554. }
  41555. }
  41556. };
  41557. _proto._spacesFor = function _spacesFor(name) {
  41558. var attrSpaces = {
  41559. before: '',
  41560. after: ''
  41561. };
  41562. var spaces = this.spaces[name] || {};
  41563. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  41564. return Object.assign(attrSpaces, spaces, rawSpaces);
  41565. };
  41566. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  41567. if (spaceName === void 0) {
  41568. spaceName = name;
  41569. }
  41570. if (concat === void 0) {
  41571. concat = defaultAttrConcat;
  41572. }
  41573. var attrSpaces = this._spacesFor(spaceName);
  41574. return concat(this.stringifyProperty(name), attrSpaces);
  41575. }
  41576. /**
  41577. * returns the offset of the attribute part specified relative to the
  41578. * start of the node of the output string.
  41579. *
  41580. * * "ns" - alias for "namespace"
  41581. * * "namespace" - the namespace if it exists.
  41582. * * "attribute" - the attribute name
  41583. * * "attributeNS" - the start of the attribute or its namespace
  41584. * * "operator" - the match operator of the attribute
  41585. * * "value" - The value (string or identifier)
  41586. * * "insensitive" - the case insensitivity flag;
  41587. * @param part One of the possible values inside an attribute.
  41588. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  41589. */
  41590. ;
  41591. _proto.offsetOf = function offsetOf(name) {
  41592. var count = 1;
  41593. var attributeSpaces = this._spacesFor("attribute");
  41594. count += attributeSpaces.before.length;
  41595. if (name === "namespace" || name === "ns") {
  41596. return this.namespace ? count : -1;
  41597. }
  41598. if (name === "attributeNS") {
  41599. return count;
  41600. }
  41601. count += this.namespaceString.length;
  41602. if (this.namespace) {
  41603. count += 1;
  41604. }
  41605. if (name === "attribute") {
  41606. return count;
  41607. }
  41608. count += this.stringifyProperty("attribute").length;
  41609. count += attributeSpaces.after.length;
  41610. var operatorSpaces = this._spacesFor("operator");
  41611. count += operatorSpaces.before.length;
  41612. var operator = this.stringifyProperty("operator");
  41613. if (name === "operator") {
  41614. return operator ? count : -1;
  41615. }
  41616. count += operator.length;
  41617. count += operatorSpaces.after.length;
  41618. var valueSpaces = this._spacesFor("value");
  41619. count += valueSpaces.before.length;
  41620. var value = this.stringifyProperty("value");
  41621. if (name === "value") {
  41622. return value ? count : -1;
  41623. }
  41624. count += value.length;
  41625. count += valueSpaces.after.length;
  41626. var insensitiveSpaces = this._spacesFor("insensitive");
  41627. count += insensitiveSpaces.before.length;
  41628. if (name === "insensitive") {
  41629. return this.insensitive ? count : -1;
  41630. }
  41631. return -1;
  41632. };
  41633. _proto.toString = function toString() {
  41634. var _this2 = this;
  41635. var selector = [this.rawSpaceBefore, '['];
  41636. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  41637. if (this.operator && (this.value || this.value === '')) {
  41638. selector.push(this._stringFor('operator'));
  41639. selector.push(this._stringFor('value'));
  41640. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  41641. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  41642. attrSpaces.before = " ";
  41643. }
  41644. return defaultAttrConcat(attrValue, attrSpaces);
  41645. }));
  41646. }
  41647. selector.push(']');
  41648. selector.push(this.rawSpaceAfter);
  41649. return selector.join('');
  41650. };
  41651. _createClass(Attribute, [{
  41652. key: "quoted",
  41653. get: function get() {
  41654. var qm = this.quoteMark;
  41655. return qm === "'" || qm === '"';
  41656. },
  41657. set: function set(value) {
  41658. warnOfDeprecatedQuotedAssignment();
  41659. }
  41660. /**
  41661. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  41662. * returns `null` if the value is not quoted.
  41663. * returns `undefined` if the quotation state is unknown (this can happen when
  41664. * the attribute is constructed without specifying a quote mark.)
  41665. */
  41666. }, {
  41667. key: "quoteMark",
  41668. get: function get() {
  41669. return this._quoteMark;
  41670. }
  41671. /**
  41672. * Set the quote mark to be used by this attribute's value.
  41673. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  41674. * value is updated accordingly.
  41675. *
  41676. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  41677. */
  41678. ,
  41679. set: function set(quoteMark) {
  41680. if (!this._constructed) {
  41681. this._quoteMark = quoteMark;
  41682. return;
  41683. }
  41684. if (this._quoteMark !== quoteMark) {
  41685. this._quoteMark = quoteMark;
  41686. this._syncRawValue();
  41687. }
  41688. }
  41689. }, {
  41690. key: "qualifiedAttribute",
  41691. get: function get() {
  41692. return this.qualifiedName(this.raws.attribute || this.attribute);
  41693. }
  41694. }, {
  41695. key: "insensitiveFlag",
  41696. get: function get() {
  41697. return this.insensitive ? 'i' : '';
  41698. }
  41699. }, {
  41700. key: "value",
  41701. get: function get() {
  41702. return this._value;
  41703. }
  41704. /**
  41705. * Before 3.0, the value had to be set to an escaped value including any wrapped
  41706. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  41707. * is unescaped during parsing and any quote marks are removed.
  41708. *
  41709. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  41710. * a deprecation warning is raised when the new value contains any characters that would
  41711. * require escaping (including if it contains wrapped quotes).
  41712. *
  41713. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  41714. * how the new value is quoted.
  41715. */
  41716. ,
  41717. set: function set(v) {
  41718. if (this._constructed) {
  41719. var _unescapeValue2 = unescapeValue(v),
  41720. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  41721. unescaped = _unescapeValue2.unescaped,
  41722. quoteMark = _unescapeValue2.quoteMark;
  41723. if (deprecatedUsage) {
  41724. warnOfDeprecatedValueAssignment();
  41725. }
  41726. if (unescaped === this._value && quoteMark === this._quoteMark) {
  41727. return;
  41728. }
  41729. this._value = unescaped;
  41730. this._quoteMark = quoteMark;
  41731. this._syncRawValue();
  41732. } else {
  41733. this._value = v;
  41734. }
  41735. }
  41736. }, {
  41737. key: "attribute",
  41738. get: function get() {
  41739. return this._attribute;
  41740. },
  41741. set: function set(name) {
  41742. this._handleEscapes("attribute", name);
  41743. this._attribute = name;
  41744. }
  41745. }]);
  41746. return Attribute;
  41747. }(_namespace["default"]);
  41748. exports["default"] = Attribute;
  41749. Attribute.NO_QUOTE = null;
  41750. Attribute.SINGLE_QUOTE = "'";
  41751. Attribute.DOUBLE_QUOTE = '"';
  41752. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  41753. "'": {
  41754. quotes: 'single',
  41755. wrap: true
  41756. },
  41757. '"': {
  41758. quotes: 'double',
  41759. wrap: true
  41760. }
  41761. }, _CSSESC_QUOTE_OPTIONS[null] = {
  41762. isIdentifier: true
  41763. }, _CSSESC_QUOTE_OPTIONS);
  41764. function defaultAttrConcat(attrValue, attrSpaces) {
  41765. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  41766. }
  41767. } (attribute$1));
  41768. var universal$1 = {exports: {}};
  41769. (function (module, exports) {
  41770. exports.__esModule = true;
  41771. exports["default"] = void 0;
  41772. var _namespace = _interopRequireDefault(namespace.exports);
  41773. var _types = types;
  41774. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41775. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41776. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41777. var Universal = /*#__PURE__*/function (_Namespace) {
  41778. _inheritsLoose(Universal, _Namespace);
  41779. function Universal(opts) {
  41780. var _this;
  41781. _this = _Namespace.call(this, opts) || this;
  41782. _this.type = _types.UNIVERSAL;
  41783. _this.value = '*';
  41784. return _this;
  41785. }
  41786. return Universal;
  41787. }(_namespace["default"]);
  41788. exports["default"] = Universal;
  41789. module.exports = exports.default;
  41790. } (universal$1, universal$1.exports));
  41791. var combinator$2 = {exports: {}};
  41792. (function (module, exports) {
  41793. exports.__esModule = true;
  41794. exports["default"] = void 0;
  41795. var _node = _interopRequireDefault(node$1.exports);
  41796. var _types = types;
  41797. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41798. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41799. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41800. var Combinator = /*#__PURE__*/function (_Node) {
  41801. _inheritsLoose(Combinator, _Node);
  41802. function Combinator(opts) {
  41803. var _this;
  41804. _this = _Node.call(this, opts) || this;
  41805. _this.type = _types.COMBINATOR;
  41806. return _this;
  41807. }
  41808. return Combinator;
  41809. }(_node["default"]);
  41810. exports["default"] = Combinator;
  41811. module.exports = exports.default;
  41812. } (combinator$2, combinator$2.exports));
  41813. var nesting$1 = {exports: {}};
  41814. (function (module, exports) {
  41815. exports.__esModule = true;
  41816. exports["default"] = void 0;
  41817. var _node = _interopRequireDefault(node$1.exports);
  41818. var _types = types;
  41819. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41820. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41821. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41822. var Nesting = /*#__PURE__*/function (_Node) {
  41823. _inheritsLoose(Nesting, _Node);
  41824. function Nesting(opts) {
  41825. var _this;
  41826. _this = _Node.call(this, opts) || this;
  41827. _this.type = _types.NESTING;
  41828. _this.value = '&';
  41829. return _this;
  41830. }
  41831. return Nesting;
  41832. }(_node["default"]);
  41833. exports["default"] = Nesting;
  41834. module.exports = exports.default;
  41835. } (nesting$1, nesting$1.exports));
  41836. var sortAscending = {exports: {}};
  41837. (function (module, exports) {
  41838. exports.__esModule = true;
  41839. exports["default"] = sortAscending;
  41840. function sortAscending(list) {
  41841. return list.sort(function (a, b) {
  41842. return a - b;
  41843. });
  41844. }
  41845. module.exports = exports.default;
  41846. } (sortAscending, sortAscending.exports));
  41847. var tokenize = {};
  41848. var tokenTypes = {};
  41849. tokenTypes.__esModule = true;
  41850. tokenTypes.combinator = tokenTypes.word = tokenTypes.comment = tokenTypes.str = tokenTypes.tab = tokenTypes.newline = tokenTypes.feed = tokenTypes.cr = tokenTypes.backslash = tokenTypes.bang = tokenTypes.slash = tokenTypes.doubleQuote = tokenTypes.singleQuote = tokenTypes.space = tokenTypes.greaterThan = tokenTypes.pipe = tokenTypes.equals = tokenTypes.plus = tokenTypes.caret = tokenTypes.tilde = tokenTypes.dollar = tokenTypes.closeSquare = tokenTypes.openSquare = tokenTypes.closeParenthesis = tokenTypes.openParenthesis = tokenTypes.semicolon = tokenTypes.colon = tokenTypes.comma = tokenTypes.at = tokenTypes.asterisk = tokenTypes.ampersand = void 0;
  41851. var ampersand = 38; // `&`.charCodeAt(0);
  41852. tokenTypes.ampersand = ampersand;
  41853. var asterisk = 42; // `*`.charCodeAt(0);
  41854. tokenTypes.asterisk = asterisk;
  41855. var at = 64; // `@`.charCodeAt(0);
  41856. tokenTypes.at = at;
  41857. var comma = 44; // `,`.charCodeAt(0);
  41858. tokenTypes.comma = comma;
  41859. var colon = 58; // `:`.charCodeAt(0);
  41860. tokenTypes.colon = colon;
  41861. var semicolon = 59; // `;`.charCodeAt(0);
  41862. tokenTypes.semicolon = semicolon;
  41863. var openParenthesis = 40; // `(`.charCodeAt(0);
  41864. tokenTypes.openParenthesis = openParenthesis;
  41865. var closeParenthesis = 41; // `)`.charCodeAt(0);
  41866. tokenTypes.closeParenthesis = closeParenthesis;
  41867. var openSquare = 91; // `[`.charCodeAt(0);
  41868. tokenTypes.openSquare = openSquare;
  41869. var closeSquare = 93; // `]`.charCodeAt(0);
  41870. tokenTypes.closeSquare = closeSquare;
  41871. var dollar = 36; // `$`.charCodeAt(0);
  41872. tokenTypes.dollar = dollar;
  41873. var tilde = 126; // `~`.charCodeAt(0);
  41874. tokenTypes.tilde = tilde;
  41875. var caret = 94; // `^`.charCodeAt(0);
  41876. tokenTypes.caret = caret;
  41877. var plus = 43; // `+`.charCodeAt(0);
  41878. tokenTypes.plus = plus;
  41879. var equals = 61; // `=`.charCodeAt(0);
  41880. tokenTypes.equals = equals;
  41881. var pipe = 124; // `|`.charCodeAt(0);
  41882. tokenTypes.pipe = pipe;
  41883. var greaterThan = 62; // `>`.charCodeAt(0);
  41884. tokenTypes.greaterThan = greaterThan;
  41885. var space = 32; // ` `.charCodeAt(0);
  41886. tokenTypes.space = space;
  41887. var singleQuote = 39; // `'`.charCodeAt(0);
  41888. tokenTypes.singleQuote = singleQuote;
  41889. var doubleQuote = 34; // `"`.charCodeAt(0);
  41890. tokenTypes.doubleQuote = doubleQuote;
  41891. var slash = 47; // `/`.charCodeAt(0);
  41892. tokenTypes.slash = slash;
  41893. var bang = 33; // `!`.charCodeAt(0);
  41894. tokenTypes.bang = bang;
  41895. var backslash = 92; // '\\'.charCodeAt(0);
  41896. tokenTypes.backslash = backslash;
  41897. var cr = 13; // '\r'.charCodeAt(0);
  41898. tokenTypes.cr = cr;
  41899. var feed = 12; // '\f'.charCodeAt(0);
  41900. tokenTypes.feed = feed;
  41901. var newline = 10; // '\n'.charCodeAt(0);
  41902. tokenTypes.newline = newline;
  41903. var tab = 9; // '\t'.charCodeAt(0);
  41904. // Expose aliases primarily for readability.
  41905. tokenTypes.tab = tab;
  41906. var str = singleQuote; // No good single character representation!
  41907. tokenTypes.str = str;
  41908. var comment$1 = -1;
  41909. tokenTypes.comment = comment$1;
  41910. var word = -2;
  41911. tokenTypes.word = word;
  41912. var combinator$1 = -3;
  41913. tokenTypes.combinator = combinator$1;
  41914. (function (exports) {
  41915. exports.__esModule = true;
  41916. exports["default"] = tokenize;
  41917. exports.FIELDS = void 0;
  41918. var t = _interopRequireWildcard(tokenTypes);
  41919. var _unescapable, _wordDelimiters;
  41920. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  41921. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  41922. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  41923. var wordDelimiters = (_wordDelimiters = {}, _wordDelimiters[t.space] = true, _wordDelimiters[t.tab] = true, _wordDelimiters[t.newline] = true, _wordDelimiters[t.cr] = true, _wordDelimiters[t.feed] = true, _wordDelimiters[t.ampersand] = true, _wordDelimiters[t.asterisk] = true, _wordDelimiters[t.bang] = true, _wordDelimiters[t.comma] = true, _wordDelimiters[t.colon] = true, _wordDelimiters[t.semicolon] = true, _wordDelimiters[t.openParenthesis] = true, _wordDelimiters[t.closeParenthesis] = true, _wordDelimiters[t.openSquare] = true, _wordDelimiters[t.closeSquare] = true, _wordDelimiters[t.singleQuote] = true, _wordDelimiters[t.doubleQuote] = true, _wordDelimiters[t.plus] = true, _wordDelimiters[t.pipe] = true, _wordDelimiters[t.tilde] = true, _wordDelimiters[t.greaterThan] = true, _wordDelimiters[t.equals] = true, _wordDelimiters[t.dollar] = true, _wordDelimiters[t.caret] = true, _wordDelimiters[t.slash] = true, _wordDelimiters);
  41924. var hex = {};
  41925. var hexChars = "0123456789abcdefABCDEF";
  41926. for (var i = 0; i < hexChars.length; i++) {
  41927. hex[hexChars.charCodeAt(i)] = true;
  41928. }
  41929. /**
  41930. * Returns the last index of the bar css word
  41931. * @param {string} css The string in which the word begins
  41932. * @param {number} start The index into the string where word's first letter occurs
  41933. */
  41934. function consumeWord(css, start) {
  41935. var next = start;
  41936. var code;
  41937. do {
  41938. code = css.charCodeAt(next);
  41939. if (wordDelimiters[code]) {
  41940. return next - 1;
  41941. } else if (code === t.backslash) {
  41942. next = consumeEscape(css, next) + 1;
  41943. } else {
  41944. // All other characters are part of the word
  41945. next++;
  41946. }
  41947. } while (next < css.length);
  41948. return next - 1;
  41949. }
  41950. /**
  41951. * Returns the last index of the escape sequence
  41952. * @param {string} css The string in which the sequence begins
  41953. * @param {number} start The index into the string where escape character (`\`) occurs.
  41954. */
  41955. function consumeEscape(css, start) {
  41956. var next = start;
  41957. var code = css.charCodeAt(next + 1);
  41958. if (unescapable[code]) ; else if (hex[code]) {
  41959. var hexDigits = 0; // consume up to 6 hex chars
  41960. do {
  41961. next++;
  41962. hexDigits++;
  41963. code = css.charCodeAt(next + 1);
  41964. } while (hex[code] && hexDigits < 6); // if fewer than 6 hex chars, a trailing space ends the escape
  41965. if (hexDigits < 6 && code === t.space) {
  41966. next++;
  41967. }
  41968. } else {
  41969. // the next char is part of the current word
  41970. next++;
  41971. }
  41972. return next;
  41973. }
  41974. var FIELDS = {
  41975. TYPE: 0,
  41976. START_LINE: 1,
  41977. START_COL: 2,
  41978. END_LINE: 3,
  41979. END_COL: 4,
  41980. START_POS: 5,
  41981. END_POS: 6
  41982. };
  41983. exports.FIELDS = FIELDS;
  41984. function tokenize(input) {
  41985. var tokens = [];
  41986. var css = input.css.valueOf();
  41987. var _css = css,
  41988. length = _css.length;
  41989. var offset = -1;
  41990. var line = 1;
  41991. var start = 0;
  41992. var end = 0;
  41993. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  41994. function unclosed(what, fix) {
  41995. if (input.safe) {
  41996. // fyi: this is never set to true.
  41997. css += fix;
  41998. next = css.length - 1;
  41999. } else {
  42000. throw input.error('Unclosed ' + what, line, start - offset, start);
  42001. }
  42002. }
  42003. while (start < length) {
  42004. code = css.charCodeAt(start);
  42005. if (code === t.newline) {
  42006. offset = start;
  42007. line += 1;
  42008. }
  42009. switch (code) {
  42010. case t.space:
  42011. case t.tab:
  42012. case t.newline:
  42013. case t.cr:
  42014. case t.feed:
  42015. next = start;
  42016. do {
  42017. next += 1;
  42018. code = css.charCodeAt(next);
  42019. if (code === t.newline) {
  42020. offset = next;
  42021. line += 1;
  42022. }
  42023. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  42024. tokenType = t.space;
  42025. endLine = line;
  42026. endColumn = next - offset - 1;
  42027. end = next;
  42028. break;
  42029. case t.plus:
  42030. case t.greaterThan:
  42031. case t.tilde:
  42032. case t.pipe:
  42033. next = start;
  42034. do {
  42035. next += 1;
  42036. code = css.charCodeAt(next);
  42037. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  42038. tokenType = t.combinator;
  42039. endLine = line;
  42040. endColumn = start - offset;
  42041. end = next;
  42042. break;
  42043. // Consume these characters as single tokens.
  42044. case t.asterisk:
  42045. case t.ampersand:
  42046. case t.bang:
  42047. case t.comma:
  42048. case t.equals:
  42049. case t.dollar:
  42050. case t.caret:
  42051. case t.openSquare:
  42052. case t.closeSquare:
  42053. case t.colon:
  42054. case t.semicolon:
  42055. case t.openParenthesis:
  42056. case t.closeParenthesis:
  42057. next = start;
  42058. tokenType = code;
  42059. endLine = line;
  42060. endColumn = start - offset;
  42061. end = next + 1;
  42062. break;
  42063. case t.singleQuote:
  42064. case t.doubleQuote:
  42065. quote = code === t.singleQuote ? "'" : '"';
  42066. next = start;
  42067. do {
  42068. escaped = false;
  42069. next = css.indexOf(quote, next + 1);
  42070. if (next === -1) {
  42071. unclosed('quote', quote);
  42072. }
  42073. escapePos = next;
  42074. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  42075. escapePos -= 1;
  42076. escaped = !escaped;
  42077. }
  42078. } while (escaped);
  42079. tokenType = t.str;
  42080. endLine = line;
  42081. endColumn = start - offset;
  42082. end = next + 1;
  42083. break;
  42084. default:
  42085. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  42086. next = css.indexOf('*/', start + 2) + 1;
  42087. if (next === 0) {
  42088. unclosed('comment', '*/');
  42089. }
  42090. content = css.slice(start, next + 1);
  42091. lines = content.split('\n');
  42092. last = lines.length - 1;
  42093. if (last > 0) {
  42094. nextLine = line + last;
  42095. nextOffset = next - lines[last].length;
  42096. } else {
  42097. nextLine = line;
  42098. nextOffset = offset;
  42099. }
  42100. tokenType = t.comment;
  42101. line = nextLine;
  42102. endLine = nextLine;
  42103. endColumn = next - nextOffset;
  42104. } else if (code === t.slash) {
  42105. next = start;
  42106. tokenType = code;
  42107. endLine = line;
  42108. endColumn = start - offset;
  42109. end = next + 1;
  42110. } else {
  42111. next = consumeWord(css, start);
  42112. tokenType = t.word;
  42113. endLine = line;
  42114. endColumn = next - offset;
  42115. }
  42116. end = next + 1;
  42117. break;
  42118. } // Ensure that the token structure remains consistent
  42119. tokens.push([tokenType, // [0] Token type
  42120. line, // [1] Starting line
  42121. start - offset, // [2] Starting column
  42122. endLine, // [3] Ending line
  42123. endColumn, // [4] Ending column
  42124. start, // [5] Start position / Source index
  42125. end // [6] End position
  42126. ]); // Reset offset for the next token
  42127. if (nextOffset) {
  42128. offset = nextOffset;
  42129. nextOffset = null;
  42130. }
  42131. start = end;
  42132. }
  42133. return tokens;
  42134. }
  42135. } (tokenize));
  42136. (function (module, exports) {
  42137. exports.__esModule = true;
  42138. exports["default"] = void 0;
  42139. var _root = _interopRequireDefault(root$1.exports);
  42140. var _selector = _interopRequireDefault(selector$1.exports);
  42141. var _className = _interopRequireDefault(className$1.exports);
  42142. var _comment = _interopRequireDefault(comment$2.exports);
  42143. var _id = _interopRequireDefault(id$1.exports);
  42144. var _tag = _interopRequireDefault(tag$1.exports);
  42145. var _string = _interopRequireDefault(string$1.exports);
  42146. var _pseudo = _interopRequireDefault(pseudo$1.exports);
  42147. var _attribute = _interopRequireWildcard(attribute$1);
  42148. var _universal = _interopRequireDefault(universal$1.exports);
  42149. var _combinator = _interopRequireDefault(combinator$2.exports);
  42150. var _nesting = _interopRequireDefault(nesting$1.exports);
  42151. var _sortAscending = _interopRequireDefault(sortAscending.exports);
  42152. var _tokenize = _interopRequireWildcard(tokenize);
  42153. var tokens = _interopRequireWildcard(tokenTypes);
  42154. var types$1 = _interopRequireWildcard(types);
  42155. var _util = util;
  42156. var _WHITESPACE_TOKENS, _Object$assign;
  42157. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  42158. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  42159. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  42160. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  42161. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  42162. var WHITESPACE_TOKENS = (_WHITESPACE_TOKENS = {}, _WHITESPACE_TOKENS[tokens.space] = true, _WHITESPACE_TOKENS[tokens.cr] = true, _WHITESPACE_TOKENS[tokens.feed] = true, _WHITESPACE_TOKENS[tokens.newline] = true, _WHITESPACE_TOKENS[tokens.tab] = true, _WHITESPACE_TOKENS);
  42163. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  42164. function tokenStart(token) {
  42165. return {
  42166. line: token[_tokenize.FIELDS.START_LINE],
  42167. column: token[_tokenize.FIELDS.START_COL]
  42168. };
  42169. }
  42170. function tokenEnd(token) {
  42171. return {
  42172. line: token[_tokenize.FIELDS.END_LINE],
  42173. column: token[_tokenize.FIELDS.END_COL]
  42174. };
  42175. }
  42176. function getSource(startLine, startColumn, endLine, endColumn) {
  42177. return {
  42178. start: {
  42179. line: startLine,
  42180. column: startColumn
  42181. },
  42182. end: {
  42183. line: endLine,
  42184. column: endColumn
  42185. }
  42186. };
  42187. }
  42188. function getTokenSource(token) {
  42189. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  42190. }
  42191. function getTokenSourceSpan(startToken, endToken) {
  42192. if (!startToken) {
  42193. return undefined;
  42194. }
  42195. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  42196. }
  42197. function unescapeProp(node, prop) {
  42198. var value = node[prop];
  42199. if (typeof value !== "string") {
  42200. return;
  42201. }
  42202. if (value.indexOf("\\") !== -1) {
  42203. (0, _util.ensureObject)(node, 'raws');
  42204. node[prop] = (0, _util.unesc)(value);
  42205. if (node.raws[prop] === undefined) {
  42206. node.raws[prop] = value;
  42207. }
  42208. }
  42209. return node;
  42210. }
  42211. function indexesOf(array, item) {
  42212. var i = -1;
  42213. var indexes = [];
  42214. while ((i = array.indexOf(item, i + 1)) !== -1) {
  42215. indexes.push(i);
  42216. }
  42217. return indexes;
  42218. }
  42219. function uniqs() {
  42220. var list = Array.prototype.concat.apply([], arguments);
  42221. return list.filter(function (item, i) {
  42222. return i === list.indexOf(item);
  42223. });
  42224. }
  42225. var Parser = /*#__PURE__*/function () {
  42226. function Parser(rule, options) {
  42227. if (options === void 0) {
  42228. options = {};
  42229. }
  42230. this.rule = rule;
  42231. this.options = Object.assign({
  42232. lossy: false,
  42233. safe: false
  42234. }, options);
  42235. this.position = 0;
  42236. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  42237. this.tokens = (0, _tokenize["default"])({
  42238. css: this.css,
  42239. error: this._errorGenerator(),
  42240. safe: this.options.safe
  42241. });
  42242. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  42243. this.root = new _root["default"]({
  42244. source: rootSource
  42245. });
  42246. this.root.errorGenerator = this._errorGenerator();
  42247. var selector = new _selector["default"]({
  42248. source: {
  42249. start: {
  42250. line: 1,
  42251. column: 1
  42252. }
  42253. }
  42254. });
  42255. this.root.append(selector);
  42256. this.current = selector;
  42257. this.loop();
  42258. }
  42259. var _proto = Parser.prototype;
  42260. _proto._errorGenerator = function _errorGenerator() {
  42261. var _this = this;
  42262. return function (message, errorOptions) {
  42263. if (typeof _this.rule === 'string') {
  42264. return new Error(message);
  42265. }
  42266. return _this.rule.error(message, errorOptions);
  42267. };
  42268. };
  42269. _proto.attribute = function attribute() {
  42270. var attr = [];
  42271. var startingToken = this.currToken;
  42272. this.position++;
  42273. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  42274. attr.push(this.currToken);
  42275. this.position++;
  42276. }
  42277. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  42278. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  42279. }
  42280. var len = attr.length;
  42281. var node = {
  42282. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  42283. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  42284. };
  42285. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  42286. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  42287. }
  42288. var pos = 0;
  42289. var spaceBefore = '';
  42290. var commentBefore = '';
  42291. var lastAdded = null;
  42292. var spaceAfterMeaningfulToken = false;
  42293. while (pos < len) {
  42294. var token = attr[pos];
  42295. var content = this.content(token);
  42296. var next = attr[pos + 1];
  42297. switch (token[_tokenize.FIELDS.TYPE]) {
  42298. case tokens.space:
  42299. // if (
  42300. // len === 1 ||
  42301. // pos === 0 && this.content(next) === '|'
  42302. // ) {
  42303. // return this.expected('attribute', token[TOKEN.START_POS], content);
  42304. // }
  42305. spaceAfterMeaningfulToken = true;
  42306. if (this.options.lossy) {
  42307. break;
  42308. }
  42309. if (lastAdded) {
  42310. (0, _util.ensureObject)(node, 'spaces', lastAdded);
  42311. var prevContent = node.spaces[lastAdded].after || '';
  42312. node.spaces[lastAdded].after = prevContent + content;
  42313. var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  42314. if (existingComment) {
  42315. node.raws.spaces[lastAdded].after = existingComment + content;
  42316. }
  42317. } else {
  42318. spaceBefore = spaceBefore + content;
  42319. commentBefore = commentBefore + content;
  42320. }
  42321. break;
  42322. case tokens.asterisk:
  42323. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  42324. node.operator = content;
  42325. lastAdded = 'operator';
  42326. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  42327. if (spaceBefore) {
  42328. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  42329. node.spaces.attribute.before = spaceBefore;
  42330. spaceBefore = '';
  42331. }
  42332. if (commentBefore) {
  42333. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  42334. node.raws.spaces.attribute.before = spaceBefore;
  42335. commentBefore = '';
  42336. }
  42337. node.namespace = (node.namespace || "") + content;
  42338. var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
  42339. if (rawValue) {
  42340. node.raws.namespace += content;
  42341. }
  42342. lastAdded = 'namespace';
  42343. }
  42344. spaceAfterMeaningfulToken = false;
  42345. break;
  42346. case tokens.dollar:
  42347. if (lastAdded === "value") {
  42348. var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
  42349. node.value += "$";
  42350. if (oldRawValue) {
  42351. node.raws.value = oldRawValue + "$";
  42352. }
  42353. break;
  42354. }
  42355. // Falls through
  42356. case tokens.caret:
  42357. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  42358. node.operator = content;
  42359. lastAdded = 'operator';
  42360. }
  42361. spaceAfterMeaningfulToken = false;
  42362. break;
  42363. case tokens.combinator:
  42364. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  42365. node.operator = content;
  42366. lastAdded = 'operator';
  42367. }
  42368. if (content !== '|') {
  42369. spaceAfterMeaningfulToken = false;
  42370. break;
  42371. }
  42372. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  42373. node.operator = content;
  42374. lastAdded = 'operator';
  42375. } else if (!node.namespace && !node.attribute) {
  42376. node.namespace = true;
  42377. }
  42378. spaceAfterMeaningfulToken = false;
  42379. break;
  42380. case tokens.word:
  42381. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals && // this look-ahead probably fails with comment nodes involved.
  42382. !node.operator && !node.namespace) {
  42383. node.namespace = content;
  42384. lastAdded = 'namespace';
  42385. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  42386. if (spaceBefore) {
  42387. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  42388. node.spaces.attribute.before = spaceBefore;
  42389. spaceBefore = '';
  42390. }
  42391. if (commentBefore) {
  42392. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  42393. node.raws.spaces.attribute.before = commentBefore;
  42394. commentBefore = '';
  42395. }
  42396. node.attribute = (node.attribute || "") + content;
  42397. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  42398. if (_rawValue) {
  42399. node.raws.attribute += content;
  42400. }
  42401. lastAdded = 'attribute';
  42402. } else if (!node.value && node.value !== "" || lastAdded === "value" && !spaceAfterMeaningfulToken) {
  42403. var _unescaped = (0, _util.unesc)(content);
  42404. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  42405. var oldValue = node.value || '';
  42406. node.value = oldValue + _unescaped;
  42407. node.quoteMark = null;
  42408. if (_unescaped !== content || _oldRawValue) {
  42409. (0, _util.ensureObject)(node, 'raws');
  42410. node.raws.value = (_oldRawValue || oldValue) + content;
  42411. }
  42412. lastAdded = 'value';
  42413. } else {
  42414. var insensitive = content === 'i' || content === "I";
  42415. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  42416. node.insensitive = insensitive;
  42417. if (!insensitive || content === "I") {
  42418. (0, _util.ensureObject)(node, 'raws');
  42419. node.raws.insensitiveFlag = content;
  42420. }
  42421. lastAdded = 'insensitive';
  42422. if (spaceBefore) {
  42423. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  42424. node.spaces.insensitive.before = spaceBefore;
  42425. spaceBefore = '';
  42426. }
  42427. if (commentBefore) {
  42428. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  42429. node.raws.spaces.insensitive.before = commentBefore;
  42430. commentBefore = '';
  42431. }
  42432. } else if (node.value || node.value === '') {
  42433. lastAdded = 'value';
  42434. node.value += content;
  42435. if (node.raws.value) {
  42436. node.raws.value += content;
  42437. }
  42438. }
  42439. }
  42440. spaceAfterMeaningfulToken = false;
  42441. break;
  42442. case tokens.str:
  42443. if (!node.attribute || !node.operator) {
  42444. return this.error("Expected an attribute followed by an operator preceding the string.", {
  42445. index: token[_tokenize.FIELDS.START_POS]
  42446. });
  42447. }
  42448. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  42449. unescaped = _unescapeValue.unescaped,
  42450. quoteMark = _unescapeValue.quoteMark;
  42451. node.value = unescaped;
  42452. node.quoteMark = quoteMark;
  42453. lastAdded = 'value';
  42454. (0, _util.ensureObject)(node, 'raws');
  42455. node.raws.value = content;
  42456. spaceAfterMeaningfulToken = false;
  42457. break;
  42458. case tokens.equals:
  42459. if (!node.attribute) {
  42460. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  42461. }
  42462. if (node.value) {
  42463. return this.error('Unexpected "=" found; an operator was already defined.', {
  42464. index: token[_tokenize.FIELDS.START_POS]
  42465. });
  42466. }
  42467. node.operator = node.operator ? node.operator + content : content;
  42468. lastAdded = 'operator';
  42469. spaceAfterMeaningfulToken = false;
  42470. break;
  42471. case tokens.comment:
  42472. if (lastAdded) {
  42473. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  42474. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  42475. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  42476. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  42477. node.raws.spaces[lastAdded].after = rawLastComment + content;
  42478. } else {
  42479. var lastValue = node[lastAdded] || '';
  42480. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  42481. (0, _util.ensureObject)(node, 'raws');
  42482. node.raws[lastAdded] = rawLastValue + content;
  42483. }
  42484. } else {
  42485. commentBefore = commentBefore + content;
  42486. }
  42487. break;
  42488. default:
  42489. return this.error("Unexpected \"" + content + "\" found.", {
  42490. index: token[_tokenize.FIELDS.START_POS]
  42491. });
  42492. }
  42493. pos++;
  42494. }
  42495. unescapeProp(node, "attribute");
  42496. unescapeProp(node, "namespace");
  42497. this.newNode(new _attribute["default"](node));
  42498. this.position++;
  42499. }
  42500. /**
  42501. * return a node containing meaningless garbage up to (but not including) the specified token position.
  42502. * if the token position is negative, all remaining tokens are consumed.
  42503. *
  42504. * This returns an array containing a single string node if all whitespace,
  42505. * otherwise an array of comment nodes with space before and after.
  42506. *
  42507. * These tokens are not added to the current selector, the caller can add them or use them to amend
  42508. * a previous node's space metadata.
  42509. *
  42510. * In lossy mode, this returns only comments.
  42511. */
  42512. ;
  42513. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  42514. if (stopPosition < 0) {
  42515. stopPosition = this.tokens.length;
  42516. }
  42517. var startPosition = this.position;
  42518. var nodes = [];
  42519. var space = "";
  42520. var lastComment = undefined;
  42521. do {
  42522. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  42523. if (!this.options.lossy) {
  42524. space += this.content();
  42525. }
  42526. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  42527. var spaces = {};
  42528. if (space) {
  42529. spaces.before = space;
  42530. space = "";
  42531. }
  42532. lastComment = new _comment["default"]({
  42533. value: this.content(),
  42534. source: getTokenSource(this.currToken),
  42535. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  42536. spaces: spaces
  42537. });
  42538. nodes.push(lastComment);
  42539. }
  42540. } while (++this.position < stopPosition);
  42541. if (space) {
  42542. if (lastComment) {
  42543. lastComment.spaces.after = space;
  42544. } else if (!this.options.lossy) {
  42545. var firstToken = this.tokens[startPosition];
  42546. var lastToken = this.tokens[this.position - 1];
  42547. nodes.push(new _string["default"]({
  42548. value: '',
  42549. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  42550. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  42551. spaces: {
  42552. before: space,
  42553. after: ''
  42554. }
  42555. }));
  42556. }
  42557. }
  42558. return nodes;
  42559. }
  42560. /**
  42561. *
  42562. * @param {*} nodes
  42563. */
  42564. ;
  42565. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  42566. var _this2 = this;
  42567. if (requiredSpace === void 0) {
  42568. requiredSpace = false;
  42569. }
  42570. var space = "";
  42571. var rawSpace = "";
  42572. nodes.forEach(function (n) {
  42573. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  42574. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  42575. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  42576. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  42577. });
  42578. if (rawSpace === space) {
  42579. rawSpace = undefined;
  42580. }
  42581. var result = {
  42582. space: space,
  42583. rawSpace: rawSpace
  42584. };
  42585. return result;
  42586. };
  42587. _proto.isNamedCombinator = function isNamedCombinator(position) {
  42588. if (position === void 0) {
  42589. position = this.position;
  42590. }
  42591. return this.tokens[position + 0] && this.tokens[position + 0][_tokenize.FIELDS.TYPE] === tokens.slash && this.tokens[position + 1] && this.tokens[position + 1][_tokenize.FIELDS.TYPE] === tokens.word && this.tokens[position + 2] && this.tokens[position + 2][_tokenize.FIELDS.TYPE] === tokens.slash;
  42592. };
  42593. _proto.namedCombinator = function namedCombinator() {
  42594. if (this.isNamedCombinator()) {
  42595. var nameRaw = this.content(this.tokens[this.position + 1]);
  42596. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  42597. var raws = {};
  42598. if (name !== nameRaw) {
  42599. raws.value = "/" + nameRaw + "/";
  42600. }
  42601. var node = new _combinator["default"]({
  42602. value: "/" + name + "/",
  42603. source: getSource(this.currToken[_tokenize.FIELDS.START_LINE], this.currToken[_tokenize.FIELDS.START_COL], this.tokens[this.position + 2][_tokenize.FIELDS.END_LINE], this.tokens[this.position + 2][_tokenize.FIELDS.END_COL]),
  42604. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  42605. raws: raws
  42606. });
  42607. this.position = this.position + 3;
  42608. return node;
  42609. } else {
  42610. this.unexpected();
  42611. }
  42612. };
  42613. _proto.combinator = function combinator() {
  42614. var _this3 = this;
  42615. if (this.content() === '|') {
  42616. return this.namespace();
  42617. } // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  42618. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  42619. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma) {
  42620. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  42621. if (nodes.length > 0) {
  42622. var last = this.current.last;
  42623. if (last) {
  42624. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  42625. space = _this$convertWhitespa.space,
  42626. rawSpace = _this$convertWhitespa.rawSpace;
  42627. if (rawSpace !== undefined) {
  42628. last.rawSpaceAfter += rawSpace;
  42629. }
  42630. last.spaces.after += space;
  42631. } else {
  42632. nodes.forEach(function (n) {
  42633. return _this3.newNode(n);
  42634. });
  42635. }
  42636. }
  42637. return;
  42638. }
  42639. var firstToken = this.currToken;
  42640. var spaceOrDescendantSelectorNodes = undefined;
  42641. if (nextSigTokenPos > this.position) {
  42642. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  42643. }
  42644. var node;
  42645. if (this.isNamedCombinator()) {
  42646. node = this.namedCombinator();
  42647. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  42648. node = new _combinator["default"]({
  42649. value: this.content(),
  42650. source: getTokenSource(this.currToken),
  42651. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  42652. });
  42653. this.position++;
  42654. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  42655. this.unexpected();
  42656. }
  42657. if (node) {
  42658. if (spaceOrDescendantSelectorNodes) {
  42659. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  42660. _space = _this$convertWhitespa2.space,
  42661. _rawSpace = _this$convertWhitespa2.rawSpace;
  42662. node.spaces.before = _space;
  42663. node.rawSpaceBefore = _rawSpace;
  42664. }
  42665. } else {
  42666. // descendant combinator
  42667. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  42668. _space2 = _this$convertWhitespa3.space,
  42669. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  42670. if (!_rawSpace2) {
  42671. _rawSpace2 = _space2;
  42672. }
  42673. var spaces = {};
  42674. var raws = {
  42675. spaces: {}
  42676. };
  42677. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  42678. spaces.before = _space2.slice(0, _space2.length - 1);
  42679. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  42680. } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
  42681. spaces.after = _space2.slice(1);
  42682. raws.spaces.after = _rawSpace2.slice(1);
  42683. } else {
  42684. raws.value = _rawSpace2;
  42685. }
  42686. node = new _combinator["default"]({
  42687. value: ' ',
  42688. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  42689. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  42690. spaces: spaces,
  42691. raws: raws
  42692. });
  42693. }
  42694. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  42695. node.spaces.after = this.optionalSpace(this.content());
  42696. this.position++;
  42697. }
  42698. return this.newNode(node);
  42699. };
  42700. _proto.comma = function comma() {
  42701. if (this.position === this.tokens.length - 1) {
  42702. this.root.trailingComma = true;
  42703. this.position++;
  42704. return;
  42705. }
  42706. this.current._inferEndPosition();
  42707. var selector = new _selector["default"]({
  42708. source: {
  42709. start: tokenStart(this.tokens[this.position + 1])
  42710. }
  42711. });
  42712. this.current.parent.append(selector);
  42713. this.current = selector;
  42714. this.position++;
  42715. };
  42716. _proto.comment = function comment() {
  42717. var current = this.currToken;
  42718. this.newNode(new _comment["default"]({
  42719. value: this.content(),
  42720. source: getTokenSource(current),
  42721. sourceIndex: current[_tokenize.FIELDS.START_POS]
  42722. }));
  42723. this.position++;
  42724. };
  42725. _proto.error = function error(message, opts) {
  42726. throw this.root.error(message, opts);
  42727. };
  42728. _proto.missingBackslash = function missingBackslash() {
  42729. return this.error('Expected a backslash preceding the semicolon.', {
  42730. index: this.currToken[_tokenize.FIELDS.START_POS]
  42731. });
  42732. };
  42733. _proto.missingParenthesis = function missingParenthesis() {
  42734. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  42735. };
  42736. _proto.missingSquareBracket = function missingSquareBracket() {
  42737. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  42738. };
  42739. _proto.unexpected = function unexpected() {
  42740. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  42741. };
  42742. _proto.namespace = function namespace() {
  42743. var before = this.prevToken && this.content(this.prevToken) || true;
  42744. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  42745. this.position++;
  42746. return this.word(before);
  42747. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  42748. this.position++;
  42749. return this.universal(before);
  42750. }
  42751. };
  42752. _proto.nesting = function nesting() {
  42753. if (this.nextToken) {
  42754. var nextContent = this.content(this.nextToken);
  42755. if (nextContent === "|") {
  42756. this.position++;
  42757. return;
  42758. }
  42759. }
  42760. var current = this.currToken;
  42761. this.newNode(new _nesting["default"]({
  42762. value: this.content(),
  42763. source: getTokenSource(current),
  42764. sourceIndex: current[_tokenize.FIELDS.START_POS]
  42765. }));
  42766. this.position++;
  42767. };
  42768. _proto.parentheses = function parentheses() {
  42769. var last = this.current.last;
  42770. var unbalanced = 1;
  42771. this.position++;
  42772. if (last && last.type === types$1.PSEUDO) {
  42773. var selector = new _selector["default"]({
  42774. source: {
  42775. start: tokenStart(this.tokens[this.position - 1])
  42776. }
  42777. });
  42778. var cache = this.current;
  42779. last.append(selector);
  42780. this.current = selector;
  42781. while (this.position < this.tokens.length && unbalanced) {
  42782. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  42783. unbalanced++;
  42784. }
  42785. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  42786. unbalanced--;
  42787. }
  42788. if (unbalanced) {
  42789. this.parse();
  42790. } else {
  42791. this.current.source.end = tokenEnd(this.currToken);
  42792. this.current.parent.source.end = tokenEnd(this.currToken);
  42793. this.position++;
  42794. }
  42795. }
  42796. this.current = cache;
  42797. } else {
  42798. // I think this case should be an error. It's used to implement a basic parse of media queries
  42799. // but I don't think it's a good idea.
  42800. var parenStart = this.currToken;
  42801. var parenValue = "(";
  42802. var parenEnd;
  42803. while (this.position < this.tokens.length && unbalanced) {
  42804. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  42805. unbalanced++;
  42806. }
  42807. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  42808. unbalanced--;
  42809. }
  42810. parenEnd = this.currToken;
  42811. parenValue += this.parseParenthesisToken(this.currToken);
  42812. this.position++;
  42813. }
  42814. if (last) {
  42815. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  42816. } else {
  42817. this.newNode(new _string["default"]({
  42818. value: parenValue,
  42819. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  42820. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  42821. }));
  42822. }
  42823. }
  42824. if (unbalanced) {
  42825. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  42826. }
  42827. };
  42828. _proto.pseudo = function pseudo() {
  42829. var _this4 = this;
  42830. var pseudoStr = '';
  42831. var startingToken = this.currToken;
  42832. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  42833. pseudoStr += this.content();
  42834. this.position++;
  42835. }
  42836. if (!this.currToken) {
  42837. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  42838. }
  42839. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  42840. this.splitWord(false, function (first, length) {
  42841. pseudoStr += first;
  42842. _this4.newNode(new _pseudo["default"]({
  42843. value: pseudoStr,
  42844. source: getTokenSourceSpan(startingToken, _this4.currToken),
  42845. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  42846. }));
  42847. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  42848. _this4.error('Misplaced parenthesis.', {
  42849. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  42850. });
  42851. }
  42852. });
  42853. } else {
  42854. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  42855. }
  42856. };
  42857. _proto.space = function space() {
  42858. var content = this.content(); // Handle space before and after the selector
  42859. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  42860. return node.type === 'comment';
  42861. })) {
  42862. this.spaces = this.optionalSpace(content);
  42863. this.position++;
  42864. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  42865. this.current.last.spaces.after = this.optionalSpace(content);
  42866. this.position++;
  42867. } else {
  42868. this.combinator();
  42869. }
  42870. };
  42871. _proto.string = function string() {
  42872. var current = this.currToken;
  42873. this.newNode(new _string["default"]({
  42874. value: this.content(),
  42875. source: getTokenSource(current),
  42876. sourceIndex: current[_tokenize.FIELDS.START_POS]
  42877. }));
  42878. this.position++;
  42879. };
  42880. _proto.universal = function universal(namespace) {
  42881. var nextToken = this.nextToken;
  42882. if (nextToken && this.content(nextToken) === '|') {
  42883. this.position++;
  42884. return this.namespace();
  42885. }
  42886. var current = this.currToken;
  42887. this.newNode(new _universal["default"]({
  42888. value: this.content(),
  42889. source: getTokenSource(current),
  42890. sourceIndex: current[_tokenize.FIELDS.START_POS]
  42891. }), namespace);
  42892. this.position++;
  42893. };
  42894. _proto.splitWord = function splitWord(namespace, firstCallback) {
  42895. var _this5 = this;
  42896. var nextToken = this.nextToken;
  42897. var word = this.content();
  42898. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  42899. this.position++;
  42900. var current = this.content();
  42901. word += current;
  42902. if (current.lastIndexOf('\\') === current.length - 1) {
  42903. var next = this.nextToken;
  42904. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  42905. word += this.requiredSpace(this.content(next));
  42906. this.position++;
  42907. }
  42908. }
  42909. nextToken = this.nextToken;
  42910. }
  42911. var hasClass = indexesOf(word, '.').filter(function (i) {
  42912. // Allow escaped dot within class name
  42913. var escapedDot = word[i - 1] === '\\'; // Allow decimal numbers percent in @keyframes
  42914. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  42915. return !escapedDot && !isKeyframesPercent;
  42916. });
  42917. var hasId = indexesOf(word, '#').filter(function (i) {
  42918. return word[i - 1] !== '\\';
  42919. }); // Eliminate Sass interpolations from the list of id indexes
  42920. var interpolations = indexesOf(word, '#{');
  42921. if (interpolations.length) {
  42922. hasId = hasId.filter(function (hashIndex) {
  42923. return !~interpolations.indexOf(hashIndex);
  42924. });
  42925. }
  42926. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  42927. indices.forEach(function (ind, i) {
  42928. var index = indices[i + 1] || word.length;
  42929. var value = word.slice(ind, index);
  42930. if (i === 0 && firstCallback) {
  42931. return firstCallback.call(_this5, value, indices.length);
  42932. }
  42933. var node;
  42934. var current = _this5.currToken;
  42935. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  42936. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  42937. if (~hasClass.indexOf(ind)) {
  42938. var classNameOpts = {
  42939. value: value.slice(1),
  42940. source: source,
  42941. sourceIndex: sourceIndex
  42942. };
  42943. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  42944. } else if (~hasId.indexOf(ind)) {
  42945. var idOpts = {
  42946. value: value.slice(1),
  42947. source: source,
  42948. sourceIndex: sourceIndex
  42949. };
  42950. node = new _id["default"](unescapeProp(idOpts, "value"));
  42951. } else {
  42952. var tagOpts = {
  42953. value: value,
  42954. source: source,
  42955. sourceIndex: sourceIndex
  42956. };
  42957. unescapeProp(tagOpts, "value");
  42958. node = new _tag["default"](tagOpts);
  42959. }
  42960. _this5.newNode(node, namespace); // Ensure that the namespace is used only once
  42961. namespace = null;
  42962. });
  42963. this.position++;
  42964. };
  42965. _proto.word = function word(namespace) {
  42966. var nextToken = this.nextToken;
  42967. if (nextToken && this.content(nextToken) === '|') {
  42968. this.position++;
  42969. return this.namespace();
  42970. }
  42971. return this.splitWord(namespace);
  42972. };
  42973. _proto.loop = function loop() {
  42974. while (this.position < this.tokens.length) {
  42975. this.parse(true);
  42976. }
  42977. this.current._inferEndPosition();
  42978. return this.root;
  42979. };
  42980. _proto.parse = function parse(throwOnParenthesis) {
  42981. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  42982. case tokens.space:
  42983. this.space();
  42984. break;
  42985. case tokens.comment:
  42986. this.comment();
  42987. break;
  42988. case tokens.openParenthesis:
  42989. this.parentheses();
  42990. break;
  42991. case tokens.closeParenthesis:
  42992. if (throwOnParenthesis) {
  42993. this.missingParenthesis();
  42994. }
  42995. break;
  42996. case tokens.openSquare:
  42997. this.attribute();
  42998. break;
  42999. case tokens.dollar:
  43000. case tokens.caret:
  43001. case tokens.equals:
  43002. case tokens.word:
  43003. this.word();
  43004. break;
  43005. case tokens.colon:
  43006. this.pseudo();
  43007. break;
  43008. case tokens.comma:
  43009. this.comma();
  43010. break;
  43011. case tokens.asterisk:
  43012. this.universal();
  43013. break;
  43014. case tokens.ampersand:
  43015. this.nesting();
  43016. break;
  43017. case tokens.slash:
  43018. case tokens.combinator:
  43019. this.combinator();
  43020. break;
  43021. case tokens.str:
  43022. this.string();
  43023. break;
  43024. // These cases throw; no break needed.
  43025. case tokens.closeSquare:
  43026. this.missingSquareBracket();
  43027. case tokens.semicolon:
  43028. this.missingBackslash();
  43029. default:
  43030. this.unexpected();
  43031. }
  43032. }
  43033. /**
  43034. * Helpers
  43035. */
  43036. ;
  43037. _proto.expected = function expected(description, index, found) {
  43038. if (Array.isArray(description)) {
  43039. var last = description.pop();
  43040. description = description.join(', ') + " or " + last;
  43041. }
  43042. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  43043. if (!found) {
  43044. return this.error("Expected " + an + " " + description + ".", {
  43045. index: index
  43046. });
  43047. }
  43048. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  43049. index: index
  43050. });
  43051. };
  43052. _proto.requiredSpace = function requiredSpace(space) {
  43053. return this.options.lossy ? ' ' : space;
  43054. };
  43055. _proto.optionalSpace = function optionalSpace(space) {
  43056. return this.options.lossy ? '' : space;
  43057. };
  43058. _proto.lossySpace = function lossySpace(space, required) {
  43059. if (this.options.lossy) {
  43060. return required ? ' ' : '';
  43061. } else {
  43062. return space;
  43063. }
  43064. };
  43065. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  43066. var content = this.content(token);
  43067. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  43068. return this.requiredSpace(content);
  43069. } else {
  43070. return content;
  43071. }
  43072. };
  43073. _proto.newNode = function newNode(node, namespace) {
  43074. if (namespace) {
  43075. if (/^ +$/.test(namespace)) {
  43076. if (!this.options.lossy) {
  43077. this.spaces = (this.spaces || '') + namespace;
  43078. }
  43079. namespace = true;
  43080. }
  43081. node.namespace = namespace;
  43082. unescapeProp(node, "namespace");
  43083. }
  43084. if (this.spaces) {
  43085. node.spaces.before = this.spaces;
  43086. this.spaces = '';
  43087. }
  43088. return this.current.append(node);
  43089. };
  43090. _proto.content = function content(token) {
  43091. if (token === void 0) {
  43092. token = this.currToken;
  43093. }
  43094. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  43095. };
  43096. /**
  43097. * returns the index of the next non-whitespace, non-comment token.
  43098. * returns -1 if no meaningful token is found.
  43099. */
  43100. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  43101. if (startPosition === void 0) {
  43102. startPosition = this.position + 1;
  43103. }
  43104. var searchPosition = startPosition;
  43105. while (searchPosition < this.tokens.length) {
  43106. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  43107. searchPosition++;
  43108. continue;
  43109. } else {
  43110. return searchPosition;
  43111. }
  43112. }
  43113. return -1;
  43114. };
  43115. _createClass(Parser, [{
  43116. key: "currToken",
  43117. get: function get() {
  43118. return this.tokens[this.position];
  43119. }
  43120. }, {
  43121. key: "nextToken",
  43122. get: function get() {
  43123. return this.tokens[this.position + 1];
  43124. }
  43125. }, {
  43126. key: "prevToken",
  43127. get: function get() {
  43128. return this.tokens[this.position - 1];
  43129. }
  43130. }]);
  43131. return Parser;
  43132. }();
  43133. exports["default"] = Parser;
  43134. module.exports = exports.default;
  43135. } (parser, parser.exports));
  43136. (function (module, exports) {
  43137. exports.__esModule = true;
  43138. exports["default"] = void 0;
  43139. var _parser = _interopRequireDefault(parser.exports);
  43140. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  43141. var Processor = /*#__PURE__*/function () {
  43142. function Processor(func, options) {
  43143. this.func = func || function noop() {};
  43144. this.funcRes = null;
  43145. this.options = options;
  43146. }
  43147. var _proto = Processor.prototype;
  43148. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  43149. if (options === void 0) {
  43150. options = {};
  43151. }
  43152. var merged = Object.assign({}, this.options, options);
  43153. if (merged.updateSelector === false) {
  43154. return false;
  43155. } else {
  43156. return typeof rule !== "string";
  43157. }
  43158. };
  43159. _proto._isLossy = function _isLossy(options) {
  43160. if (options === void 0) {
  43161. options = {};
  43162. }
  43163. var merged = Object.assign({}, this.options, options);
  43164. if (merged.lossless === false) {
  43165. return true;
  43166. } else {
  43167. return false;
  43168. }
  43169. };
  43170. _proto._root = function _root(rule, options) {
  43171. if (options === void 0) {
  43172. options = {};
  43173. }
  43174. var parser = new _parser["default"](rule, this._parseOptions(options));
  43175. return parser.root;
  43176. };
  43177. _proto._parseOptions = function _parseOptions(options) {
  43178. return {
  43179. lossy: this._isLossy(options)
  43180. };
  43181. };
  43182. _proto._run = function _run(rule, options) {
  43183. var _this = this;
  43184. if (options === void 0) {
  43185. options = {};
  43186. }
  43187. return new Promise(function (resolve, reject) {
  43188. try {
  43189. var root = _this._root(rule, options);
  43190. Promise.resolve(_this.func(root)).then(function (transform) {
  43191. var string = undefined;
  43192. if (_this._shouldUpdateSelector(rule, options)) {
  43193. string = root.toString();
  43194. rule.selector = string;
  43195. }
  43196. return {
  43197. transform: transform,
  43198. root: root,
  43199. string: string
  43200. };
  43201. }).then(resolve, reject);
  43202. } catch (e) {
  43203. reject(e);
  43204. return;
  43205. }
  43206. });
  43207. };
  43208. _proto._runSync = function _runSync(rule, options) {
  43209. if (options === void 0) {
  43210. options = {};
  43211. }
  43212. var root = this._root(rule, options);
  43213. var transform = this.func(root);
  43214. if (transform && typeof transform.then === "function") {
  43215. throw new Error("Selector processor returned a promise to a synchronous call.");
  43216. }
  43217. var string = undefined;
  43218. if (options.updateSelector && typeof rule !== "string") {
  43219. string = root.toString();
  43220. rule.selector = string;
  43221. }
  43222. return {
  43223. transform: transform,
  43224. root: root,
  43225. string: string
  43226. };
  43227. }
  43228. /**
  43229. * Process rule into a selector AST.
  43230. *
  43231. * @param rule {postcss.Rule | string} The css selector to be processed
  43232. * @param options The options for processing
  43233. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  43234. */
  43235. ;
  43236. _proto.ast = function ast(rule, options) {
  43237. return this._run(rule, options).then(function (result) {
  43238. return result.root;
  43239. });
  43240. }
  43241. /**
  43242. * Process rule into a selector AST synchronously.
  43243. *
  43244. * @param rule {postcss.Rule | string} The css selector to be processed
  43245. * @param options The options for processing
  43246. * @returns {parser.Root} The AST of the selector after processing it.
  43247. */
  43248. ;
  43249. _proto.astSync = function astSync(rule, options) {
  43250. return this._runSync(rule, options).root;
  43251. }
  43252. /**
  43253. * Process a selector into a transformed value asynchronously
  43254. *
  43255. * @param rule {postcss.Rule | string} The css selector to be processed
  43256. * @param options The options for processing
  43257. * @returns {Promise<any>} The value returned by the processor.
  43258. */
  43259. ;
  43260. _proto.transform = function transform(rule, options) {
  43261. return this._run(rule, options).then(function (result) {
  43262. return result.transform;
  43263. });
  43264. }
  43265. /**
  43266. * Process a selector into a transformed value synchronously.
  43267. *
  43268. * @param rule {postcss.Rule | string} The css selector to be processed
  43269. * @param options The options for processing
  43270. * @returns {any} The value returned by the processor.
  43271. */
  43272. ;
  43273. _proto.transformSync = function transformSync(rule, options) {
  43274. return this._runSync(rule, options).transform;
  43275. }
  43276. /**
  43277. * Process a selector into a new selector string asynchronously.
  43278. *
  43279. * @param rule {postcss.Rule | string} The css selector to be processed
  43280. * @param options The options for processing
  43281. * @returns {string} the selector after processing.
  43282. */
  43283. ;
  43284. _proto.process = function process(rule, options) {
  43285. return this._run(rule, options).then(function (result) {
  43286. return result.string || result.root.toString();
  43287. });
  43288. }
  43289. /**
  43290. * Process a selector into a new selector string synchronously.
  43291. *
  43292. * @param rule {postcss.Rule | string} The css selector to be processed
  43293. * @param options The options for processing
  43294. * @returns {string} the selector after processing.
  43295. */
  43296. ;
  43297. _proto.processSync = function processSync(rule, options) {
  43298. var result = this._runSync(rule, options);
  43299. return result.string || result.root.toString();
  43300. };
  43301. return Processor;
  43302. }();
  43303. exports["default"] = Processor;
  43304. module.exports = exports.default;
  43305. } (processor, processor.exports));
  43306. var selectors = {};
  43307. var constructors = {};
  43308. constructors.__esModule = true;
  43309. constructors.universal = constructors.tag = constructors.string = constructors.selector = constructors.root = constructors.pseudo = constructors.nesting = constructors.id = constructors.comment = constructors.combinator = constructors.className = constructors.attribute = void 0;
  43310. var _attribute = _interopRequireDefault(attribute$1);
  43311. var _className = _interopRequireDefault(className$1.exports);
  43312. var _combinator = _interopRequireDefault(combinator$2.exports);
  43313. var _comment = _interopRequireDefault(comment$2.exports);
  43314. var _id = _interopRequireDefault(id$1.exports);
  43315. var _nesting = _interopRequireDefault(nesting$1.exports);
  43316. var _pseudo = _interopRequireDefault(pseudo$1.exports);
  43317. var _root = _interopRequireDefault(root$1.exports);
  43318. var _selector = _interopRequireDefault(selector$1.exports);
  43319. var _string = _interopRequireDefault(string$1.exports);
  43320. var _tag = _interopRequireDefault(tag$1.exports);
  43321. var _universal = _interopRequireDefault(universal$1.exports);
  43322. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  43323. var attribute = function attribute(opts) {
  43324. return new _attribute["default"](opts);
  43325. };
  43326. constructors.attribute = attribute;
  43327. var className = function className(opts) {
  43328. return new _className["default"](opts);
  43329. };
  43330. constructors.className = className;
  43331. var combinator = function combinator(opts) {
  43332. return new _combinator["default"](opts);
  43333. };
  43334. constructors.combinator = combinator;
  43335. var comment = function comment(opts) {
  43336. return new _comment["default"](opts);
  43337. };
  43338. constructors.comment = comment;
  43339. var id = function id(opts) {
  43340. return new _id["default"](opts);
  43341. };
  43342. constructors.id = id;
  43343. var nesting = function nesting(opts) {
  43344. return new _nesting["default"](opts);
  43345. };
  43346. constructors.nesting = nesting;
  43347. var pseudo = function pseudo(opts) {
  43348. return new _pseudo["default"](opts);
  43349. };
  43350. constructors.pseudo = pseudo;
  43351. var root = function root(opts) {
  43352. return new _root["default"](opts);
  43353. };
  43354. constructors.root = root;
  43355. var selector = function selector(opts) {
  43356. return new _selector["default"](opts);
  43357. };
  43358. constructors.selector = selector;
  43359. var string = function string(opts) {
  43360. return new _string["default"](opts);
  43361. };
  43362. constructors.string = string;
  43363. var tag = function tag(opts) {
  43364. return new _tag["default"](opts);
  43365. };
  43366. constructors.tag = tag;
  43367. var universal = function universal(opts) {
  43368. return new _universal["default"](opts);
  43369. };
  43370. constructors.universal = universal;
  43371. var guards = {};
  43372. guards.__esModule = true;
  43373. guards.isNode = isNode;
  43374. guards.isPseudoElement = isPseudoElement;
  43375. guards.isPseudoClass = isPseudoClass;
  43376. guards.isContainer = isContainer;
  43377. guards.isNamespace = isNamespace;
  43378. guards.isUniversal = guards.isTag = guards.isString = guards.isSelector = guards.isRoot = guards.isPseudo = guards.isNesting = guards.isIdentifier = guards.isComment = guards.isCombinator = guards.isClassName = guards.isAttribute = void 0;
  43379. var _types = types;
  43380. var _IS_TYPE;
  43381. var IS_TYPE = (_IS_TYPE = {}, _IS_TYPE[_types.ATTRIBUTE] = true, _IS_TYPE[_types.CLASS] = true, _IS_TYPE[_types.COMBINATOR] = true, _IS_TYPE[_types.COMMENT] = true, _IS_TYPE[_types.ID] = true, _IS_TYPE[_types.NESTING] = true, _IS_TYPE[_types.PSEUDO] = true, _IS_TYPE[_types.ROOT] = true, _IS_TYPE[_types.SELECTOR] = true, _IS_TYPE[_types.STRING] = true, _IS_TYPE[_types.TAG] = true, _IS_TYPE[_types.UNIVERSAL] = true, _IS_TYPE);
  43382. function isNode(node) {
  43383. return typeof node === "object" && IS_TYPE[node.type];
  43384. }
  43385. function isNodeType(type, node) {
  43386. return isNode(node) && node.type === type;
  43387. }
  43388. var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
  43389. guards.isAttribute = isAttribute;
  43390. var isClassName = isNodeType.bind(null, _types.CLASS);
  43391. guards.isClassName = isClassName;
  43392. var isCombinator = isNodeType.bind(null, _types.COMBINATOR);
  43393. guards.isCombinator = isCombinator;
  43394. var isComment = isNodeType.bind(null, _types.COMMENT);
  43395. guards.isComment = isComment;
  43396. var isIdentifier = isNodeType.bind(null, _types.ID);
  43397. guards.isIdentifier = isIdentifier;
  43398. var isNesting = isNodeType.bind(null, _types.NESTING);
  43399. guards.isNesting = isNesting;
  43400. var isPseudo = isNodeType.bind(null, _types.PSEUDO);
  43401. guards.isPseudo = isPseudo;
  43402. var isRoot = isNodeType.bind(null, _types.ROOT);
  43403. guards.isRoot = isRoot;
  43404. var isSelector = isNodeType.bind(null, _types.SELECTOR);
  43405. guards.isSelector = isSelector;
  43406. var isString = isNodeType.bind(null, _types.STRING);
  43407. guards.isString = isString;
  43408. var isTag = isNodeType.bind(null, _types.TAG);
  43409. guards.isTag = isTag;
  43410. var isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
  43411. guards.isUniversal = isUniversal;
  43412. function isPseudoElement(node) {
  43413. return isPseudo(node) && node.value && (node.value.startsWith("::") || node.value.toLowerCase() === ":before" || node.value.toLowerCase() === ":after");
  43414. }
  43415. function isPseudoClass(node) {
  43416. return isPseudo(node) && !isPseudoElement(node);
  43417. }
  43418. function isContainer(node) {
  43419. return !!(isNode(node) && node.walk);
  43420. }
  43421. function isNamespace(node) {
  43422. return isAttribute(node) || isTag(node);
  43423. }
  43424. (function (exports) {
  43425. exports.__esModule = true;
  43426. var _types = types;
  43427. Object.keys(_types).forEach(function (key) {
  43428. if (key === "default" || key === "__esModule") return;
  43429. if (key in exports && exports[key] === _types[key]) return;
  43430. exports[key] = _types[key];
  43431. });
  43432. var _constructors = constructors;
  43433. Object.keys(_constructors).forEach(function (key) {
  43434. if (key === "default" || key === "__esModule") return;
  43435. if (key in exports && exports[key] === _constructors[key]) return;
  43436. exports[key] = _constructors[key];
  43437. });
  43438. var _guards = guards;
  43439. Object.keys(_guards).forEach(function (key) {
  43440. if (key === "default" || key === "__esModule") return;
  43441. if (key in exports && exports[key] === _guards[key]) return;
  43442. exports[key] = _guards[key];
  43443. });
  43444. } (selectors));
  43445. (function (module, exports) {
  43446. exports.__esModule = true;
  43447. exports["default"] = void 0;
  43448. var _processor = _interopRequireDefault(processor.exports);
  43449. var selectors$1 = _interopRequireWildcard(selectors);
  43450. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  43451. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  43452. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  43453. var parser = function parser(processor) {
  43454. return new _processor["default"](processor);
  43455. };
  43456. Object.assign(parser, selectors$1);
  43457. delete parser.__esModule;
  43458. var _default = parser;
  43459. exports["default"] = _default;
  43460. module.exports = exports.default;
  43461. } (dist, dist.exports));
  43462. var selectorParser = /*@__PURE__*/getDefaultExportFromCjs(dist.exports);
  43463. const animationNameRE = /^(-\w+-)?animation-name$/;
  43464. const animationRE = /^(-\w+-)?animation$/;
  43465. const scopedPlugin = (id = '') => {
  43466. const keyframes = Object.create(null);
  43467. const shortId = id.replace(/^data-v-/, '');
  43468. return {
  43469. postcssPlugin: 'vue-sfc-scoped',
  43470. Rule(rule) {
  43471. processRule(id, rule);
  43472. },
  43473. AtRule(node) {
  43474. if (/-?keyframes$/.test(node.name) &&
  43475. !node.params.endsWith(`-${shortId}`)) {
  43476. // register keyframes
  43477. keyframes[node.params] = node.params = node.params + '-' + shortId;
  43478. }
  43479. },
  43480. OnceExit(root) {
  43481. if (Object.keys(keyframes).length) {
  43482. // If keyframes are found in this <style>, find and rewrite animation names
  43483. // in declarations.
  43484. // Caveat: this only works for keyframes and animation rules in the same
  43485. // <style> element.
  43486. // individual animation-name declaration
  43487. root.walkDecls(decl => {
  43488. if (animationNameRE.test(decl.prop)) {
  43489. decl.value = decl.value
  43490. .split(',')
  43491. .map(v => keyframes[v.trim()] || v.trim())
  43492. .join(',');
  43493. }
  43494. // shorthand
  43495. if (animationRE.test(decl.prop)) {
  43496. decl.value = decl.value
  43497. .split(',')
  43498. .map(v => {
  43499. const vals = v.trim().split(/\s+/);
  43500. const i = vals.findIndex(val => keyframes[val]);
  43501. if (i !== -1) {
  43502. vals.splice(i, 1, keyframes[vals[i]]);
  43503. return vals.join(' ');
  43504. }
  43505. else {
  43506. return v;
  43507. }
  43508. })
  43509. .join(',');
  43510. }
  43511. });
  43512. }
  43513. }
  43514. };
  43515. };
  43516. const processedRules = new WeakSet();
  43517. function processRule(id, rule) {
  43518. if (processedRules.has(rule) ||
  43519. (rule.parent &&
  43520. rule.parent.type === 'atrule' &&
  43521. /-?keyframes$/.test(rule.parent.name))) {
  43522. return;
  43523. }
  43524. processedRules.add(rule);
  43525. rule.selector = selectorParser(selectorRoot => {
  43526. selectorRoot.each(selector => {
  43527. rewriteSelector(id, selector, selectorRoot);
  43528. });
  43529. }).processSync(rule.selector);
  43530. }
  43531. function rewriteSelector(id, selector, selectorRoot, slotted = false) {
  43532. let node = null;
  43533. let shouldInject = true;
  43534. // find the last child node to insert attribute selector
  43535. selector.each(n => {
  43536. // DEPRECATED ">>>" and "/deep/" combinator
  43537. if (n.type === 'combinator' &&
  43538. (n.value === '>>>' || n.value === '/deep/')) {
  43539. n.value = ' ';
  43540. n.spaces.before = n.spaces.after = '';
  43541. warn$1(`the >>> and /deep/ combinators have been deprecated. ` +
  43542. `Use :deep() instead.`);
  43543. return false;
  43544. }
  43545. if (n.type === 'pseudo') {
  43546. const { value } = n;
  43547. // deep: inject [id] attribute at the node before the ::v-deep
  43548. // combinator.
  43549. if (value === ':deep' || value === '::v-deep') {
  43550. if (n.nodes.length) {
  43551. // .foo ::v-deep(.bar) -> .foo[xxxxxxx] .bar
  43552. // replace the current node with ::v-deep's inner selector
  43553. let last = n;
  43554. n.nodes[0].each(ss => {
  43555. selector.insertAfter(last, ss);
  43556. last = ss;
  43557. });
  43558. // insert a space combinator before if it doesn't already have one
  43559. const prev = selector.at(selector.index(n) - 1);
  43560. if (!prev || !isSpaceCombinator(prev)) {
  43561. selector.insertAfter(n, selectorParser.combinator({
  43562. value: ' '
  43563. }));
  43564. }
  43565. selector.removeChild(n);
  43566. }
  43567. else {
  43568. // DEPRECATED usage
  43569. // .foo ::v-deep .bar -> .foo[xxxxxxx] .bar
  43570. warn$1(`::v-deep usage as a combinator has ` +
  43571. `been deprecated. Use :deep(<inner-selector>) instead.`);
  43572. const prev = selector.at(selector.index(n) - 1);
  43573. if (prev && isSpaceCombinator(prev)) {
  43574. selector.removeChild(prev);
  43575. }
  43576. selector.removeChild(n);
  43577. }
  43578. return false;
  43579. }
  43580. // slot: use selector inside `::v-slotted` and inject [id + '-s']
  43581. // instead.
  43582. // ::v-slotted(.foo) -> .foo[xxxxxxx-s]
  43583. if (value === ':slotted' || value === '::v-slotted') {
  43584. rewriteSelector(id, n.nodes[0], selectorRoot, true /* slotted */);
  43585. let last = n;
  43586. n.nodes[0].each(ss => {
  43587. selector.insertAfter(last, ss);
  43588. last = ss;
  43589. });
  43590. // selector.insertAfter(n, n.nodes[0])
  43591. selector.removeChild(n);
  43592. // since slotted attribute already scopes the selector there's no
  43593. // need for the non-slot attribute.
  43594. shouldInject = false;
  43595. return false;
  43596. }
  43597. // global: replace with inner selector and do not inject [id].
  43598. // ::v-global(.foo) -> .foo
  43599. if (value === ':global' || value === '::v-global') {
  43600. selectorRoot.insertAfter(selector, n.nodes[0]);
  43601. selectorRoot.removeChild(selector);
  43602. return false;
  43603. }
  43604. }
  43605. if (n.type !== 'pseudo' && n.type !== 'combinator') {
  43606. node = n;
  43607. }
  43608. });
  43609. if (node) {
  43610. node.spaces.after = '';
  43611. }
  43612. else {
  43613. // For deep selectors & standalone pseudo selectors,
  43614. // the attribute selectors are prepended rather than appended.
  43615. // So all leading spaces must be eliminated to avoid problems.
  43616. selector.first.spaces.before = '';
  43617. }
  43618. if (shouldInject) {
  43619. const idToAdd = slotted ? id + '-s' : id;
  43620. selector.insertAfter(
  43621. // If node is null it means we need to inject [id] at the start
  43622. // insertAfter can handle `null` here
  43623. node, selectorParser.attribute({
  43624. attribute: idToAdd,
  43625. value: idToAdd,
  43626. raws: {},
  43627. quoteMark: `"`
  43628. }));
  43629. }
  43630. }
  43631. function isSpaceCombinator(node) {
  43632. return node.type === 'combinator' && /^\s+$/.test(node.value);
  43633. }
  43634. scopedPlugin.postcss = true;
  43635. var scopedPlugin$1 = scopedPlugin;
  43636. var sourceMap = sourceMap$2;
  43637. var SourceMapConsumer = sourceMap.SourceMapConsumer;
  43638. var SourceMapGenerator = sourceMap.SourceMapGenerator;
  43639. var mergeSourceMap = merge;
  43640. /**
  43641. * Merge old source map and new source map and return merged.
  43642. * If old or new source map value is falsy, return another one as it is.
  43643. *
  43644. * @param {object|string} [oldMap] old source map object
  43645. * @param {object|string} [newmap] new source map object
  43646. * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
  43647. */
  43648. function merge(oldMap, newMap) {
  43649. if (!oldMap) return newMap
  43650. if (!newMap) return oldMap
  43651. var oldMapConsumer = new SourceMapConsumer(oldMap);
  43652. var newMapConsumer = new SourceMapConsumer(newMap);
  43653. var mergedMapGenerator = new SourceMapGenerator();
  43654. // iterate on new map and overwrite original position of new map with one of old map
  43655. newMapConsumer.eachMapping(function(m) {
  43656. // pass when `originalLine` is null.
  43657. // It occurs in case that the node does not have origin in original code.
  43658. if (m.originalLine == null) return
  43659. var origPosInOldMap = oldMapConsumer.originalPositionFor({
  43660. line: m.originalLine,
  43661. column: m.originalColumn
  43662. });
  43663. if (origPosInOldMap.source == null) return
  43664. mergedMapGenerator.addMapping({
  43665. original: {
  43666. line: origPosInOldMap.line,
  43667. column: origPosInOldMap.column
  43668. },
  43669. generated: {
  43670. line: m.generatedLine,
  43671. column: m.generatedColumn
  43672. },
  43673. source: origPosInOldMap.source,
  43674. name: origPosInOldMap.name
  43675. });
  43676. });
  43677. var consumers = [oldMapConsumer, newMapConsumer];
  43678. consumers.forEach(function(consumer) {
  43679. consumer.sources.forEach(function(sourceFile) {
  43680. mergedMapGenerator._sources.add(sourceFile);
  43681. var sourceContent = consumer.sourceContentFor(sourceFile);
  43682. if (sourceContent != null) {
  43683. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  43684. }
  43685. });
  43686. });
  43687. mergedMapGenerator._sourceRoot = oldMap.sourceRoot;
  43688. mergedMapGenerator._file = oldMap.file;
  43689. return JSON.parse(mergedMapGenerator.toString())
  43690. }
  43691. var merge$1 = mergeSourceMap;
  43692. // .scss/.sass processor
  43693. const scss = (source, map, options, load = require) => {
  43694. const nodeSass = load('sass');
  43695. const finalOptions = Object.assign(Object.assign({}, options), { data: getSource(source, options.filename, options.additionalData), file: options.filename, outFile: options.filename, sourceMap: !!map });
  43696. try {
  43697. const result = nodeSass.renderSync(finalOptions);
  43698. const dependencies = result.stats.includedFiles;
  43699. if (map) {
  43700. return {
  43701. code: result.css.toString(),
  43702. map: merge$1(map, JSON.parse(result.map.toString())),
  43703. errors: [],
  43704. dependencies
  43705. };
  43706. }
  43707. return { code: result.css.toString(), errors: [], dependencies };
  43708. }
  43709. catch (e) {
  43710. return { code: '', errors: [e], dependencies: [] };
  43711. }
  43712. };
  43713. const sass = (source, map, options, load) => scss(source, map, Object.assign(Object.assign({}, options), { indentedSyntax: true }), load);
  43714. // .less
  43715. const less = (source, map, options, load = require) => {
  43716. const nodeLess = load('less');
  43717. let result;
  43718. let error = null;
  43719. nodeLess.render(getSource(source, options.filename, options.additionalData), Object.assign(Object.assign({}, options), { syncImport: true }), (err, output) => {
  43720. error = err;
  43721. result = output;
  43722. });
  43723. if (error)
  43724. return { code: '', errors: [error], dependencies: [] };
  43725. const dependencies = result.imports;
  43726. if (map) {
  43727. return {
  43728. code: result.css.toString(),
  43729. map: merge$1(map, result.map),
  43730. errors: [],
  43731. dependencies: dependencies
  43732. };
  43733. }
  43734. return {
  43735. code: result.css.toString(),
  43736. errors: [],
  43737. dependencies: dependencies
  43738. };
  43739. };
  43740. // .styl
  43741. const styl = (source, map, options, load = require) => {
  43742. const nodeStylus = load('stylus');
  43743. try {
  43744. const ref = nodeStylus(source);
  43745. Object.keys(options).forEach(key => ref.set(key, options[key]));
  43746. if (map)
  43747. ref.set('sourcemap', { inline: false, comment: false });
  43748. const result = ref.render();
  43749. const dependencies = ref.deps();
  43750. if (map) {
  43751. return {
  43752. code: result,
  43753. map: merge$1(map, ref.sourcemap),
  43754. errors: [],
  43755. dependencies
  43756. };
  43757. }
  43758. return { code: result, errors: [], dependencies };
  43759. }
  43760. catch (e) {
  43761. return { code: '', errors: [e], dependencies: [] };
  43762. }
  43763. };
  43764. function getSource(source, filename, additionalData) {
  43765. if (!additionalData)
  43766. return source;
  43767. if (isFunction$1(additionalData)) {
  43768. return additionalData(source, filename);
  43769. }
  43770. return additionalData + source;
  43771. }
  43772. const processors = {
  43773. less,
  43774. sass,
  43775. scss,
  43776. styl,
  43777. stylus: styl
  43778. };
  43779. function compileStyle(options) {
  43780. return doCompileStyle(Object.assign(Object.assign({}, options), { isAsync: false }));
  43781. }
  43782. function compileStyleAsync(options) {
  43783. return doCompileStyle(Object.assign(Object.assign({}, options), { isAsync: true }));
  43784. }
  43785. function doCompileStyle(options) {
  43786. const { filename, id, scoped = false, trim = true, isProd = false, modules = false, modulesOptions = {}, preprocessLang, postcssOptions, postcssPlugins } = options;
  43787. const preprocessor = preprocessLang && processors[preprocessLang];
  43788. const preProcessedSource = preprocessor && preprocess(options, preprocessor);
  43789. const map = preProcessedSource
  43790. ? preProcessedSource.map
  43791. : options.inMap || options.map;
  43792. const source = preProcessedSource ? preProcessedSource.code : options.source;
  43793. const shortId = id.replace(/^data-v-/, '');
  43794. const longId = `data-v-${shortId}`;
  43795. const plugins = (postcssPlugins || []).slice();
  43796. plugins.unshift(cssVarsPlugin({ id: shortId, isProd }));
  43797. if (trim) {
  43798. plugins.push(trimPlugin$1());
  43799. }
  43800. if (scoped) {
  43801. plugins.push(scopedPlugin$1(longId));
  43802. }
  43803. let cssModules;
  43804. if (modules) {
  43805. {
  43806. throw new Error('[@vue/compiler-sfc] `modules` option is not supported in the browser build.');
  43807. }
  43808. }
  43809. const postCSSOptions = Object.assign(Object.assign({}, postcssOptions), { to: filename, from: filename });
  43810. if (map) {
  43811. postCSSOptions.map = {
  43812. inline: false,
  43813. annotation: false,
  43814. prev: map
  43815. };
  43816. }
  43817. let result;
  43818. let code;
  43819. let outMap;
  43820. // stylus output include plain css. so need remove the repeat item
  43821. const dependencies = new Set(preProcessedSource ? preProcessedSource.dependencies : []);
  43822. // sass has filename self when provided filename option
  43823. dependencies.delete(filename);
  43824. const errors = [];
  43825. if (preProcessedSource && preProcessedSource.errors.length) {
  43826. errors.push(...preProcessedSource.errors);
  43827. }
  43828. const recordPlainCssDependencies = (messages) => {
  43829. messages.forEach(msg => {
  43830. if (msg.type === 'dependency') {
  43831. // postcss output path is absolute position path
  43832. dependencies.add(msg.file);
  43833. }
  43834. });
  43835. return dependencies;
  43836. };
  43837. try {
  43838. result = postcss$1(plugins).process(source, postCSSOptions);
  43839. // In async mode, return a promise.
  43840. if (options.isAsync) {
  43841. return result
  43842. .then(result => ({
  43843. code: result.css || '',
  43844. map: result.map && result.map.toJSON(),
  43845. errors,
  43846. modules: cssModules,
  43847. rawResult: result,
  43848. dependencies: recordPlainCssDependencies(result.messages)
  43849. }))
  43850. .catch(error => ({
  43851. code: '',
  43852. map: undefined,
  43853. errors: [...errors, error],
  43854. rawResult: undefined,
  43855. dependencies
  43856. }));
  43857. }
  43858. recordPlainCssDependencies(result.messages);
  43859. // force synchronous transform (we know we only have sync plugins)
  43860. code = result.css;
  43861. outMap = result.map;
  43862. }
  43863. catch (e) {
  43864. errors.push(e);
  43865. }
  43866. return {
  43867. code: code || ``,
  43868. map: outMap && outMap.toJSON(),
  43869. errors,
  43870. rawResult: result,
  43871. dependencies
  43872. };
  43873. }
  43874. function preprocess(options, preprocessor) {
  43875. if (!options.preprocessCustomRequire) {
  43876. throw new Error(`[@vue/compiler-sfc] Style preprocessing in the browser build must ` +
  43877. `provide the \`preprocessCustomRequire\` option to return the in-browser ` +
  43878. `version of the preprocessor.`);
  43879. }
  43880. return preprocessor(options.source, options.inMap || options.map, Object.assign({ filename: options.filename }, options.preprocessOptions), options.preprocessCustomRequire);
  43881. }
  43882. // API
  43883. const walk = walk$1;
  43884. export { MagicString$1 as MagicString, parse_1$1 as babelParse, compileScript, compileStyle, compileStyleAsync, compileTemplate, extractIdentifiers, generateCodeFrame, isInDestructureAssignment, isStaticProperty, parse$5 as parse, rewriteDefault, shouldTransform as shouldTransformRef, transform as transformRef, transformAST as transformRefAST, walk, walkIdentifiers };