compiler-sfc.esm-browser.js 1.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602
  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(value)) {
  92. const res = {};
  93. for (let i = 0; i < value.length; i++) {
  94. const item = value[i];
  95. const normalized = isString(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(value)) {
  107. return value;
  108. }
  109. else if (isObject(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(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(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(value)) {
  147. res = value;
  148. }
  149. else if (isArray(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(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,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. 'feDistanceLight,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(val)
  349. ? val
  350. : val == null
  351. ? ''
  352. : isArray(val) ||
  353. (isObject(val) &&
  354. (val.toString === objectToString || !isFunction(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(val) && !isArray(val) && !isPlainObject(val)) {
  377. return String(val);
  378. }
  379. return val;
  380. };
  381. const EMPTY_OBJ = Object.freeze({})
  382. ;
  383. Object.freeze([]) ;
  384. const NOOP = () => { };
  385. /**
  386. * Always return false.
  387. */
  388. const NO = () => false;
  389. const onRE = /^on[^a-z]/;
  390. const isOn = (key) => onRE.test(key);
  391. const extend = Object.assign;
  392. const hasOwnProperty = Object.prototype.hasOwnProperty;
  393. const hasOwn = (val, key) => hasOwnProperty.call(val, key);
  394. const isArray = Array.isArray;
  395. const isMap = (val) => toTypeString(val) === '[object Map]';
  396. const isSet = (val) => toTypeString(val) === '[object Set]';
  397. const isFunction = (val) => typeof val === 'function';
  398. const isString = (val) => typeof val === 'string';
  399. const isSymbol = (val) => typeof val === 'symbol';
  400. const isObject = (val) => val !== null && typeof val === 'object';
  401. const objectToString = Object.prototype.toString;
  402. const toTypeString = (value) => objectToString.call(value);
  403. const isPlainObject = (val) => toTypeString(val) === '[object Object]';
  404. const isReservedProp = /*#__PURE__*/ makeMap(
  405. // the leading comma is intentional so empty string "" is also included
  406. ',key,ref,ref_for,ref_key,' +
  407. 'onVnodeBeforeMount,onVnodeMounted,' +
  408. 'onVnodeBeforeUpdate,onVnodeUpdated,' +
  409. 'onVnodeBeforeUnmount,onVnodeUnmounted');
  410. const isBuiltInDirective = /*#__PURE__*/ makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo');
  411. const cacheStringFunction = (fn) => {
  412. const cache = Object.create(null);
  413. return ((str) => {
  414. const hit = cache[str];
  415. return hit || (cache[str] = fn(str));
  416. });
  417. };
  418. const camelizeRE = /-(\w)/g;
  419. /**
  420. * @private
  421. */
  422. const camelize = cacheStringFunction((str) => {
  423. return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
  424. });
  425. const hyphenateRE = /\B([A-Z])/g;
  426. /**
  427. * @private
  428. */
  429. const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
  430. /**
  431. * @private
  432. */
  433. const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
  434. /**
  435. * @private
  436. */
  437. const toHandlerKey = cacheStringFunction((str) => str ? `on${capitalize(str)}` : ``);
  438. const identRE = /^[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/;
  439. function genPropsAccessExp(name) {
  440. return identRE.test(name)
  441. ? `__props.${name}`
  442. : `__props[${JSON.stringify(name)}]`;
  443. }
  444. function defaultOnError(error) {
  445. throw error;
  446. }
  447. function defaultOnWarn(msg) {
  448. console.warn(`[Vue warn] ${msg.message}`);
  449. }
  450. function createCompilerError(code, loc, messages, additionalMessage) {
  451. const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
  452. ;
  453. const error = new SyntaxError(String(msg));
  454. error.code = code;
  455. error.loc = loc;
  456. return error;
  457. }
  458. const errorMessages = {
  459. // parse errors
  460. [0 /* ErrorCodes.ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
  461. [1 /* ErrorCodes.CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
  462. [2 /* ErrorCodes.DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
  463. [3 /* ErrorCodes.END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
  464. [4 /* ErrorCodes.END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
  465. [5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
  466. [6 /* ErrorCodes.EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
  467. [7 /* ErrorCodes.EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
  468. [8 /* ErrorCodes.EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
  469. [9 /* ErrorCodes.EOF_IN_TAG */]: 'Unexpected EOF in tag.',
  470. [10 /* ErrorCodes.INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
  471. [11 /* ErrorCodes.INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
  472. [12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
  473. [13 /* ErrorCodes.MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
  474. [14 /* ErrorCodes.MISSING_END_TAG_NAME */]: 'End tag name was expected.',
  475. [15 /* ErrorCodes.MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
  476. [16 /* ErrorCodes.NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
  477. [17 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
  478. [18 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
  479. [19 /* ErrorCodes.UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
  480. [21 /* ErrorCodes.UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
  481. [20 /* ErrorCodes.UNEXPECTED_NULL_CHARACTER */]: `Unexpected null character.`,
  482. [22 /* ErrorCodes.UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
  483. // Vue-specific parse errors
  484. [23 /* ErrorCodes.X_INVALID_END_TAG */]: 'Invalid end tag.',
  485. [24 /* ErrorCodes.X_MISSING_END_TAG */]: 'Element is missing end tag.',
  486. [25 /* ErrorCodes.X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
  487. [27 /* ErrorCodes.X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
  488. 'Note that dynamic directive argument cannot contain spaces.',
  489. [26 /* ErrorCodes.X_MISSING_DIRECTIVE_NAME */]: 'Legal directive name was expected.',
  490. // transform errors
  491. [28 /* ErrorCodes.X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
  492. [29 /* ErrorCodes.X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
  493. [30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if or v-else-if.`,
  494. [31 /* ErrorCodes.X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
  495. [32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
  496. [33 /* ErrorCodes.X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
  497. [34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
  498. [35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
  499. [36 /* ErrorCodes.X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
  500. [37 /* ErrorCodes.X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
  501. `When there are multiple named slots, all slots should use <template> ` +
  502. `syntax to avoid scope ambiguity.`,
  503. [38 /* ErrorCodes.X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
  504. [39 /* ErrorCodes.X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
  505. `default slot. These children will be ignored.`,
  506. [40 /* ErrorCodes.X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
  507. [41 /* ErrorCodes.X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
  508. [42 /* ErrorCodes.X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
  509. [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.`,
  510. [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.`,
  511. [45 /* ErrorCodes.X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
  512. [46 /* ErrorCodes.X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
  513. // generic errors
  514. [47 /* ErrorCodes.X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
  515. [48 /* ErrorCodes.X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
  516. [49 /* ErrorCodes.X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
  517. [50 /* ErrorCodes.X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`,
  518. // just to fulfill types
  519. [51 /* ErrorCodes.__EXTEND_POINT__ */]: ``
  520. };
  521. const FRAGMENT = Symbol(`Fragment` );
  522. const TELEPORT = Symbol(`Teleport` );
  523. const SUSPENSE = Symbol(`Suspense` );
  524. const KEEP_ALIVE = Symbol(`KeepAlive` );
  525. const BASE_TRANSITION = Symbol(`BaseTransition` );
  526. const OPEN_BLOCK = Symbol(`openBlock` );
  527. const CREATE_BLOCK = Symbol(`createBlock` );
  528. const CREATE_ELEMENT_BLOCK = Symbol(`createElementBlock` );
  529. const CREATE_VNODE = Symbol(`createVNode` );
  530. const CREATE_ELEMENT_VNODE = Symbol(`createElementVNode` );
  531. const CREATE_COMMENT = Symbol(`createCommentVNode` );
  532. const CREATE_TEXT = Symbol(`createTextVNode` );
  533. const CREATE_STATIC = Symbol(`createStaticVNode` );
  534. const RESOLVE_COMPONENT = Symbol(`resolveComponent` );
  535. const RESOLVE_DYNAMIC_COMPONENT = Symbol(`resolveDynamicComponent` );
  536. const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` );
  537. const RESOLVE_FILTER = Symbol(`resolveFilter` );
  538. const WITH_DIRECTIVES = Symbol(`withDirectives` );
  539. const RENDER_LIST = Symbol(`renderList` );
  540. const RENDER_SLOT = Symbol(`renderSlot` );
  541. const CREATE_SLOTS = Symbol(`createSlots` );
  542. const TO_DISPLAY_STRING = Symbol(`toDisplayString` );
  543. const MERGE_PROPS = Symbol(`mergeProps` );
  544. const NORMALIZE_CLASS = Symbol(`normalizeClass` );
  545. const NORMALIZE_STYLE = Symbol(`normalizeStyle` );
  546. const NORMALIZE_PROPS = Symbol(`normalizeProps` );
  547. const GUARD_REACTIVE_PROPS = Symbol(`guardReactiveProps` );
  548. const TO_HANDLERS = Symbol(`toHandlers` );
  549. const CAMELIZE = Symbol(`camelize` );
  550. const CAPITALIZE = Symbol(`capitalize` );
  551. const TO_HANDLER_KEY = Symbol(`toHandlerKey` );
  552. const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` );
  553. const PUSH_SCOPE_ID = Symbol(`pushScopeId` );
  554. const POP_SCOPE_ID = Symbol(`popScopeId` );
  555. const WITH_CTX = Symbol(`withCtx` );
  556. const UNREF = Symbol(`unref` );
  557. const IS_REF = Symbol(`isRef` );
  558. const WITH_MEMO = Symbol(`withMemo` );
  559. const IS_MEMO_SAME = Symbol(`isMemoSame` );
  560. // Name mapping for runtime helpers that need to be imported from 'vue' in
  561. // generated code. Make sure these are correctly exported in the runtime!
  562. const helperNameMap = {
  563. [FRAGMENT]: `Fragment`,
  564. [TELEPORT]: `Teleport`,
  565. [SUSPENSE]: `Suspense`,
  566. [KEEP_ALIVE]: `KeepAlive`,
  567. [BASE_TRANSITION]: `BaseTransition`,
  568. [OPEN_BLOCK]: `openBlock`,
  569. [CREATE_BLOCK]: `createBlock`,
  570. [CREATE_ELEMENT_BLOCK]: `createElementBlock`,
  571. [CREATE_VNODE]: `createVNode`,
  572. [CREATE_ELEMENT_VNODE]: `createElementVNode`,
  573. [CREATE_COMMENT]: `createCommentVNode`,
  574. [CREATE_TEXT]: `createTextVNode`,
  575. [CREATE_STATIC]: `createStaticVNode`,
  576. [RESOLVE_COMPONENT]: `resolveComponent`,
  577. [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
  578. [RESOLVE_DIRECTIVE]: `resolveDirective`,
  579. [RESOLVE_FILTER]: `resolveFilter`,
  580. [WITH_DIRECTIVES]: `withDirectives`,
  581. [RENDER_LIST]: `renderList`,
  582. [RENDER_SLOT]: `renderSlot`,
  583. [CREATE_SLOTS]: `createSlots`,
  584. [TO_DISPLAY_STRING]: `toDisplayString`,
  585. [MERGE_PROPS]: `mergeProps`,
  586. [NORMALIZE_CLASS]: `normalizeClass`,
  587. [NORMALIZE_STYLE]: `normalizeStyle`,
  588. [NORMALIZE_PROPS]: `normalizeProps`,
  589. [GUARD_REACTIVE_PROPS]: `guardReactiveProps`,
  590. [TO_HANDLERS]: `toHandlers`,
  591. [CAMELIZE]: `camelize`,
  592. [CAPITALIZE]: `capitalize`,
  593. [TO_HANDLER_KEY]: `toHandlerKey`,
  594. [SET_BLOCK_TRACKING]: `setBlockTracking`,
  595. [PUSH_SCOPE_ID]: `pushScopeId`,
  596. [POP_SCOPE_ID]: `popScopeId`,
  597. [WITH_CTX]: `withCtx`,
  598. [UNREF]: `unref`,
  599. [IS_REF]: `isRef`,
  600. [WITH_MEMO]: `withMemo`,
  601. [IS_MEMO_SAME]: `isMemoSame`
  602. };
  603. function registerRuntimeHelpers(helpers) {
  604. Object.getOwnPropertySymbols(helpers).forEach(s => {
  605. helperNameMap[s] = helpers[s];
  606. });
  607. }
  608. // AST Utilities ---------------------------------------------------------------
  609. // Some expressions, e.g. sequence and conditional expressions, are never
  610. // associated with template nodes, so their source locations are just a stub.
  611. // Container types like CompoundExpression also don't need a real location.
  612. const locStub = {
  613. source: '',
  614. start: { line: 1, column: 1, offset: 0 },
  615. end: { line: 1, column: 1, offset: 0 }
  616. };
  617. function createRoot(children, loc = locStub) {
  618. return {
  619. type: 0 /* NodeTypes.ROOT */,
  620. children,
  621. helpers: [],
  622. components: [],
  623. directives: [],
  624. hoists: [],
  625. imports: [],
  626. cached: 0,
  627. temps: 0,
  628. codegenNode: undefined,
  629. loc
  630. };
  631. }
  632. function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent = false, loc = locStub) {
  633. if (context) {
  634. if (isBlock) {
  635. context.helper(OPEN_BLOCK);
  636. context.helper(getVNodeBlockHelper(context.inSSR, isComponent));
  637. }
  638. else {
  639. context.helper(getVNodeHelper(context.inSSR, isComponent));
  640. }
  641. if (directives) {
  642. context.helper(WITH_DIRECTIVES);
  643. }
  644. }
  645. return {
  646. type: 13 /* NodeTypes.VNODE_CALL */,
  647. tag,
  648. props,
  649. children,
  650. patchFlag,
  651. dynamicProps,
  652. directives,
  653. isBlock,
  654. disableTracking,
  655. isComponent,
  656. loc
  657. };
  658. }
  659. function createArrayExpression(elements, loc = locStub) {
  660. return {
  661. type: 17 /* NodeTypes.JS_ARRAY_EXPRESSION */,
  662. loc,
  663. elements
  664. };
  665. }
  666. function createObjectExpression(properties, loc = locStub) {
  667. return {
  668. type: 15 /* NodeTypes.JS_OBJECT_EXPRESSION */,
  669. loc,
  670. properties
  671. };
  672. }
  673. function createObjectProperty(key, value) {
  674. return {
  675. type: 16 /* NodeTypes.JS_PROPERTY */,
  676. loc: locStub,
  677. key: isString(key) ? createSimpleExpression(key, true) : key,
  678. value
  679. };
  680. }
  681. function createSimpleExpression(content, isStatic = false, loc = locStub, constType = 0 /* ConstantTypes.NOT_CONSTANT */) {
  682. return {
  683. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  684. loc,
  685. content,
  686. isStatic,
  687. constType: isStatic ? 3 /* ConstantTypes.CAN_STRINGIFY */ : constType
  688. };
  689. }
  690. function createInterpolation(content, loc) {
  691. return {
  692. type: 5 /* NodeTypes.INTERPOLATION */,
  693. loc,
  694. content: isString(content)
  695. ? createSimpleExpression(content, false, loc)
  696. : content
  697. };
  698. }
  699. function createCompoundExpression(children, loc = locStub) {
  700. return {
  701. type: 8 /* NodeTypes.COMPOUND_EXPRESSION */,
  702. loc,
  703. children
  704. };
  705. }
  706. function createCallExpression(callee, args = [], loc = locStub) {
  707. return {
  708. type: 14 /* NodeTypes.JS_CALL_EXPRESSION */,
  709. loc,
  710. callee,
  711. arguments: args
  712. };
  713. }
  714. function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
  715. return {
  716. type: 18 /* NodeTypes.JS_FUNCTION_EXPRESSION */,
  717. params,
  718. returns,
  719. newline,
  720. isSlot,
  721. loc
  722. };
  723. }
  724. function createConditionalExpression(test, consequent, alternate, newline = true) {
  725. return {
  726. type: 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */,
  727. test,
  728. consequent,
  729. alternate,
  730. newline,
  731. loc: locStub
  732. };
  733. }
  734. function createCacheExpression(index, value, isVNode = false) {
  735. return {
  736. type: 20 /* NodeTypes.JS_CACHE_EXPRESSION */,
  737. index,
  738. value,
  739. isVNode,
  740. loc: locStub
  741. };
  742. }
  743. function createBlockStatement(body) {
  744. return {
  745. type: 21 /* NodeTypes.JS_BLOCK_STATEMENT */,
  746. body,
  747. loc: locStub
  748. };
  749. }
  750. function createTemplateLiteral(elements) {
  751. return {
  752. type: 22 /* NodeTypes.JS_TEMPLATE_LITERAL */,
  753. elements,
  754. loc: locStub
  755. };
  756. }
  757. function createIfStatement(test, consequent, alternate) {
  758. return {
  759. type: 23 /* NodeTypes.JS_IF_STATEMENT */,
  760. test,
  761. consequent,
  762. alternate,
  763. loc: locStub
  764. };
  765. }
  766. function createAssignmentExpression(left, right) {
  767. return {
  768. type: 24 /* NodeTypes.JS_ASSIGNMENT_EXPRESSION */,
  769. left,
  770. right,
  771. loc: locStub
  772. };
  773. }
  774. function createSequenceExpression(expressions) {
  775. return {
  776. type: 25 /* NodeTypes.JS_SEQUENCE_EXPRESSION */,
  777. expressions,
  778. loc: locStub
  779. };
  780. }
  781. function createReturnStatement(returns) {
  782. return {
  783. type: 26 /* NodeTypes.JS_RETURN_STATEMENT */,
  784. returns,
  785. loc: locStub
  786. };
  787. }
  788. const lineBreak = /\r\n?|[\n\u2028\u2029]/;
  789. const lineBreakG = new RegExp(lineBreak.source, "g");
  790. function isNewLine(code) {
  791. switch (code) {
  792. case 10:
  793. case 13:
  794. case 8232:
  795. case 8233:
  796. return true;
  797. default:
  798. return false;
  799. }
  800. }
  801. const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  802. const skipWhiteSpaceInLine = /(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/y;
  803. const skipWhiteSpaceToLineBreak = new RegExp("(?=(" + skipWhiteSpaceInLine.source + "))\\1" + /(?=[\n\r\u2028\u2029]|\/\*(?!.*?\*\/)|$)/.source, "y");
  804. function isWhitespace(code) {
  805. switch (code) {
  806. case 0x0009:
  807. case 0x000b:
  808. case 0x000c:
  809. case 32:
  810. case 160:
  811. case 5760:
  812. case 0x2000:
  813. case 0x2001:
  814. case 0x2002:
  815. case 0x2003:
  816. case 0x2004:
  817. case 0x2005:
  818. case 0x2006:
  819. case 0x2007:
  820. case 0x2008:
  821. case 0x2009:
  822. case 0x200a:
  823. case 0x202f:
  824. case 0x205f:
  825. case 0x3000:
  826. case 0xfeff:
  827. return true;
  828. default:
  829. return false;
  830. }
  831. }
  832. class Position {
  833. constructor(line, col) {
  834. this.line = void 0;
  835. this.column = void 0;
  836. this.line = line;
  837. this.column = col;
  838. }
  839. }
  840. class SourceLocation {
  841. constructor(start, end) {
  842. this.start = void 0;
  843. this.end = void 0;
  844. this.filename = void 0;
  845. this.identifierName = void 0;
  846. this.start = start;
  847. this.end = end;
  848. }
  849. }
  850. function getLineInfo(input, offset) {
  851. let line = 1;
  852. let lineStart = 0;
  853. let match;
  854. lineBreakG.lastIndex = 0;
  855. while ((match = lineBreakG.exec(input)) && match.index < offset) {
  856. line++;
  857. lineStart = lineBreakG.lastIndex;
  858. }
  859. return new Position(line, offset - lineStart);
  860. }
  861. class BaseParser {
  862. constructor() {
  863. this.sawUnambiguousESM = false;
  864. this.ambiguousScriptDifferentAst = false;
  865. }
  866. hasPlugin(name) {
  867. return this.plugins.has(name);
  868. }
  869. getPluginOption(plugin, name) {
  870. if (this.hasPlugin(plugin)) return this.plugins.get(plugin)[name];
  871. }
  872. }
  873. function setTrailingComments(node, comments) {
  874. if (node.trailingComments === undefined) {
  875. node.trailingComments = comments;
  876. } else {
  877. node.trailingComments.unshift(...comments);
  878. }
  879. }
  880. function setLeadingComments(node, comments) {
  881. if (node.leadingComments === undefined) {
  882. node.leadingComments = comments;
  883. } else {
  884. node.leadingComments.unshift(...comments);
  885. }
  886. }
  887. function setInnerComments(node, comments) {
  888. if (node.innerComments === undefined) {
  889. node.innerComments = comments;
  890. } else {
  891. node.innerComments.unshift(...comments);
  892. }
  893. }
  894. function adjustInnerComments(node, elements, commentWS) {
  895. let lastElement = null;
  896. let i = elements.length;
  897. while (lastElement === null && i > 0) {
  898. lastElement = elements[--i];
  899. }
  900. if (lastElement === null || lastElement.start > commentWS.start) {
  901. setInnerComments(node, commentWS.comments);
  902. } else {
  903. setTrailingComments(lastElement, commentWS.comments);
  904. }
  905. }
  906. class CommentsParser extends BaseParser {
  907. addComment(comment) {
  908. if (this.filename) comment.loc.filename = this.filename;
  909. this.state.comments.push(comment);
  910. }
  911. processComment(node) {
  912. const {
  913. commentStack
  914. } = this.state;
  915. const commentStackLength = commentStack.length;
  916. if (commentStackLength === 0) return;
  917. let i = commentStackLength - 1;
  918. const lastCommentWS = commentStack[i];
  919. if (lastCommentWS.start === node.end) {
  920. lastCommentWS.leadingNode = node;
  921. i--;
  922. }
  923. const {
  924. start: nodeStart
  925. } = node;
  926. for (; i >= 0; i--) {
  927. const commentWS = commentStack[i];
  928. const commentEnd = commentWS.end;
  929. if (commentEnd > nodeStart) {
  930. commentWS.containingNode = node;
  931. this.finalizeComment(commentWS);
  932. commentStack.splice(i, 1);
  933. } else {
  934. if (commentEnd === nodeStart) {
  935. commentWS.trailingNode = node;
  936. }
  937. break;
  938. }
  939. }
  940. }
  941. finalizeComment(commentWS) {
  942. const {
  943. comments
  944. } = commentWS;
  945. if (commentWS.leadingNode !== null || commentWS.trailingNode !== null) {
  946. if (commentWS.leadingNode !== null) {
  947. setTrailingComments(commentWS.leadingNode, comments);
  948. }
  949. if (commentWS.trailingNode !== null) {
  950. setLeadingComments(commentWS.trailingNode, comments);
  951. }
  952. } else {
  953. const {
  954. containingNode: node,
  955. start: commentStart
  956. } = commentWS;
  957. if (this.input.charCodeAt(commentStart - 1) === 44) {
  958. switch (node.type) {
  959. case "ObjectExpression":
  960. case "ObjectPattern":
  961. case "RecordExpression":
  962. adjustInnerComments(node, node.properties, commentWS);
  963. break;
  964. case "CallExpression":
  965. case "OptionalCallExpression":
  966. adjustInnerComments(node, node.arguments, commentWS);
  967. break;
  968. case "FunctionDeclaration":
  969. case "FunctionExpression":
  970. case "ArrowFunctionExpression":
  971. case "ObjectMethod":
  972. case "ClassMethod":
  973. case "ClassPrivateMethod":
  974. adjustInnerComments(node, node.params, commentWS);
  975. break;
  976. case "ArrayExpression":
  977. case "ArrayPattern":
  978. case "TupleExpression":
  979. adjustInnerComments(node, node.elements, commentWS);
  980. break;
  981. case "ExportNamedDeclaration":
  982. case "ImportDeclaration":
  983. adjustInnerComments(node, node.specifiers, commentWS);
  984. break;
  985. default:
  986. {
  987. setInnerComments(node, comments);
  988. }
  989. }
  990. } else {
  991. setInnerComments(node, comments);
  992. }
  993. }
  994. }
  995. finalizeRemainingComments() {
  996. const {
  997. commentStack
  998. } = this.state;
  999. for (let i = commentStack.length - 1; i >= 0; i--) {
  1000. this.finalizeComment(commentStack[i]);
  1001. }
  1002. this.state.commentStack = [];
  1003. }
  1004. resetPreviousNodeTrailingComments(node) {
  1005. const {
  1006. commentStack
  1007. } = this.state;
  1008. const {
  1009. length
  1010. } = commentStack;
  1011. if (length === 0) return;
  1012. const commentWS = commentStack[length - 1];
  1013. if (commentWS.leadingNode === node) {
  1014. commentWS.leadingNode = null;
  1015. }
  1016. }
  1017. takeSurroundingComments(node, start, end) {
  1018. const {
  1019. commentStack
  1020. } = this.state;
  1021. const commentStackLength = commentStack.length;
  1022. if (commentStackLength === 0) return;
  1023. let i = commentStackLength - 1;
  1024. for (; i >= 0; i--) {
  1025. const commentWS = commentStack[i];
  1026. const commentEnd = commentWS.end;
  1027. const commentStart = commentWS.start;
  1028. if (commentStart === end) {
  1029. commentWS.leadingNode = node;
  1030. } else if (commentEnd === start) {
  1031. commentWS.trailingNode = node;
  1032. } else if (commentEnd < start) {
  1033. break;
  1034. }
  1035. }
  1036. }
  1037. }
  1038. const ErrorCodes = Object.freeze({
  1039. SyntaxError: "BABEL_PARSER_SYNTAX_ERROR",
  1040. SourceTypeModuleError: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  1041. });
  1042. const ErrorMessages = makeErrorTemplates({
  1043. AccessorIsGenerator: "A %0ter cannot be a generator.",
  1044. ArgumentsInClass: "'arguments' is only allowed in functions and class methods.",
  1045. AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block.",
  1046. AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function.",
  1047. AwaitBindingIdentifierInStaticBlock: "Can not use 'await' as identifier inside a static block.",
  1048. AwaitExpressionFormalParameter: "'await' is not allowed in async function parameters.",
  1049. AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules.",
  1050. AwaitNotInAsyncFunction: "'await' is only allowed within async functions.",
  1051. BadGetterArity: "A 'get' accesor must not have any formal parameters.",
  1052. BadSetterArity: "A 'set' accesor must have exactly one formal parameter.",
  1053. BadSetterRestParameter: "A 'set' accesor function argument must not be a rest parameter.",
  1054. ConstructorClassField: "Classes may not have a field named 'constructor'.",
  1055. ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'.",
  1056. ConstructorIsAccessor: "Class constructor may not be an accessor.",
  1057. ConstructorIsAsync: "Constructor can't be an async function.",
  1058. ConstructorIsGenerator: "Constructor can't be a generator.",
  1059. DeclarationMissingInitializer: "'%0' require an initialization value.",
  1060. DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. You can set the 'decoratorsBeforeExport' option to false to use the 'export @decorator class {}' syntax.",
  1061. DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",
  1062. DecoratorExportClass: "Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class` instead.",
  1063. DecoratorSemicolon: "Decorators must not be followed by a semicolon.",
  1064. DecoratorStaticBlock: "Decorators can't be used with a static block.",
  1065. DeletePrivateField: "Deleting a private field is not allowed.",
  1066. DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.",
  1067. DuplicateConstructor: "Duplicate constructor in the same class.",
  1068. DuplicateDefaultExport: "Only one default export allowed per module.",
  1069. DuplicateExport: "`%0` has already been exported. Exported identifiers must be unique.",
  1070. DuplicateProto: "Redefinition of __proto__ property.",
  1071. DuplicateRegExpFlags: "Duplicate regular expression flag.",
  1072. ElementAfterRest: "Rest element must be last element.",
  1073. EscapedCharNotAnIdentifier: "Invalid Unicode escape.",
  1074. ExportBindingIsString: "A string literal cannot be used as an exported binding without `from`.\n- Did you mean `export { '%0' as '%1' } from 'some-module'`?",
  1075. ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'.",
  1076. ForInOfLoopInitializer: "'%0' loop variable declaration may not have an initializer.",
  1077. ForOfAsync: "The left-hand side of a for-of loop may not be 'async'.",
  1078. ForOfLet: "The left-hand side of a for-of loop may not start with 'let'.",
  1079. GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block.",
  1080. IllegalBreakContinue: "Unsyntactic %0.",
  1081. IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list.",
  1082. IllegalReturn: "'return' outside of function.",
  1083. ImportBindingIsString: 'A string literal cannot be used as an imported binding.\n- Did you mean `import { "%0" as foo }`?',
  1084. ImportCallArgumentTrailingComma: "Trailing comma is disallowed inside import(...) arguments.",
  1085. ImportCallArity: "`import()` requires exactly %0.",
  1086. ImportCallNotNewExpression: "Cannot use new with import(...).",
  1087. ImportCallSpreadArgument: "`...` is not allowed in `import()`.",
  1088. InvalidBigIntLiteral: "Invalid BigIntLiteral.",
  1089. InvalidCodePoint: "Code point out of bounds.",
  1090. InvalidDecimal: "Invalid decimal.",
  1091. InvalidDigit: "Expected number in radix %0.",
  1092. InvalidEscapeSequence: "Bad character escape sequence.",
  1093. InvalidEscapeSequenceTemplate: "Invalid escape sequence in template.",
  1094. InvalidEscapedReservedWord: "Escape sequence in keyword %0.",
  1095. InvalidIdentifier: "Invalid identifier %0.",
  1096. InvalidLhs: "Invalid left-hand side in %0.",
  1097. InvalidLhsBinding: "Binding invalid left-hand side in %0.",
  1098. InvalidNumber: "Invalid number.",
  1099. InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'.",
  1100. InvalidOrUnexpectedToken: "Unexpected character '%0'.",
  1101. InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern.",
  1102. InvalidPrivateFieldResolution: "Private name #%0 is not defined.",
  1103. InvalidPropertyBindingPattern: "Binding member expression.",
  1104. InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions.",
  1105. InvalidRestAssignmentPattern: "Invalid rest operator's argument.",
  1106. LabelRedeclaration: "Label '%0' is already declared.",
  1107. LetInLexicalBinding: "'let' is not allowed to be used as a name in 'let' or 'const' declarations.",
  1108. LineTerminatorBeforeArrow: "No line break is allowed before '=>'.",
  1109. MalformedRegExpFlags: "Invalid regular expression flag.",
  1110. MissingClassName: "A class name is required.",
  1111. MissingEqInAssignment: "Only '=' operator can be used for specifying default value.",
  1112. MissingSemicolon: "Missing semicolon.",
  1113. MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX.",
  1114. MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators.",
  1115. ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`.",
  1116. ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values.",
  1117. ModuleAttributesWithDuplicateKeys: 'Duplicate key "%0" is not allowed in module attributes.',
  1118. ModuleExportNameHasLoneSurrogate: "An export name cannot include a lone surrogate, found '\\u%0'.",
  1119. ModuleExportUndefined: "Export '%0' is not defined.",
  1120. MultipleDefaultsInSwitch: "Multiple default clauses.",
  1121. NewlineAfterThrow: "Illegal newline after throw.",
  1122. NoCatchOrFinally: "Missing catch or finally clause.",
  1123. NumberIdentifier: "Identifier directly after number.",
  1124. NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.",
  1125. ObsoleteAwaitStar: "'await*' has been removed from the async functions proposal. Use Promise.all() instead.",
  1126. OptionalChainingNoNew: "Constructors in/after an Optional Chain are not allowed.",
  1127. OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain.",
  1128. OverrideOnConstructor: "'override' modifier cannot appear on a constructor declaration.",
  1129. ParamDupe: "Argument name clash.",
  1130. PatternHasAccessor: "Object pattern can't contain getter or setter.",
  1131. PatternHasMethod: "Object pattern can't contain methods.",
  1132. PipeBodyIsTighter: "Unexpected %0 after pipeline body; any %0 expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.",
  1133. PipeTopicRequiresHackPipes: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.',
  1134. PipeTopicUnbound: "Topic reference is unbound; it must be inside a pipe body.",
  1135. 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" }.',
  1136. PipeTopicUnused: "Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.",
  1137. PipeUnparenthesizedBody: "Hack-style pipe body cannot be an unparenthesized %0 expression; please wrap it in parentheses.",
  1138. PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized.',
  1139. PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression.",
  1140. PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression.",
  1141. PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference.",
  1142. PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding.",
  1143. PrimaryTopicRequiresSmartPipeline: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.',
  1144. PrivateInExpectedIn: "Private names are only allowed in property accesses (`obj.#%0`) or in `in` expressions (`#%0 in obj`).",
  1145. PrivateNameRedeclaration: "Duplicate private name #%0.",
  1146. RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  1147. RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  1148. RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",
  1149. RecordNoProto: "'__proto__' is not allowed in Record expressions.",
  1150. RestTrailingComma: "Unexpected trailing comma after rest element.",
  1151. 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.",
  1152. StaticPrototype: "Classes may not have static property named prototype.",
  1153. StrictDelete: "Deleting local variable in strict mode.",
  1154. StrictEvalArguments: "Assigning to '%0' in strict mode.",
  1155. StrictEvalArgumentsBinding: "Binding '%0' in strict mode.",
  1156. StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block.",
  1157. StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'.",
  1158. StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode.",
  1159. StrictWith: "'with' in strict mode.",
  1160. 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?",
  1161. SuperPrivateField: "Private fields can't be accessed on super.",
  1162. TrailingDecorator: "Decorators must be attached to a class element.",
  1163. TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  1164. TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  1165. TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",
  1166. UnexpectedArgumentPlaceholder: "Unexpected argument placeholder.",
  1167. UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal.',
  1168. UnexpectedDigitAfterHash: "Unexpected digit after hash token.",
  1169. UnexpectedImportExport: "'import' and 'export' may only appear at the top level.",
  1170. UnexpectedKeyword: "Unexpected keyword '%0'.",
  1171. UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration.",
  1172. UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context.",
  1173. UnexpectedNewTarget: "`new.target` can only be used in functions or class properties.",
  1174. UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits.",
  1175. 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).",
  1176. UnexpectedReservedWord: "Unexpected reserved word '%0'.",
  1177. UnexpectedSuper: "'super' is only allowed in object methods and classes.",
  1178. UnexpectedToken: "Unexpected token '%0'.",
  1179. UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",
  1180. UnsupportedBind: "Binding should be performed on object property.",
  1181. UnsupportedDecoratorExport: "A decorated export must export a class declaration.",
  1182. UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.",
  1183. UnsupportedImport: "`import` can only be used in `import()` or `import.meta`.",
  1184. UnsupportedMetaProperty: "The only valid meta property for %0 is %0.%1.",
  1185. UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters.",
  1186. UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties.",
  1187. UnsupportedSuper: "'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).",
  1188. UnterminatedComment: "Unterminated comment.",
  1189. UnterminatedRegExp: "Unterminated regular expression.",
  1190. UnterminatedString: "Unterminated string constant.",
  1191. UnterminatedTemplate: "Unterminated template.",
  1192. VarRedeclaration: "Identifier '%0' has already been declared.",
  1193. YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator.",
  1194. YieldInParameter: "Yield expression is not allowed in formal parameters.",
  1195. ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0."
  1196. }, ErrorCodes.SyntaxError);
  1197. const SourceTypeModuleErrorMessages = makeErrorTemplates({
  1198. ImportMetaOutsideModule: `import.meta may appear only with 'sourceType: "module"'`,
  1199. ImportOutsideModule: `'import' and 'export' may appear only with 'sourceType: "module"'`
  1200. }, ErrorCodes.SourceTypeModuleError);
  1201. function keepReasonCodeCompat(reasonCode, syntaxPlugin) {
  1202. {
  1203. if (syntaxPlugin === "flow" && reasonCode === "PatternIsOptional") {
  1204. return "OptionalBindingPattern";
  1205. }
  1206. }
  1207. return reasonCode;
  1208. }
  1209. function makeErrorTemplates(messages, code, syntaxPlugin) {
  1210. const templates = {};
  1211. Object.keys(messages).forEach(reasonCode => {
  1212. templates[reasonCode] = Object.freeze({
  1213. code,
  1214. reasonCode: keepReasonCodeCompat(reasonCode, syntaxPlugin),
  1215. template: messages[reasonCode]
  1216. });
  1217. });
  1218. return Object.freeze(templates);
  1219. }
  1220. class ParserError extends CommentsParser {
  1221. getLocationForPosition(pos) {
  1222. let loc;
  1223. 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);
  1224. return loc;
  1225. }
  1226. raise(pos, {
  1227. code,
  1228. reasonCode,
  1229. template
  1230. }, ...params) {
  1231. return this.raiseWithData(pos, {
  1232. code,
  1233. reasonCode
  1234. }, template, ...params);
  1235. }
  1236. raiseOverwrite(pos, {
  1237. code,
  1238. template
  1239. }, ...params) {
  1240. const loc = this.getLocationForPosition(pos);
  1241. const message = template.replace(/%(\d+)/g, (_, i) => params[i]) + ` (${loc.line}:${loc.column})`;
  1242. if (this.options.errorRecovery) {
  1243. const errors = this.state.errors;
  1244. for (let i = errors.length - 1; i >= 0; i--) {
  1245. const error = errors[i];
  1246. if (error.pos === pos) {
  1247. return Object.assign(error, {
  1248. message
  1249. });
  1250. } else if (error.pos < pos) {
  1251. break;
  1252. }
  1253. }
  1254. }
  1255. return this._raise({
  1256. code,
  1257. loc,
  1258. pos
  1259. }, message);
  1260. }
  1261. raiseWithData(pos, data, errorTemplate, ...params) {
  1262. const loc = this.getLocationForPosition(pos);
  1263. const message = errorTemplate.replace(/%(\d+)/g, (_, i) => params[i]) + ` (${loc.line}:${loc.column})`;
  1264. return this._raise(Object.assign({
  1265. loc,
  1266. pos
  1267. }, data), message);
  1268. }
  1269. _raise(errorContext, message) {
  1270. const err = new SyntaxError(message);
  1271. Object.assign(err, errorContext);
  1272. if (this.options.errorRecovery) {
  1273. if (!this.isLookahead) this.state.errors.push(err);
  1274. return err;
  1275. } else {
  1276. throw err;
  1277. }
  1278. }
  1279. }
  1280. var estree = (superClass => class extends superClass {
  1281. parseRegExpLiteral({
  1282. pattern,
  1283. flags
  1284. }) {
  1285. let regex = null;
  1286. try {
  1287. regex = new RegExp(pattern, flags);
  1288. } catch (e) {}
  1289. const node = this.estreeParseLiteral(regex);
  1290. node.regex = {
  1291. pattern,
  1292. flags
  1293. };
  1294. return node;
  1295. }
  1296. parseBigIntLiteral(value) {
  1297. let bigInt;
  1298. try {
  1299. bigInt = BigInt(value);
  1300. } catch (_unused) {
  1301. bigInt = null;
  1302. }
  1303. const node = this.estreeParseLiteral(bigInt);
  1304. node.bigint = String(node.value || value);
  1305. return node;
  1306. }
  1307. parseDecimalLiteral(value) {
  1308. const decimal = null;
  1309. const node = this.estreeParseLiteral(decimal);
  1310. node.decimal = String(node.value || value);
  1311. return node;
  1312. }
  1313. estreeParseLiteral(value) {
  1314. return this.parseLiteral(value, "Literal");
  1315. }
  1316. parseStringLiteral(value) {
  1317. return this.estreeParseLiteral(value);
  1318. }
  1319. parseNumericLiteral(value) {
  1320. return this.estreeParseLiteral(value);
  1321. }
  1322. parseNullLiteral() {
  1323. return this.estreeParseLiteral(null);
  1324. }
  1325. parseBooleanLiteral(value) {
  1326. return this.estreeParseLiteral(value);
  1327. }
  1328. directiveToStmt(directive) {
  1329. const directiveLiteral = directive.value;
  1330. const stmt = this.startNodeAt(directive.start, directive.loc.start);
  1331. const expression = this.startNodeAt(directiveLiteral.start, directiveLiteral.loc.start);
  1332. expression.value = directiveLiteral.extra.expressionValue;
  1333. expression.raw = directiveLiteral.extra.raw;
  1334. stmt.expression = this.finishNodeAt(expression, "Literal", directiveLiteral.end, directiveLiteral.loc.end);
  1335. stmt.directive = directiveLiteral.extra.raw.slice(1, -1);
  1336. return this.finishNodeAt(stmt, "ExpressionStatement", directive.end, directive.loc.end);
  1337. }
  1338. initFunction(node, isAsync) {
  1339. super.initFunction(node, isAsync);
  1340. node.expression = false;
  1341. }
  1342. checkDeclaration(node) {
  1343. if (node != null && this.isObjectProperty(node)) {
  1344. this.checkDeclaration(node.value);
  1345. } else {
  1346. super.checkDeclaration(node);
  1347. }
  1348. }
  1349. getObjectOrClassMethodParams(method) {
  1350. return method.value.params;
  1351. }
  1352. isValidDirective(stmt) {
  1353. var _stmt$expression$extr;
  1354. return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && !((_stmt$expression$extr = stmt.expression.extra) != null && _stmt$expression$extr.parenthesized);
  1355. }
  1356. parseBlockBody(node, ...args) {
  1357. super.parseBlockBody(node, ...args);
  1358. const directiveStatements = node.directives.map(d => this.directiveToStmt(d));
  1359. node.body = directiveStatements.concat(node.body);
  1360. delete node.directives;
  1361. }
  1362. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  1363. this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true);
  1364. if (method.typeParameters) {
  1365. method.value.typeParameters = method.typeParameters;
  1366. delete method.typeParameters;
  1367. }
  1368. classBody.body.push(method);
  1369. }
  1370. parsePrivateName() {
  1371. const node = super.parsePrivateName();
  1372. {
  1373. if (!this.getPluginOption("estree", "classFeatures")) {
  1374. return node;
  1375. }
  1376. }
  1377. return this.convertPrivateNameToPrivateIdentifier(node);
  1378. }
  1379. convertPrivateNameToPrivateIdentifier(node) {
  1380. const name = super.getPrivateNameSV(node);
  1381. node = node;
  1382. delete node.id;
  1383. node.name = name;
  1384. node.type = "PrivateIdentifier";
  1385. return node;
  1386. }
  1387. isPrivateName(node) {
  1388. {
  1389. if (!this.getPluginOption("estree", "classFeatures")) {
  1390. return super.isPrivateName(node);
  1391. }
  1392. }
  1393. return node.type === "PrivateIdentifier";
  1394. }
  1395. getPrivateNameSV(node) {
  1396. {
  1397. if (!this.getPluginOption("estree", "classFeatures")) {
  1398. return super.getPrivateNameSV(node);
  1399. }
  1400. }
  1401. return node.name;
  1402. }
  1403. parseLiteral(value, type) {
  1404. const node = super.parseLiteral(value, type);
  1405. node.raw = node.extra.raw;
  1406. delete node.extra;
  1407. return node;
  1408. }
  1409. parseFunctionBody(node, allowExpression, isMethod = false) {
  1410. super.parseFunctionBody(node, allowExpression, isMethod);
  1411. node.expression = node.body.type !== "BlockStatement";
  1412. }
  1413. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  1414. let funcNode = this.startNode();
  1415. funcNode.kind = node.kind;
  1416. funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  1417. funcNode.type = "FunctionExpression";
  1418. delete funcNode.kind;
  1419. node.value = funcNode;
  1420. if (type === "ClassPrivateMethod") {
  1421. node.computed = false;
  1422. }
  1423. type = "MethodDefinition";
  1424. return this.finishNode(node, type);
  1425. }
  1426. parseClassProperty(...args) {
  1427. const propertyNode = super.parseClassProperty(...args);
  1428. {
  1429. if (!this.getPluginOption("estree", "classFeatures")) {
  1430. return propertyNode;
  1431. }
  1432. }
  1433. propertyNode.type = "PropertyDefinition";
  1434. return propertyNode;
  1435. }
  1436. parseClassPrivateProperty(...args) {
  1437. const propertyNode = super.parseClassPrivateProperty(...args);
  1438. {
  1439. if (!this.getPluginOption("estree", "classFeatures")) {
  1440. return propertyNode;
  1441. }
  1442. }
  1443. propertyNode.type = "PropertyDefinition";
  1444. propertyNode.computed = false;
  1445. return propertyNode;
  1446. }
  1447. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  1448. const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor);
  1449. if (node) {
  1450. node.type = "Property";
  1451. if (node.kind === "method") node.kind = "init";
  1452. node.shorthand = false;
  1453. }
  1454. return node;
  1455. }
  1456. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  1457. const node = super.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  1458. if (node) {
  1459. node.kind = "init";
  1460. node.type = "Property";
  1461. }
  1462. return node;
  1463. }
  1464. isAssignable(node, isBinding) {
  1465. if (node != null && this.isObjectProperty(node)) {
  1466. return this.isAssignable(node.value, isBinding);
  1467. }
  1468. return super.isAssignable(node, isBinding);
  1469. }
  1470. toAssignable(node, isLHS = false) {
  1471. if (node != null && this.isObjectProperty(node)) {
  1472. this.toAssignable(node.value, isLHS);
  1473. return node;
  1474. }
  1475. return super.toAssignable(node, isLHS);
  1476. }
  1477. toAssignableObjectExpressionProp(prop, ...args) {
  1478. if (prop.kind === "get" || prop.kind === "set") {
  1479. this.raise(prop.key.start, ErrorMessages.PatternHasAccessor);
  1480. } else if (prop.method) {
  1481. this.raise(prop.key.start, ErrorMessages.PatternHasMethod);
  1482. } else {
  1483. super.toAssignableObjectExpressionProp(prop, ...args);
  1484. }
  1485. }
  1486. finishCallExpression(node, optional) {
  1487. super.finishCallExpression(node, optional);
  1488. if (node.callee.type === "Import") {
  1489. node.type = "ImportExpression";
  1490. node.source = node.arguments[0];
  1491. if (this.hasPlugin("importAssertions")) {
  1492. var _node$arguments$;
  1493. node.attributes = (_node$arguments$ = node.arguments[1]) != null ? _node$arguments$ : null;
  1494. }
  1495. delete node.arguments;
  1496. delete node.callee;
  1497. }
  1498. return node;
  1499. }
  1500. toReferencedArguments(node) {
  1501. if (node.type === "ImportExpression") {
  1502. return;
  1503. }
  1504. super.toReferencedArguments(node);
  1505. }
  1506. parseExport(node) {
  1507. super.parseExport(node);
  1508. switch (node.type) {
  1509. case "ExportAllDeclaration":
  1510. node.exported = null;
  1511. break;
  1512. case "ExportNamedDeclaration":
  1513. if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") {
  1514. node.type = "ExportAllDeclaration";
  1515. node.exported = node.specifiers[0].exported;
  1516. delete node.specifiers;
  1517. }
  1518. break;
  1519. }
  1520. return node;
  1521. }
  1522. parseSubscript(base, startPos, startLoc, noCalls, state) {
  1523. const node = super.parseSubscript(base, startPos, startLoc, noCalls, state);
  1524. if (state.optionalChainMember) {
  1525. if (node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression") {
  1526. node.type = node.type.substring(8);
  1527. }
  1528. if (state.stop) {
  1529. const chain = this.startNodeAtNode(node);
  1530. chain.expression = node;
  1531. return this.finishNode(chain, "ChainExpression");
  1532. }
  1533. } else if (node.type === "MemberExpression" || node.type === "CallExpression") {
  1534. node.optional = false;
  1535. }
  1536. return node;
  1537. }
  1538. hasPropertyAsPrivateName(node) {
  1539. if (node.type === "ChainExpression") {
  1540. node = node.expression;
  1541. }
  1542. return super.hasPropertyAsPrivateName(node);
  1543. }
  1544. isOptionalChain(node) {
  1545. return node.type === "ChainExpression";
  1546. }
  1547. isObjectProperty(node) {
  1548. return node.type === "Property" && node.kind === "init" && !node.method;
  1549. }
  1550. isObjectMethod(node) {
  1551. return node.method || node.kind === "get" || node.kind === "set";
  1552. }
  1553. });
  1554. class TokContext {
  1555. constructor(token, preserveSpace) {
  1556. this.token = void 0;
  1557. this.preserveSpace = void 0;
  1558. this.token = token;
  1559. this.preserveSpace = !!preserveSpace;
  1560. }
  1561. }
  1562. const types = {
  1563. brace: new TokContext("{"),
  1564. template: new TokContext("`", true)
  1565. };
  1566. const beforeExpr = true;
  1567. const startsExpr = true;
  1568. const isLoop = true;
  1569. const isAssign = true;
  1570. const prefix = true;
  1571. const postfix = true;
  1572. class ExportedTokenType {
  1573. constructor(label, conf = {}) {
  1574. this.label = void 0;
  1575. this.keyword = void 0;
  1576. this.beforeExpr = void 0;
  1577. this.startsExpr = void 0;
  1578. this.rightAssociative = void 0;
  1579. this.isLoop = void 0;
  1580. this.isAssign = void 0;
  1581. this.prefix = void 0;
  1582. this.postfix = void 0;
  1583. this.binop = void 0;
  1584. this.label = label;
  1585. this.keyword = conf.keyword;
  1586. this.beforeExpr = !!conf.beforeExpr;
  1587. this.startsExpr = !!conf.startsExpr;
  1588. this.rightAssociative = !!conf.rightAssociative;
  1589. this.isLoop = !!conf.isLoop;
  1590. this.isAssign = !!conf.isAssign;
  1591. this.prefix = !!conf.prefix;
  1592. this.postfix = !!conf.postfix;
  1593. this.binop = conf.binop != null ? conf.binop : null;
  1594. {
  1595. this.updateContext = null;
  1596. }
  1597. }
  1598. }
  1599. const keywords$1 = new Map();
  1600. function createKeyword(name, options = {}) {
  1601. options.keyword = name;
  1602. const token = createToken(name, options);
  1603. keywords$1.set(name, token);
  1604. return token;
  1605. }
  1606. function createBinop(name, binop) {
  1607. return createToken(name, {
  1608. beforeExpr,
  1609. binop
  1610. });
  1611. }
  1612. let tokenTypeCounter = -1;
  1613. const tokenTypes = [];
  1614. const tokenLabels = [];
  1615. const tokenBinops = [];
  1616. const tokenBeforeExprs = [];
  1617. const tokenStartsExprs = [];
  1618. const tokenPrefixes = [];
  1619. function createToken(name, options = {}) {
  1620. var _options$binop, _options$beforeExpr, _options$startsExpr, _options$prefix;
  1621. ++tokenTypeCounter;
  1622. tokenLabels.push(name);
  1623. tokenBinops.push((_options$binop = options.binop) != null ? _options$binop : -1);
  1624. tokenBeforeExprs.push((_options$beforeExpr = options.beforeExpr) != null ? _options$beforeExpr : false);
  1625. tokenStartsExprs.push((_options$startsExpr = options.startsExpr) != null ? _options$startsExpr : false);
  1626. tokenPrefixes.push((_options$prefix = options.prefix) != null ? _options$prefix : false);
  1627. tokenTypes.push(new ExportedTokenType(name, options));
  1628. return tokenTypeCounter;
  1629. }
  1630. function createKeywordLike(name, options = {}) {
  1631. var _options$binop2, _options$beforeExpr2, _options$startsExpr2, _options$prefix2;
  1632. ++tokenTypeCounter;
  1633. keywords$1.set(name, tokenTypeCounter);
  1634. tokenLabels.push(name);
  1635. tokenBinops.push((_options$binop2 = options.binop) != null ? _options$binop2 : -1);
  1636. tokenBeforeExprs.push((_options$beforeExpr2 = options.beforeExpr) != null ? _options$beforeExpr2 : false);
  1637. tokenStartsExprs.push((_options$startsExpr2 = options.startsExpr) != null ? _options$startsExpr2 : false);
  1638. tokenPrefixes.push((_options$prefix2 = options.prefix) != null ? _options$prefix2 : false);
  1639. tokenTypes.push(new ExportedTokenType("name", options));
  1640. return tokenTypeCounter;
  1641. }
  1642. const tt = {
  1643. bracketL: createToken("[", {
  1644. beforeExpr,
  1645. startsExpr
  1646. }),
  1647. bracketHashL: createToken("#[", {
  1648. beforeExpr,
  1649. startsExpr
  1650. }),
  1651. bracketBarL: createToken("[|", {
  1652. beforeExpr,
  1653. startsExpr
  1654. }),
  1655. bracketR: createToken("]"),
  1656. bracketBarR: createToken("|]"),
  1657. braceL: createToken("{", {
  1658. beforeExpr,
  1659. startsExpr
  1660. }),
  1661. braceBarL: createToken("{|", {
  1662. beforeExpr,
  1663. startsExpr
  1664. }),
  1665. braceHashL: createToken("#{", {
  1666. beforeExpr,
  1667. startsExpr
  1668. }),
  1669. braceR: createToken("}", {
  1670. beforeExpr
  1671. }),
  1672. braceBarR: createToken("|}"),
  1673. parenL: createToken("(", {
  1674. beforeExpr,
  1675. startsExpr
  1676. }),
  1677. parenR: createToken(")"),
  1678. comma: createToken(",", {
  1679. beforeExpr
  1680. }),
  1681. semi: createToken(";", {
  1682. beforeExpr
  1683. }),
  1684. colon: createToken(":", {
  1685. beforeExpr
  1686. }),
  1687. doubleColon: createToken("::", {
  1688. beforeExpr
  1689. }),
  1690. dot: createToken("."),
  1691. question: createToken("?", {
  1692. beforeExpr
  1693. }),
  1694. questionDot: createToken("?."),
  1695. arrow: createToken("=>", {
  1696. beforeExpr
  1697. }),
  1698. template: createToken("template"),
  1699. ellipsis: createToken("...", {
  1700. beforeExpr
  1701. }),
  1702. backQuote: createToken("`", {
  1703. startsExpr
  1704. }),
  1705. dollarBraceL: createToken("${", {
  1706. beforeExpr,
  1707. startsExpr
  1708. }),
  1709. at: createToken("@"),
  1710. hash: createToken("#", {
  1711. startsExpr
  1712. }),
  1713. interpreterDirective: createToken("#!..."),
  1714. eq: createToken("=", {
  1715. beforeExpr,
  1716. isAssign
  1717. }),
  1718. assign: createToken("_=", {
  1719. beforeExpr,
  1720. isAssign
  1721. }),
  1722. slashAssign: createToken("_=", {
  1723. beforeExpr,
  1724. isAssign
  1725. }),
  1726. xorAssign: createToken("_=", {
  1727. beforeExpr,
  1728. isAssign
  1729. }),
  1730. moduloAssign: createToken("_=", {
  1731. beforeExpr,
  1732. isAssign
  1733. }),
  1734. incDec: createToken("++/--", {
  1735. prefix,
  1736. postfix,
  1737. startsExpr
  1738. }),
  1739. bang: createToken("!", {
  1740. beforeExpr,
  1741. prefix,
  1742. startsExpr
  1743. }),
  1744. tilde: createToken("~", {
  1745. beforeExpr,
  1746. prefix,
  1747. startsExpr
  1748. }),
  1749. pipeline: createBinop("|>", 0),
  1750. nullishCoalescing: createBinop("??", 1),
  1751. logicalOR: createBinop("||", 1),
  1752. logicalAND: createBinop("&&", 2),
  1753. bitwiseOR: createBinop("|", 3),
  1754. bitwiseXOR: createBinop("^", 4),
  1755. bitwiseAND: createBinop("&", 5),
  1756. equality: createBinop("==/!=/===/!==", 6),
  1757. lt: createBinop("</>/<=/>=", 7),
  1758. gt: createBinop("</>/<=/>=", 7),
  1759. relational: createBinop("</>/<=/>=", 7),
  1760. bitShift: createBinop("<</>>/>>>", 8),
  1761. plusMin: createToken("+/-", {
  1762. beforeExpr,
  1763. binop: 9,
  1764. prefix,
  1765. startsExpr
  1766. }),
  1767. modulo: createToken("%", {
  1768. binop: 10,
  1769. startsExpr
  1770. }),
  1771. star: createToken("*", {
  1772. binop: 10
  1773. }),
  1774. slash: createBinop("/", 10),
  1775. exponent: createToken("**", {
  1776. beforeExpr,
  1777. binop: 11,
  1778. rightAssociative: true
  1779. }),
  1780. _in: createKeyword("in", {
  1781. beforeExpr,
  1782. binop: 7
  1783. }),
  1784. _instanceof: createKeyword("instanceof", {
  1785. beforeExpr,
  1786. binop: 7
  1787. }),
  1788. _break: createKeyword("break"),
  1789. _case: createKeyword("case", {
  1790. beforeExpr
  1791. }),
  1792. _catch: createKeyword("catch"),
  1793. _continue: createKeyword("continue"),
  1794. _debugger: createKeyword("debugger"),
  1795. _default: createKeyword("default", {
  1796. beforeExpr
  1797. }),
  1798. _else: createKeyword("else", {
  1799. beforeExpr
  1800. }),
  1801. _finally: createKeyword("finally"),
  1802. _function: createKeyword("function", {
  1803. startsExpr
  1804. }),
  1805. _if: createKeyword("if"),
  1806. _return: createKeyword("return", {
  1807. beforeExpr
  1808. }),
  1809. _switch: createKeyword("switch"),
  1810. _throw: createKeyword("throw", {
  1811. beforeExpr,
  1812. prefix,
  1813. startsExpr
  1814. }),
  1815. _try: createKeyword("try"),
  1816. _var: createKeyword("var"),
  1817. _const: createKeyword("const"),
  1818. _with: createKeyword("with"),
  1819. _new: createKeyword("new", {
  1820. beforeExpr,
  1821. startsExpr
  1822. }),
  1823. _this: createKeyword("this", {
  1824. startsExpr
  1825. }),
  1826. _super: createKeyword("super", {
  1827. startsExpr
  1828. }),
  1829. _class: createKeyword("class", {
  1830. startsExpr
  1831. }),
  1832. _extends: createKeyword("extends", {
  1833. beforeExpr
  1834. }),
  1835. _export: createKeyword("export"),
  1836. _import: createKeyword("import", {
  1837. startsExpr
  1838. }),
  1839. _null: createKeyword("null", {
  1840. startsExpr
  1841. }),
  1842. _true: createKeyword("true", {
  1843. startsExpr
  1844. }),
  1845. _false: createKeyword("false", {
  1846. startsExpr
  1847. }),
  1848. _typeof: createKeyword("typeof", {
  1849. beforeExpr,
  1850. prefix,
  1851. startsExpr
  1852. }),
  1853. _void: createKeyword("void", {
  1854. beforeExpr,
  1855. prefix,
  1856. startsExpr
  1857. }),
  1858. _delete: createKeyword("delete", {
  1859. beforeExpr,
  1860. prefix,
  1861. startsExpr
  1862. }),
  1863. _do: createKeyword("do", {
  1864. isLoop,
  1865. beforeExpr
  1866. }),
  1867. _for: createKeyword("for", {
  1868. isLoop
  1869. }),
  1870. _while: createKeyword("while", {
  1871. isLoop
  1872. }),
  1873. _as: createKeywordLike("as", {
  1874. startsExpr
  1875. }),
  1876. _assert: createKeywordLike("assert", {
  1877. startsExpr
  1878. }),
  1879. _async: createKeywordLike("async", {
  1880. startsExpr
  1881. }),
  1882. _await: createKeywordLike("await", {
  1883. startsExpr
  1884. }),
  1885. _from: createKeywordLike("from", {
  1886. startsExpr
  1887. }),
  1888. _get: createKeywordLike("get", {
  1889. startsExpr
  1890. }),
  1891. _let: createKeywordLike("let", {
  1892. startsExpr
  1893. }),
  1894. _meta: createKeywordLike("meta", {
  1895. startsExpr
  1896. }),
  1897. _of: createKeywordLike("of", {
  1898. startsExpr
  1899. }),
  1900. _sent: createKeywordLike("sent", {
  1901. startsExpr
  1902. }),
  1903. _set: createKeywordLike("set", {
  1904. startsExpr
  1905. }),
  1906. _static: createKeywordLike("static", {
  1907. startsExpr
  1908. }),
  1909. _yield: createKeywordLike("yield", {
  1910. startsExpr
  1911. }),
  1912. _asserts: createKeywordLike("asserts", {
  1913. startsExpr
  1914. }),
  1915. _checks: createKeywordLike("checks", {
  1916. startsExpr
  1917. }),
  1918. _exports: createKeywordLike("exports", {
  1919. startsExpr
  1920. }),
  1921. _global: createKeywordLike("global", {
  1922. startsExpr
  1923. }),
  1924. _implements: createKeywordLike("implements", {
  1925. startsExpr
  1926. }),
  1927. _intrinsic: createKeywordLike("intrinsic", {
  1928. startsExpr
  1929. }),
  1930. _infer: createKeywordLike("infer", {
  1931. startsExpr
  1932. }),
  1933. _is: createKeywordLike("is", {
  1934. startsExpr
  1935. }),
  1936. _mixins: createKeywordLike("mixins", {
  1937. startsExpr
  1938. }),
  1939. _proto: createKeywordLike("proto", {
  1940. startsExpr
  1941. }),
  1942. _require: createKeywordLike("require", {
  1943. startsExpr
  1944. }),
  1945. _keyof: createKeywordLike("keyof", {
  1946. startsExpr
  1947. }),
  1948. _readonly: createKeywordLike("readonly", {
  1949. startsExpr
  1950. }),
  1951. _unique: createKeywordLike("unique", {
  1952. startsExpr
  1953. }),
  1954. _abstract: createKeywordLike("abstract", {
  1955. startsExpr
  1956. }),
  1957. _declare: createKeywordLike("declare", {
  1958. startsExpr
  1959. }),
  1960. _enum: createKeywordLike("enum", {
  1961. startsExpr
  1962. }),
  1963. _module: createKeywordLike("module", {
  1964. startsExpr
  1965. }),
  1966. _namespace: createKeywordLike("namespace", {
  1967. startsExpr
  1968. }),
  1969. _interface: createKeywordLike("interface", {
  1970. startsExpr
  1971. }),
  1972. _type: createKeywordLike("type", {
  1973. startsExpr
  1974. }),
  1975. _opaque: createKeywordLike("opaque", {
  1976. startsExpr
  1977. }),
  1978. name: createToken("name", {
  1979. startsExpr
  1980. }),
  1981. string: createToken("string", {
  1982. startsExpr
  1983. }),
  1984. num: createToken("num", {
  1985. startsExpr
  1986. }),
  1987. bigint: createToken("bigint", {
  1988. startsExpr
  1989. }),
  1990. decimal: createToken("decimal", {
  1991. startsExpr
  1992. }),
  1993. regexp: createToken("regexp", {
  1994. startsExpr
  1995. }),
  1996. privateName: createToken("#name", {
  1997. startsExpr
  1998. }),
  1999. eof: createToken("eof"),
  2000. jsxName: createToken("jsxName"),
  2001. jsxText: createToken("jsxText", {
  2002. beforeExpr: true
  2003. }),
  2004. jsxTagStart: createToken("jsxTagStart", {
  2005. startsExpr: true
  2006. }),
  2007. jsxTagEnd: createToken("jsxTagEnd"),
  2008. placeholder: createToken("%%", {
  2009. startsExpr: true
  2010. })
  2011. };
  2012. function tokenIsIdentifier(token) {
  2013. return token >= 87 && token <= 122;
  2014. }
  2015. function tokenKeywordOrIdentifierIsKeyword(token) {
  2016. return token <= 86;
  2017. }
  2018. function tokenIsKeywordOrIdentifier(token) {
  2019. return token >= 52 && token <= 122;
  2020. }
  2021. function tokenIsLiteralPropertyName(token) {
  2022. return token >= 52 && token <= 126;
  2023. }
  2024. function tokenComesBeforeExpression(token) {
  2025. return tokenBeforeExprs[token];
  2026. }
  2027. function tokenCanStartExpression(token) {
  2028. return tokenStartsExprs[token];
  2029. }
  2030. function tokenIsAssignment(token) {
  2031. return token >= 27 && token <= 31;
  2032. }
  2033. function tokenIsFlowInterfaceOrTypeOrOpaque(token) {
  2034. return token >= 119 && token <= 121;
  2035. }
  2036. function tokenIsLoop(token) {
  2037. return token >= 84 && token <= 86;
  2038. }
  2039. function tokenIsKeyword(token) {
  2040. return token >= 52 && token <= 86;
  2041. }
  2042. function tokenIsOperator(token) {
  2043. return token >= 35 && token <= 53;
  2044. }
  2045. function tokenIsPostfix(token) {
  2046. return token === 32;
  2047. }
  2048. function tokenIsPrefix(token) {
  2049. return tokenPrefixes[token];
  2050. }
  2051. function tokenIsTSTypeOperator(token) {
  2052. return token >= 111 && token <= 113;
  2053. }
  2054. function tokenIsTSDeclarationStart(token) {
  2055. return token >= 114 && token <= 120;
  2056. }
  2057. function tokenLabelName(token) {
  2058. return tokenLabels[token];
  2059. }
  2060. function tokenOperatorPrecedence(token) {
  2061. return tokenBinops[token];
  2062. }
  2063. function tokenIsRightAssociative(token) {
  2064. return token === 51;
  2065. }
  2066. function getExportedToken(token) {
  2067. return tokenTypes[token];
  2068. }
  2069. function isTokenType(obj) {
  2070. return typeof obj === "number";
  2071. }
  2072. {
  2073. tokenTypes[8].updateContext = context => {
  2074. context.pop();
  2075. };
  2076. tokenTypes[5].updateContext = tokenTypes[7].updateContext = tokenTypes[23].updateContext = context => {
  2077. context.push(types.brace);
  2078. };
  2079. tokenTypes[22].updateContext = context => {
  2080. if (context[context.length - 1] === types.template) {
  2081. context.pop();
  2082. } else {
  2083. context.push(types.template);
  2084. }
  2085. };
  2086. tokenTypes[132].updateContext = context => {
  2087. context.push(types.j_expr, types.j_oTag);
  2088. };
  2089. }
  2090. 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";
  2091. 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";
  2092. const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  2093. const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  2094. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  2095. 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];
  2096. 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];
  2097. function isInAstralSet(code, set) {
  2098. let pos = 0x10000;
  2099. for (let i = 0, length = set.length; i < length; i += 2) {
  2100. pos += set[i];
  2101. if (pos > code) return false;
  2102. pos += set[i + 1];
  2103. if (pos >= code) return true;
  2104. }
  2105. return false;
  2106. }
  2107. function isIdentifierStart(code) {
  2108. if (code < 65) return code === 36;
  2109. if (code <= 90) return true;
  2110. if (code < 97) return code === 95;
  2111. if (code <= 122) return true;
  2112. if (code <= 0xffff) {
  2113. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  2114. }
  2115. return isInAstralSet(code, astralIdentifierStartCodes);
  2116. }
  2117. function isIdentifierChar(code) {
  2118. if (code < 48) return code === 36;
  2119. if (code < 58) return true;
  2120. if (code < 65) return false;
  2121. if (code <= 90) return true;
  2122. if (code < 97) return code === 95;
  2123. if (code <= 122) return true;
  2124. if (code <= 0xffff) {
  2125. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  2126. }
  2127. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
  2128. }
  2129. const reservedWords = {
  2130. 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"],
  2131. strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
  2132. strictBind: ["eval", "arguments"]
  2133. };
  2134. const keywords = new Set(reservedWords.keyword);
  2135. const reservedWordsStrictSet = new Set(reservedWords.strict);
  2136. const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
  2137. function isReservedWord(word, inModule) {
  2138. return inModule && word === "await" || word === "enum";
  2139. }
  2140. function isStrictReservedWord(word, inModule) {
  2141. return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
  2142. }
  2143. function isStrictBindOnlyReservedWord(word) {
  2144. return reservedWordsStrictBindSet.has(word);
  2145. }
  2146. function isStrictBindReservedWord(word, inModule) {
  2147. return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
  2148. }
  2149. function isKeyword(word) {
  2150. return keywords.has(word);
  2151. }
  2152. function isIteratorStart(current, next) {
  2153. return current === 64 && next === 64;
  2154. }
  2155. 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"]);
  2156. function canBeReservedWord(word) {
  2157. return reservedWordLikeSet.has(word);
  2158. }
  2159. const SCOPE_OTHER = 0b000000000,
  2160. SCOPE_PROGRAM = 0b000000001,
  2161. SCOPE_FUNCTION = 0b000000010,
  2162. SCOPE_ARROW = 0b000000100,
  2163. SCOPE_SIMPLE_CATCH = 0b000001000,
  2164. SCOPE_SUPER = 0b000010000,
  2165. SCOPE_DIRECT_SUPER = 0b000100000,
  2166. SCOPE_CLASS = 0b001000000,
  2167. SCOPE_STATIC_BLOCK = 0b010000000,
  2168. SCOPE_TS_MODULE = 0b100000000,
  2169. SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION | SCOPE_TS_MODULE;
  2170. const BIND_KIND_VALUE = 0b000000000001,
  2171. BIND_KIND_TYPE = 0b000000000010,
  2172. BIND_SCOPE_VAR = 0b000000000100,
  2173. BIND_SCOPE_LEXICAL = 0b000000001000,
  2174. BIND_SCOPE_FUNCTION = 0b000000010000,
  2175. BIND_FLAGS_NONE = 0b000001000000,
  2176. BIND_FLAGS_CLASS = 0b000010000000,
  2177. BIND_FLAGS_TS_ENUM = 0b000100000000,
  2178. BIND_FLAGS_TS_CONST_ENUM = 0b001000000000,
  2179. BIND_FLAGS_TS_EXPORT_ONLY = 0b010000000000,
  2180. BIND_FLAGS_FLOW_DECLARE_FN = 0b100000000000;
  2181. const BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS,
  2182. BIND_LEXICAL = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0,
  2183. BIND_VAR = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0,
  2184. BIND_FUNCTION = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0,
  2185. BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS,
  2186. BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0,
  2187. BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM,
  2188. BIND_TS_AMBIENT = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
  2189. BIND_NONE = 0 | 0 | 0 | BIND_FLAGS_NONE,
  2190. BIND_OUTSIDE = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE,
  2191. BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM,
  2192. BIND_TS_NAMESPACE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
  2193. BIND_FLOW_DECLARE_FN = BIND_FLAGS_FLOW_DECLARE_FN;
  2194. const CLASS_ELEMENT_FLAG_STATIC = 0b100,
  2195. CLASS_ELEMENT_KIND_GETTER = 0b010,
  2196. CLASS_ELEMENT_KIND_SETTER = 0b001,
  2197. CLASS_ELEMENT_KIND_ACCESSOR = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_KIND_SETTER;
  2198. const CLASS_ELEMENT_STATIC_GETTER = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_FLAG_STATIC,
  2199. CLASS_ELEMENT_STATIC_SETTER = CLASS_ELEMENT_KIND_SETTER | CLASS_ELEMENT_FLAG_STATIC,
  2200. CLASS_ELEMENT_INSTANCE_GETTER = CLASS_ELEMENT_KIND_GETTER,
  2201. CLASS_ELEMENT_INSTANCE_SETTER = CLASS_ELEMENT_KIND_SETTER,
  2202. CLASS_ELEMENT_OTHER = 0;
  2203. class Scope {
  2204. constructor(flags) {
  2205. this.var = new Set();
  2206. this.lexical = new Set();
  2207. this.functions = new Set();
  2208. this.flags = flags;
  2209. }
  2210. }
  2211. class ScopeHandler {
  2212. constructor(raise, inModule) {
  2213. this.scopeStack = [];
  2214. this.undefinedExports = new Map();
  2215. this.undefinedPrivateNames = new Map();
  2216. this.raise = raise;
  2217. this.inModule = inModule;
  2218. }
  2219. get inFunction() {
  2220. return (this.currentVarScopeFlags() & SCOPE_FUNCTION) > 0;
  2221. }
  2222. get allowSuper() {
  2223. return (this.currentThisScopeFlags() & SCOPE_SUPER) > 0;
  2224. }
  2225. get allowDirectSuper() {
  2226. return (this.currentThisScopeFlags() & SCOPE_DIRECT_SUPER) > 0;
  2227. }
  2228. get inClass() {
  2229. return (this.currentThisScopeFlags() & SCOPE_CLASS) > 0;
  2230. }
  2231. get inClassAndNotInNonArrowFunction() {
  2232. const flags = this.currentThisScopeFlags();
  2233. return (flags & SCOPE_CLASS) > 0 && (flags & SCOPE_FUNCTION) === 0;
  2234. }
  2235. get inStaticBlock() {
  2236. for (let i = this.scopeStack.length - 1;; i--) {
  2237. const {
  2238. flags
  2239. } = this.scopeStack[i];
  2240. if (flags & SCOPE_STATIC_BLOCK) {
  2241. return true;
  2242. }
  2243. if (flags & (SCOPE_VAR | SCOPE_CLASS)) {
  2244. return false;
  2245. }
  2246. }
  2247. }
  2248. get inNonArrowFunction() {
  2249. return (this.currentThisScopeFlags() & SCOPE_FUNCTION) > 0;
  2250. }
  2251. get treatFunctionsAsVar() {
  2252. return this.treatFunctionsAsVarInScope(this.currentScope());
  2253. }
  2254. createScope(flags) {
  2255. return new Scope(flags);
  2256. }
  2257. enter(flags) {
  2258. this.scopeStack.push(this.createScope(flags));
  2259. }
  2260. exit() {
  2261. this.scopeStack.pop();
  2262. }
  2263. treatFunctionsAsVarInScope(scope) {
  2264. return !!(scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_PROGRAM);
  2265. }
  2266. declareName(name, bindingType, pos) {
  2267. let scope = this.currentScope();
  2268. if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) {
  2269. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  2270. if (bindingType & BIND_SCOPE_FUNCTION) {
  2271. scope.functions.add(name);
  2272. } else {
  2273. scope.lexical.add(name);
  2274. }
  2275. if (bindingType & BIND_SCOPE_LEXICAL) {
  2276. this.maybeExportDefined(scope, name);
  2277. }
  2278. } else if (bindingType & BIND_SCOPE_VAR) {
  2279. for (let i = this.scopeStack.length - 1; i >= 0; --i) {
  2280. scope = this.scopeStack[i];
  2281. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  2282. scope.var.add(name);
  2283. this.maybeExportDefined(scope, name);
  2284. if (scope.flags & SCOPE_VAR) break;
  2285. }
  2286. }
  2287. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  2288. this.undefinedExports.delete(name);
  2289. }
  2290. }
  2291. maybeExportDefined(scope, name) {
  2292. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  2293. this.undefinedExports.delete(name);
  2294. }
  2295. }
  2296. checkRedeclarationInScope(scope, name, bindingType, pos) {
  2297. if (this.isRedeclaredInScope(scope, name, bindingType)) {
  2298. this.raise(pos, ErrorMessages.VarRedeclaration, name);
  2299. }
  2300. }
  2301. isRedeclaredInScope(scope, name, bindingType) {
  2302. if (!(bindingType & BIND_KIND_VALUE)) return false;
  2303. if (bindingType & BIND_SCOPE_LEXICAL) {
  2304. return scope.lexical.has(name) || scope.functions.has(name) || scope.var.has(name);
  2305. }
  2306. if (bindingType & BIND_SCOPE_FUNCTION) {
  2307. return scope.lexical.has(name) || !this.treatFunctionsAsVarInScope(scope) && scope.var.has(name);
  2308. }
  2309. return scope.lexical.has(name) && !(scope.flags & SCOPE_SIMPLE_CATCH && scope.lexical.values().next().value === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.has(name);
  2310. }
  2311. checkLocalExport(id) {
  2312. const {
  2313. name
  2314. } = id;
  2315. const topLevelScope = this.scopeStack[0];
  2316. if (!topLevelScope.lexical.has(name) && !topLevelScope.var.has(name) && !topLevelScope.functions.has(name)) {
  2317. this.undefinedExports.set(name, id.start);
  2318. }
  2319. }
  2320. currentScope() {
  2321. return this.scopeStack[this.scopeStack.length - 1];
  2322. }
  2323. currentVarScopeFlags() {
  2324. for (let i = this.scopeStack.length - 1;; i--) {
  2325. const {
  2326. flags
  2327. } = this.scopeStack[i];
  2328. if (flags & SCOPE_VAR) {
  2329. return flags;
  2330. }
  2331. }
  2332. }
  2333. currentThisScopeFlags() {
  2334. for (let i = this.scopeStack.length - 1;; i--) {
  2335. const {
  2336. flags
  2337. } = this.scopeStack[i];
  2338. if (flags & (SCOPE_VAR | SCOPE_CLASS) && !(flags & SCOPE_ARROW)) {
  2339. return flags;
  2340. }
  2341. }
  2342. }
  2343. }
  2344. class FlowScope extends Scope {
  2345. constructor(...args) {
  2346. super(...args);
  2347. this.declareFunctions = new Set();
  2348. }
  2349. }
  2350. class FlowScopeHandler extends ScopeHandler {
  2351. createScope(flags) {
  2352. return new FlowScope(flags);
  2353. }
  2354. declareName(name, bindingType, pos) {
  2355. const scope = this.currentScope();
  2356. if (bindingType & BIND_FLAGS_FLOW_DECLARE_FN) {
  2357. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  2358. this.maybeExportDefined(scope, name);
  2359. scope.declareFunctions.add(name);
  2360. return;
  2361. }
  2362. super.declareName(...arguments);
  2363. }
  2364. isRedeclaredInScope(scope, name, bindingType) {
  2365. if (super.isRedeclaredInScope(...arguments)) return true;
  2366. if (bindingType & BIND_FLAGS_FLOW_DECLARE_FN) {
  2367. return !scope.declareFunctions.has(name) && (scope.lexical.has(name) || scope.functions.has(name));
  2368. }
  2369. return false;
  2370. }
  2371. checkLocalExport(id) {
  2372. if (!this.scopeStack[0].declareFunctions.has(id.name)) {
  2373. super.checkLocalExport(id);
  2374. }
  2375. }
  2376. }
  2377. class State {
  2378. constructor() {
  2379. this.strict = void 0;
  2380. this.curLine = void 0;
  2381. this.lineStart = void 0;
  2382. this.startLoc = void 0;
  2383. this.endLoc = void 0;
  2384. this.errors = [];
  2385. this.potentialArrowAt = -1;
  2386. this.noArrowAt = [];
  2387. this.noArrowParamsConversionAt = [];
  2388. this.maybeInArrowParameters = false;
  2389. this.inType = false;
  2390. this.noAnonFunctionType = false;
  2391. this.hasFlowComment = false;
  2392. this.isAmbientContext = false;
  2393. this.inAbstractClass = false;
  2394. this.topicContext = {
  2395. maxNumOfResolvableTopics: 0,
  2396. maxTopicIndex: null
  2397. };
  2398. this.soloAwait = false;
  2399. this.inFSharpPipelineDirectBody = false;
  2400. this.labels = [];
  2401. this.decoratorStack = [[]];
  2402. this.comments = [];
  2403. this.commentStack = [];
  2404. this.pos = 0;
  2405. this.type = 129;
  2406. this.value = null;
  2407. this.start = 0;
  2408. this.end = 0;
  2409. this.lastTokEndLoc = null;
  2410. this.lastTokStartLoc = null;
  2411. this.lastTokStart = 0;
  2412. this.lastTokEnd = 0;
  2413. this.context = [types.brace];
  2414. this.canStartJSXElement = true;
  2415. this.containsEsc = false;
  2416. this.strictErrors = new Map();
  2417. this.tokensLength = 0;
  2418. }
  2419. init({
  2420. strictMode,
  2421. sourceType,
  2422. startLine,
  2423. startColumn
  2424. }) {
  2425. this.strict = strictMode === false ? false : strictMode === true ? true : sourceType === "module";
  2426. this.curLine = startLine;
  2427. this.lineStart = -startColumn;
  2428. this.startLoc = this.endLoc = new Position(startLine, startColumn);
  2429. }
  2430. curPosition() {
  2431. return new Position(this.curLine, this.pos - this.lineStart);
  2432. }
  2433. clone(skipArrays) {
  2434. const state = new State();
  2435. const keys = Object.keys(this);
  2436. for (let i = 0, length = keys.length; i < length; i++) {
  2437. const key = keys[i];
  2438. let val = this[key];
  2439. if (!skipArrays && Array.isArray(val)) {
  2440. val = val.slice();
  2441. }
  2442. state[key] = val;
  2443. }
  2444. return state;
  2445. }
  2446. }
  2447. var _isDigit = function isDigit(code) {
  2448. return code >= 48 && code <= 57;
  2449. };
  2450. const VALID_REGEX_FLAGS = new Set([103, 109, 115, 105, 121, 117, 100]);
  2451. const forbiddenNumericSeparatorSiblings = {
  2452. decBinOct: [46, 66, 69, 79, 95, 98, 101, 111],
  2453. hex: [46, 88, 95, 120]
  2454. };
  2455. const allowedNumericSeparatorSiblings = {};
  2456. allowedNumericSeparatorSiblings.bin = [48, 49];
  2457. allowedNumericSeparatorSiblings.oct = [...allowedNumericSeparatorSiblings.bin, 50, 51, 52, 53, 54, 55];
  2458. allowedNumericSeparatorSiblings.dec = [...allowedNumericSeparatorSiblings.oct, 56, 57];
  2459. allowedNumericSeparatorSiblings.hex = [...allowedNumericSeparatorSiblings.dec, 65, 66, 67, 68, 69, 70, 97, 98, 99, 100, 101, 102];
  2460. class Token {
  2461. constructor(state) {
  2462. this.type = state.type;
  2463. this.value = state.value;
  2464. this.start = state.start;
  2465. this.end = state.end;
  2466. this.loc = new SourceLocation(state.startLoc, state.endLoc);
  2467. }
  2468. }
  2469. class Tokenizer extends ParserError {
  2470. constructor(options, input) {
  2471. super();
  2472. this.isLookahead = void 0;
  2473. this.tokens = [];
  2474. this.state = new State();
  2475. this.state.init(options);
  2476. this.input = input;
  2477. this.length = input.length;
  2478. this.isLookahead = false;
  2479. }
  2480. pushToken(token) {
  2481. this.tokens.length = this.state.tokensLength;
  2482. this.tokens.push(token);
  2483. ++this.state.tokensLength;
  2484. }
  2485. next() {
  2486. this.checkKeywordEscapes();
  2487. if (this.options.tokens) {
  2488. this.pushToken(new Token(this.state));
  2489. }
  2490. this.state.lastTokEnd = this.state.end;
  2491. this.state.lastTokStart = this.state.start;
  2492. this.state.lastTokEndLoc = this.state.endLoc;
  2493. this.state.lastTokStartLoc = this.state.startLoc;
  2494. this.nextToken();
  2495. }
  2496. eat(type) {
  2497. if (this.match(type)) {
  2498. this.next();
  2499. return true;
  2500. } else {
  2501. return false;
  2502. }
  2503. }
  2504. match(type) {
  2505. return this.state.type === type;
  2506. }
  2507. createLookaheadState(state) {
  2508. return {
  2509. pos: state.pos,
  2510. value: null,
  2511. type: state.type,
  2512. start: state.start,
  2513. end: state.end,
  2514. lastTokEnd: state.end,
  2515. context: [this.curContext()],
  2516. inType: state.inType
  2517. };
  2518. }
  2519. lookahead() {
  2520. const old = this.state;
  2521. this.state = this.createLookaheadState(old);
  2522. this.isLookahead = true;
  2523. this.nextToken();
  2524. this.isLookahead = false;
  2525. const curr = this.state;
  2526. this.state = old;
  2527. return curr;
  2528. }
  2529. nextTokenStart() {
  2530. return this.nextTokenStartSince(this.state.pos);
  2531. }
  2532. nextTokenStartSince(pos) {
  2533. skipWhiteSpace.lastIndex = pos;
  2534. return skipWhiteSpace.test(this.input) ? skipWhiteSpace.lastIndex : pos;
  2535. }
  2536. lookaheadCharCode() {
  2537. return this.input.charCodeAt(this.nextTokenStart());
  2538. }
  2539. codePointAtPos(pos) {
  2540. let cp = this.input.charCodeAt(pos);
  2541. if ((cp & 0xfc00) === 0xd800 && ++pos < this.input.length) {
  2542. const trail = this.input.charCodeAt(pos);
  2543. if ((trail & 0xfc00) === 0xdc00) {
  2544. cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);
  2545. }
  2546. }
  2547. return cp;
  2548. }
  2549. setStrict(strict) {
  2550. this.state.strict = strict;
  2551. if (strict) {
  2552. this.state.strictErrors.forEach((message, pos) => this.raise(pos, message));
  2553. this.state.strictErrors.clear();
  2554. }
  2555. }
  2556. curContext() {
  2557. return this.state.context[this.state.context.length - 1];
  2558. }
  2559. nextToken() {
  2560. const curContext = this.curContext();
  2561. if (!curContext.preserveSpace) this.skipSpace();
  2562. this.state.start = this.state.pos;
  2563. if (!this.isLookahead) this.state.startLoc = this.state.curPosition();
  2564. if (this.state.pos >= this.length) {
  2565. this.finishToken(129);
  2566. return;
  2567. }
  2568. if (curContext === types.template) {
  2569. this.readTmplToken();
  2570. } else {
  2571. this.getTokenFromCode(this.codePointAtPos(this.state.pos));
  2572. }
  2573. }
  2574. skipBlockComment() {
  2575. let startLoc;
  2576. if (!this.isLookahead) startLoc = this.state.curPosition();
  2577. const start = this.state.pos;
  2578. const end = this.input.indexOf("*/", start + 2);
  2579. if (end === -1) throw this.raise(start, ErrorMessages.UnterminatedComment);
  2580. this.state.pos = end + 2;
  2581. lineBreakG.lastIndex = start + 2;
  2582. while (lineBreakG.test(this.input) && lineBreakG.lastIndex <= end) {
  2583. ++this.state.curLine;
  2584. this.state.lineStart = lineBreakG.lastIndex;
  2585. }
  2586. if (this.isLookahead) return;
  2587. const comment = {
  2588. type: "CommentBlock",
  2589. value: this.input.slice(start + 2, end),
  2590. start,
  2591. end: end + 2,
  2592. loc: new SourceLocation(startLoc, this.state.curPosition())
  2593. };
  2594. if (this.options.tokens) this.pushToken(comment);
  2595. return comment;
  2596. }
  2597. skipLineComment(startSkip) {
  2598. const start = this.state.pos;
  2599. let startLoc;
  2600. if (!this.isLookahead) startLoc = this.state.curPosition();
  2601. let ch = this.input.charCodeAt(this.state.pos += startSkip);
  2602. if (this.state.pos < this.length) {
  2603. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  2604. ch = this.input.charCodeAt(this.state.pos);
  2605. }
  2606. }
  2607. if (this.isLookahead) return;
  2608. const end = this.state.pos;
  2609. const value = this.input.slice(start + startSkip, end);
  2610. const comment = {
  2611. type: "CommentLine",
  2612. value,
  2613. start,
  2614. end,
  2615. loc: new SourceLocation(startLoc, this.state.curPosition())
  2616. };
  2617. if (this.options.tokens) this.pushToken(comment);
  2618. return comment;
  2619. }
  2620. skipSpace() {
  2621. const spaceStart = this.state.pos;
  2622. const comments = [];
  2623. loop: while (this.state.pos < this.length) {
  2624. const ch = this.input.charCodeAt(this.state.pos);
  2625. switch (ch) {
  2626. case 32:
  2627. case 160:
  2628. case 9:
  2629. ++this.state.pos;
  2630. break;
  2631. case 13:
  2632. if (this.input.charCodeAt(this.state.pos + 1) === 10) {
  2633. ++this.state.pos;
  2634. }
  2635. case 10:
  2636. case 8232:
  2637. case 8233:
  2638. ++this.state.pos;
  2639. ++this.state.curLine;
  2640. this.state.lineStart = this.state.pos;
  2641. break;
  2642. case 47:
  2643. switch (this.input.charCodeAt(this.state.pos + 1)) {
  2644. case 42:
  2645. {
  2646. const comment = this.skipBlockComment();
  2647. if (comment !== undefined) {
  2648. this.addComment(comment);
  2649. if (this.options.attachComment) comments.push(comment);
  2650. }
  2651. break;
  2652. }
  2653. case 47:
  2654. {
  2655. const comment = this.skipLineComment(2);
  2656. if (comment !== undefined) {
  2657. this.addComment(comment);
  2658. if (this.options.attachComment) comments.push(comment);
  2659. }
  2660. break;
  2661. }
  2662. default:
  2663. break loop;
  2664. }
  2665. break;
  2666. default:
  2667. if (isWhitespace(ch)) {
  2668. ++this.state.pos;
  2669. } else if (ch === 45 && !this.inModule) {
  2670. const pos = this.state.pos;
  2671. if (this.input.charCodeAt(pos + 1) === 45 && this.input.charCodeAt(pos + 2) === 62 && (spaceStart === 0 || this.state.lineStart > spaceStart)) {
  2672. const comment = this.skipLineComment(3);
  2673. if (comment !== undefined) {
  2674. this.addComment(comment);
  2675. if (this.options.attachComment) comments.push(comment);
  2676. }
  2677. } else {
  2678. break loop;
  2679. }
  2680. } else if (ch === 60 && !this.inModule) {
  2681. const pos = this.state.pos;
  2682. if (this.input.charCodeAt(pos + 1) === 33 && this.input.charCodeAt(pos + 2) === 45 && this.input.charCodeAt(pos + 3) === 45) {
  2683. const comment = this.skipLineComment(4);
  2684. if (comment !== undefined) {
  2685. this.addComment(comment);
  2686. if (this.options.attachComment) comments.push(comment);
  2687. }
  2688. } else {
  2689. break loop;
  2690. }
  2691. } else {
  2692. break loop;
  2693. }
  2694. }
  2695. }
  2696. if (comments.length > 0) {
  2697. const end = this.state.pos;
  2698. const CommentWhitespace = {
  2699. start: spaceStart,
  2700. end,
  2701. comments,
  2702. leadingNode: null,
  2703. trailingNode: null,
  2704. containingNode: null
  2705. };
  2706. this.state.commentStack.push(CommentWhitespace);
  2707. }
  2708. }
  2709. finishToken(type, val) {
  2710. this.state.end = this.state.pos;
  2711. const prevType = this.state.type;
  2712. this.state.type = type;
  2713. this.state.value = val;
  2714. if (!this.isLookahead) {
  2715. this.state.endLoc = this.state.curPosition();
  2716. this.updateContext(prevType);
  2717. }
  2718. }
  2719. replaceToken(type) {
  2720. this.state.type = type;
  2721. this.updateContext();
  2722. }
  2723. readToken_numberSign() {
  2724. if (this.state.pos === 0 && this.readToken_interpreter()) {
  2725. return;
  2726. }
  2727. const nextPos = this.state.pos + 1;
  2728. const next = this.codePointAtPos(nextPos);
  2729. if (next >= 48 && next <= 57) {
  2730. throw this.raise(this.state.pos, ErrorMessages.UnexpectedDigitAfterHash);
  2731. }
  2732. if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) {
  2733. this.expectPlugin("recordAndTuple");
  2734. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "hash") {
  2735. throw this.raise(this.state.pos, next === 123 ? ErrorMessages.RecordExpressionHashIncorrectStartSyntaxType : ErrorMessages.TupleExpressionHashIncorrectStartSyntaxType);
  2736. }
  2737. this.state.pos += 2;
  2738. if (next === 123) {
  2739. this.finishToken(7);
  2740. } else {
  2741. this.finishToken(1);
  2742. }
  2743. } else if (isIdentifierStart(next)) {
  2744. ++this.state.pos;
  2745. this.finishToken(128, this.readWord1(next));
  2746. } else if (next === 92) {
  2747. ++this.state.pos;
  2748. this.finishToken(128, this.readWord1());
  2749. } else {
  2750. this.finishOp(25, 1);
  2751. }
  2752. }
  2753. readToken_dot() {
  2754. const next = this.input.charCodeAt(this.state.pos + 1);
  2755. if (next >= 48 && next <= 57) {
  2756. this.readNumber(true);
  2757. return;
  2758. }
  2759. if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) {
  2760. this.state.pos += 3;
  2761. this.finishToken(21);
  2762. } else {
  2763. ++this.state.pos;
  2764. this.finishToken(16);
  2765. }
  2766. }
  2767. readToken_slash() {
  2768. const next = this.input.charCodeAt(this.state.pos + 1);
  2769. if (next === 61) {
  2770. this.finishOp(29, 2);
  2771. } else {
  2772. this.finishOp(50, 1);
  2773. }
  2774. }
  2775. readToken_interpreter() {
  2776. if (this.state.pos !== 0 || this.length < 2) return false;
  2777. let ch = this.input.charCodeAt(this.state.pos + 1);
  2778. if (ch !== 33) return false;
  2779. const start = this.state.pos;
  2780. this.state.pos += 1;
  2781. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  2782. ch = this.input.charCodeAt(this.state.pos);
  2783. }
  2784. const value = this.input.slice(start + 2, this.state.pos);
  2785. this.finishToken(26, value);
  2786. return true;
  2787. }
  2788. readToken_mult_modulo(code) {
  2789. let type = code === 42 ? 49 : 48;
  2790. let width = 1;
  2791. let next = this.input.charCodeAt(this.state.pos + 1);
  2792. if (code === 42 && next === 42) {
  2793. width++;
  2794. next = this.input.charCodeAt(this.state.pos + 2);
  2795. type = 51;
  2796. }
  2797. if (next === 61 && !this.state.inType) {
  2798. width++;
  2799. type = code === 37 ? 31 : 28;
  2800. }
  2801. this.finishOp(type, width);
  2802. }
  2803. readToken_pipe_amp(code) {
  2804. const next = this.input.charCodeAt(this.state.pos + 1);
  2805. if (next === code) {
  2806. if (this.input.charCodeAt(this.state.pos + 2) === 61) {
  2807. this.finishOp(28, 3);
  2808. } else {
  2809. this.finishOp(code === 124 ? 37 : 38, 2);
  2810. }
  2811. return;
  2812. }
  2813. if (code === 124) {
  2814. if (next === 62) {
  2815. this.finishOp(35, 2);
  2816. return;
  2817. }
  2818. if (this.hasPlugin("recordAndTuple") && next === 125) {
  2819. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2820. throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectEndSyntaxType);
  2821. }
  2822. this.state.pos += 2;
  2823. this.finishToken(9);
  2824. return;
  2825. }
  2826. if (this.hasPlugin("recordAndTuple") && next === 93) {
  2827. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2828. throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectEndSyntaxType);
  2829. }
  2830. this.state.pos += 2;
  2831. this.finishToken(4);
  2832. return;
  2833. }
  2834. }
  2835. if (next === 61) {
  2836. this.finishOp(28, 2);
  2837. return;
  2838. }
  2839. this.finishOp(code === 124 ? 39 : 41, 1);
  2840. }
  2841. readToken_caret() {
  2842. const next = this.input.charCodeAt(this.state.pos + 1);
  2843. if (next === 61 && !this.state.inType) {
  2844. this.finishOp(30, 2);
  2845. } else {
  2846. this.finishOp(40, 1);
  2847. }
  2848. }
  2849. readToken_plus_min(code) {
  2850. const next = this.input.charCodeAt(this.state.pos + 1);
  2851. if (next === code) {
  2852. this.finishOp(32, 2);
  2853. return;
  2854. }
  2855. if (next === 61) {
  2856. this.finishOp(28, 2);
  2857. } else {
  2858. this.finishOp(47, 1);
  2859. }
  2860. }
  2861. readToken_lt() {
  2862. const {
  2863. pos
  2864. } = this.state;
  2865. const next = this.input.charCodeAt(pos + 1);
  2866. if (next === 60) {
  2867. if (this.input.charCodeAt(pos + 2) === 61) {
  2868. this.finishOp(28, 3);
  2869. return;
  2870. }
  2871. this.finishOp(46, 2);
  2872. return;
  2873. }
  2874. if (next === 61) {
  2875. this.finishOp(45, 2);
  2876. return;
  2877. }
  2878. this.finishOp(43, 1);
  2879. }
  2880. readToken_gt() {
  2881. const {
  2882. pos
  2883. } = this.state;
  2884. const next = this.input.charCodeAt(pos + 1);
  2885. if (next === 62) {
  2886. const size = this.input.charCodeAt(pos + 2) === 62 ? 3 : 2;
  2887. if (this.input.charCodeAt(pos + size) === 61) {
  2888. this.finishOp(28, size + 1);
  2889. return;
  2890. }
  2891. this.finishOp(46, size);
  2892. return;
  2893. }
  2894. if (next === 61) {
  2895. this.finishOp(45, 2);
  2896. return;
  2897. }
  2898. this.finishOp(44, 1);
  2899. }
  2900. readToken_eq_excl(code) {
  2901. const next = this.input.charCodeAt(this.state.pos + 1);
  2902. if (next === 61) {
  2903. this.finishOp(42, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
  2904. return;
  2905. }
  2906. if (code === 61 && next === 62) {
  2907. this.state.pos += 2;
  2908. this.finishToken(19);
  2909. return;
  2910. }
  2911. this.finishOp(code === 61 ? 27 : 33, 1);
  2912. }
  2913. readToken_question() {
  2914. const next = this.input.charCodeAt(this.state.pos + 1);
  2915. const next2 = this.input.charCodeAt(this.state.pos + 2);
  2916. if (next === 63) {
  2917. if (next2 === 61) {
  2918. this.finishOp(28, 3);
  2919. } else {
  2920. this.finishOp(36, 2);
  2921. }
  2922. } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) {
  2923. this.state.pos += 2;
  2924. this.finishToken(18);
  2925. } else {
  2926. ++this.state.pos;
  2927. this.finishToken(17);
  2928. }
  2929. }
  2930. getTokenFromCode(code) {
  2931. switch (code) {
  2932. case 46:
  2933. this.readToken_dot();
  2934. return;
  2935. case 40:
  2936. ++this.state.pos;
  2937. this.finishToken(10);
  2938. return;
  2939. case 41:
  2940. ++this.state.pos;
  2941. this.finishToken(11);
  2942. return;
  2943. case 59:
  2944. ++this.state.pos;
  2945. this.finishToken(13);
  2946. return;
  2947. case 44:
  2948. ++this.state.pos;
  2949. this.finishToken(12);
  2950. return;
  2951. case 91:
  2952. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  2953. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2954. throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectStartSyntaxType);
  2955. }
  2956. this.state.pos += 2;
  2957. this.finishToken(2);
  2958. } else {
  2959. ++this.state.pos;
  2960. this.finishToken(0);
  2961. }
  2962. return;
  2963. case 93:
  2964. ++this.state.pos;
  2965. this.finishToken(3);
  2966. return;
  2967. case 123:
  2968. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  2969. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2970. throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectStartSyntaxType);
  2971. }
  2972. this.state.pos += 2;
  2973. this.finishToken(6);
  2974. } else {
  2975. ++this.state.pos;
  2976. this.finishToken(5);
  2977. }
  2978. return;
  2979. case 125:
  2980. ++this.state.pos;
  2981. this.finishToken(8);
  2982. return;
  2983. case 58:
  2984. if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
  2985. this.finishOp(15, 2);
  2986. } else {
  2987. ++this.state.pos;
  2988. this.finishToken(14);
  2989. }
  2990. return;
  2991. case 63:
  2992. this.readToken_question();
  2993. return;
  2994. case 96:
  2995. ++this.state.pos;
  2996. this.finishToken(22);
  2997. return;
  2998. case 48:
  2999. {
  3000. const next = this.input.charCodeAt(this.state.pos + 1);
  3001. if (next === 120 || next === 88) {
  3002. this.readRadixNumber(16);
  3003. return;
  3004. }
  3005. if (next === 111 || next === 79) {
  3006. this.readRadixNumber(8);
  3007. return;
  3008. }
  3009. if (next === 98 || next === 66) {
  3010. this.readRadixNumber(2);
  3011. return;
  3012. }
  3013. }
  3014. case 49:
  3015. case 50:
  3016. case 51:
  3017. case 52:
  3018. case 53:
  3019. case 54:
  3020. case 55:
  3021. case 56:
  3022. case 57:
  3023. this.readNumber(false);
  3024. return;
  3025. case 34:
  3026. case 39:
  3027. this.readString(code);
  3028. return;
  3029. case 47:
  3030. this.readToken_slash();
  3031. return;
  3032. case 37:
  3033. case 42:
  3034. this.readToken_mult_modulo(code);
  3035. return;
  3036. case 124:
  3037. case 38:
  3038. this.readToken_pipe_amp(code);
  3039. return;
  3040. case 94:
  3041. this.readToken_caret();
  3042. return;
  3043. case 43:
  3044. case 45:
  3045. this.readToken_plus_min(code);
  3046. return;
  3047. case 60:
  3048. this.readToken_lt();
  3049. return;
  3050. case 62:
  3051. this.readToken_gt();
  3052. return;
  3053. case 61:
  3054. case 33:
  3055. this.readToken_eq_excl(code);
  3056. return;
  3057. case 126:
  3058. this.finishOp(34, 1);
  3059. return;
  3060. case 64:
  3061. ++this.state.pos;
  3062. this.finishToken(24);
  3063. return;
  3064. case 35:
  3065. this.readToken_numberSign();
  3066. return;
  3067. case 92:
  3068. this.readWord();
  3069. return;
  3070. default:
  3071. if (isIdentifierStart(code)) {
  3072. this.readWord(code);
  3073. return;
  3074. }
  3075. }
  3076. throw this.raise(this.state.pos, ErrorMessages.InvalidOrUnexpectedToken, String.fromCodePoint(code));
  3077. }
  3078. finishOp(type, size) {
  3079. const str = this.input.slice(this.state.pos, this.state.pos + size);
  3080. this.state.pos += size;
  3081. this.finishToken(type, str);
  3082. }
  3083. readRegexp() {
  3084. const start = this.state.start + 1;
  3085. let escaped, inClass;
  3086. let {
  3087. pos
  3088. } = this.state;
  3089. for (;; ++pos) {
  3090. if (pos >= this.length) {
  3091. throw this.raise(start, ErrorMessages.UnterminatedRegExp);
  3092. }
  3093. const ch = this.input.charCodeAt(pos);
  3094. if (isNewLine(ch)) {
  3095. throw this.raise(start, ErrorMessages.UnterminatedRegExp);
  3096. }
  3097. if (escaped) {
  3098. escaped = false;
  3099. } else {
  3100. if (ch === 91) {
  3101. inClass = true;
  3102. } else if (ch === 93 && inClass) {
  3103. inClass = false;
  3104. } else if (ch === 47 && !inClass) {
  3105. break;
  3106. }
  3107. escaped = ch === 92;
  3108. }
  3109. }
  3110. const content = this.input.slice(start, pos);
  3111. ++pos;
  3112. let mods = "";
  3113. while (pos < this.length) {
  3114. const cp = this.codePointAtPos(pos);
  3115. const char = String.fromCharCode(cp);
  3116. if (VALID_REGEX_FLAGS.has(cp)) {
  3117. if (mods.includes(char)) {
  3118. this.raise(pos + 1, ErrorMessages.DuplicateRegExpFlags);
  3119. }
  3120. } else if (isIdentifierChar(cp) || cp === 92) {
  3121. this.raise(pos + 1, ErrorMessages.MalformedRegExpFlags);
  3122. } else {
  3123. break;
  3124. }
  3125. ++pos;
  3126. mods += char;
  3127. }
  3128. this.state.pos = pos;
  3129. this.finishToken(127, {
  3130. pattern: content,
  3131. flags: mods
  3132. });
  3133. }
  3134. readInt(radix, len, forceLen, allowNumSeparator = true) {
  3135. const start = this.state.pos;
  3136. const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct;
  3137. const allowedSiblings = radix === 16 ? allowedNumericSeparatorSiblings.hex : radix === 10 ? allowedNumericSeparatorSiblings.dec : radix === 8 ? allowedNumericSeparatorSiblings.oct : allowedNumericSeparatorSiblings.bin;
  3138. let invalid = false;
  3139. let total = 0;
  3140. for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  3141. const code = this.input.charCodeAt(this.state.pos);
  3142. let val;
  3143. if (code === 95) {
  3144. const prev = this.input.charCodeAt(this.state.pos - 1);
  3145. const next = this.input.charCodeAt(this.state.pos + 1);
  3146. if (allowedSiblings.indexOf(next) === -1) {
  3147. this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator);
  3148. } else if (forbiddenSiblings.indexOf(prev) > -1 || forbiddenSiblings.indexOf(next) > -1 || Number.isNaN(next)) {
  3149. this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator);
  3150. }
  3151. if (!allowNumSeparator) {
  3152. this.raise(this.state.pos, ErrorMessages.NumericSeparatorInEscapeSequence);
  3153. }
  3154. ++this.state.pos;
  3155. continue;
  3156. }
  3157. if (code >= 97) {
  3158. val = code - 97 + 10;
  3159. } else if (code >= 65) {
  3160. val = code - 65 + 10;
  3161. } else if (_isDigit(code)) {
  3162. val = code - 48;
  3163. } else {
  3164. val = Infinity;
  3165. }
  3166. if (val >= radix) {
  3167. if (this.options.errorRecovery && val <= 9) {
  3168. val = 0;
  3169. this.raise(this.state.start + i + 2, ErrorMessages.InvalidDigit, radix);
  3170. } else if (forceLen) {
  3171. val = 0;
  3172. invalid = true;
  3173. } else {
  3174. break;
  3175. }
  3176. }
  3177. ++this.state.pos;
  3178. total = total * radix + val;
  3179. }
  3180. if (this.state.pos === start || len != null && this.state.pos - start !== len || invalid) {
  3181. return null;
  3182. }
  3183. return total;
  3184. }
  3185. readRadixNumber(radix) {
  3186. const start = this.state.pos;
  3187. let isBigInt = false;
  3188. this.state.pos += 2;
  3189. const val = this.readInt(radix);
  3190. if (val == null) {
  3191. this.raise(this.state.start + 2, ErrorMessages.InvalidDigit, radix);
  3192. }
  3193. const next = this.input.charCodeAt(this.state.pos);
  3194. if (next === 110) {
  3195. ++this.state.pos;
  3196. isBigInt = true;
  3197. } else if (next === 109) {
  3198. throw this.raise(start, ErrorMessages.InvalidDecimal);
  3199. }
  3200. if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {
  3201. throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier);
  3202. }
  3203. if (isBigInt) {
  3204. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  3205. this.finishToken(125, str);
  3206. return;
  3207. }
  3208. this.finishToken(124, val);
  3209. }
  3210. readNumber(startsWithDot) {
  3211. const start = this.state.pos;
  3212. let isFloat = false;
  3213. let isBigInt = false;
  3214. let isDecimal = false;
  3215. let hasExponent = false;
  3216. let isOctal = false;
  3217. if (!startsWithDot && this.readInt(10) === null) {
  3218. this.raise(start, ErrorMessages.InvalidNumber);
  3219. }
  3220. const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  3221. if (hasLeadingZero) {
  3222. const integer = this.input.slice(start, this.state.pos);
  3223. this.recordStrictModeErrors(start, ErrorMessages.StrictOctalLiteral);
  3224. if (!this.state.strict) {
  3225. const underscorePos = integer.indexOf("_");
  3226. if (underscorePos > 0) {
  3227. this.raise(underscorePos + start, ErrorMessages.ZeroDigitNumericSeparator);
  3228. }
  3229. }
  3230. isOctal = hasLeadingZero && !/[89]/.test(integer);
  3231. }
  3232. let next = this.input.charCodeAt(this.state.pos);
  3233. if (next === 46 && !isOctal) {
  3234. ++this.state.pos;
  3235. this.readInt(10);
  3236. isFloat = true;
  3237. next = this.input.charCodeAt(this.state.pos);
  3238. }
  3239. if ((next === 69 || next === 101) && !isOctal) {
  3240. next = this.input.charCodeAt(++this.state.pos);
  3241. if (next === 43 || next === 45) {
  3242. ++this.state.pos;
  3243. }
  3244. if (this.readInt(10) === null) {
  3245. this.raise(start, ErrorMessages.InvalidOrMissingExponent);
  3246. }
  3247. isFloat = true;
  3248. hasExponent = true;
  3249. next = this.input.charCodeAt(this.state.pos);
  3250. }
  3251. if (next === 110) {
  3252. if (isFloat || hasLeadingZero) {
  3253. this.raise(start, ErrorMessages.InvalidBigIntLiteral);
  3254. }
  3255. ++this.state.pos;
  3256. isBigInt = true;
  3257. }
  3258. if (next === 109) {
  3259. this.expectPlugin("decimal", this.state.pos);
  3260. if (hasExponent || hasLeadingZero) {
  3261. this.raise(start, ErrorMessages.InvalidDecimal);
  3262. }
  3263. ++this.state.pos;
  3264. isDecimal = true;
  3265. }
  3266. if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {
  3267. throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier);
  3268. }
  3269. const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, "");
  3270. if (isBigInt) {
  3271. this.finishToken(125, str);
  3272. return;
  3273. }
  3274. if (isDecimal) {
  3275. this.finishToken(126, str);
  3276. return;
  3277. }
  3278. const val = isOctal ? parseInt(str, 8) : parseFloat(str);
  3279. this.finishToken(124, val);
  3280. }
  3281. readCodePoint(throwOnInvalid) {
  3282. const ch = this.input.charCodeAt(this.state.pos);
  3283. let code;
  3284. if (ch === 123) {
  3285. const codePos = ++this.state.pos;
  3286. code = this.readHexChar(this.input.indexOf("}", this.state.pos) - this.state.pos, true, throwOnInvalid);
  3287. ++this.state.pos;
  3288. if (code !== null && code > 0x10ffff) {
  3289. if (throwOnInvalid) {
  3290. this.raise(codePos, ErrorMessages.InvalidCodePoint);
  3291. } else {
  3292. return null;
  3293. }
  3294. }
  3295. } else {
  3296. code = this.readHexChar(4, false, throwOnInvalid);
  3297. }
  3298. return code;
  3299. }
  3300. readString(quote) {
  3301. let out = "",
  3302. chunkStart = ++this.state.pos;
  3303. for (;;) {
  3304. if (this.state.pos >= this.length) {
  3305. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  3306. }
  3307. const ch = this.input.charCodeAt(this.state.pos);
  3308. if (ch === quote) break;
  3309. if (ch === 92) {
  3310. out += this.input.slice(chunkStart, this.state.pos);
  3311. out += this.readEscapedChar(false);
  3312. chunkStart = this.state.pos;
  3313. } else if (ch === 8232 || ch === 8233) {
  3314. ++this.state.pos;
  3315. ++this.state.curLine;
  3316. this.state.lineStart = this.state.pos;
  3317. } else if (isNewLine(ch)) {
  3318. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  3319. } else {
  3320. ++this.state.pos;
  3321. }
  3322. }
  3323. out += this.input.slice(chunkStart, this.state.pos++);
  3324. this.finishToken(123, out);
  3325. }
  3326. readTmplToken() {
  3327. let out = "",
  3328. chunkStart = this.state.pos,
  3329. containsInvalid = false;
  3330. for (;;) {
  3331. if (this.state.pos >= this.length) {
  3332. throw this.raise(this.state.start, ErrorMessages.UnterminatedTemplate);
  3333. }
  3334. const ch = this.input.charCodeAt(this.state.pos);
  3335. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.state.pos + 1) === 123) {
  3336. if (this.state.pos === this.state.start && this.match(20)) {
  3337. if (ch === 36) {
  3338. this.state.pos += 2;
  3339. this.finishToken(23);
  3340. return;
  3341. } else {
  3342. ++this.state.pos;
  3343. this.finishToken(22);
  3344. return;
  3345. }
  3346. }
  3347. out += this.input.slice(chunkStart, this.state.pos);
  3348. this.finishToken(20, containsInvalid ? null : out);
  3349. return;
  3350. }
  3351. if (ch === 92) {
  3352. out += this.input.slice(chunkStart, this.state.pos);
  3353. const escaped = this.readEscapedChar(true);
  3354. if (escaped === null) {
  3355. containsInvalid = true;
  3356. } else {
  3357. out += escaped;
  3358. }
  3359. chunkStart = this.state.pos;
  3360. } else if (isNewLine(ch)) {
  3361. out += this.input.slice(chunkStart, this.state.pos);
  3362. ++this.state.pos;
  3363. switch (ch) {
  3364. case 13:
  3365. if (this.input.charCodeAt(this.state.pos) === 10) {
  3366. ++this.state.pos;
  3367. }
  3368. case 10:
  3369. out += "\n";
  3370. break;
  3371. default:
  3372. out += String.fromCharCode(ch);
  3373. break;
  3374. }
  3375. ++this.state.curLine;
  3376. this.state.lineStart = this.state.pos;
  3377. chunkStart = this.state.pos;
  3378. } else {
  3379. ++this.state.pos;
  3380. }
  3381. }
  3382. }
  3383. recordStrictModeErrors(pos, message) {
  3384. if (this.state.strict && !this.state.strictErrors.has(pos)) {
  3385. this.raise(pos, message);
  3386. } else {
  3387. this.state.strictErrors.set(pos, message);
  3388. }
  3389. }
  3390. readEscapedChar(inTemplate) {
  3391. const throwOnInvalid = !inTemplate;
  3392. const ch = this.input.charCodeAt(++this.state.pos);
  3393. ++this.state.pos;
  3394. switch (ch) {
  3395. case 110:
  3396. return "\n";
  3397. case 114:
  3398. return "\r";
  3399. case 120:
  3400. {
  3401. const code = this.readHexChar(2, false, throwOnInvalid);
  3402. return code === null ? null : String.fromCharCode(code);
  3403. }
  3404. case 117:
  3405. {
  3406. const code = this.readCodePoint(throwOnInvalid);
  3407. return code === null ? null : String.fromCodePoint(code);
  3408. }
  3409. case 116:
  3410. return "\t";
  3411. case 98:
  3412. return "\b";
  3413. case 118:
  3414. return "\u000b";
  3415. case 102:
  3416. return "\f";
  3417. case 13:
  3418. if (this.input.charCodeAt(this.state.pos) === 10) {
  3419. ++this.state.pos;
  3420. }
  3421. case 10:
  3422. this.state.lineStart = this.state.pos;
  3423. ++this.state.curLine;
  3424. case 8232:
  3425. case 8233:
  3426. return "";
  3427. case 56:
  3428. case 57:
  3429. if (inTemplate) {
  3430. return null;
  3431. } else {
  3432. this.recordStrictModeErrors(this.state.pos - 1, ErrorMessages.StrictNumericEscape);
  3433. }
  3434. default:
  3435. if (ch >= 48 && ch <= 55) {
  3436. const codePos = this.state.pos - 1;
  3437. const match = this.input.substr(this.state.pos - 1, 3).match(/^[0-7]+/);
  3438. let octalStr = match[0];
  3439. let octal = parseInt(octalStr, 8);
  3440. if (octal > 255) {
  3441. octalStr = octalStr.slice(0, -1);
  3442. octal = parseInt(octalStr, 8);
  3443. }
  3444. this.state.pos += octalStr.length - 1;
  3445. const next = this.input.charCodeAt(this.state.pos);
  3446. if (octalStr !== "0" || next === 56 || next === 57) {
  3447. if (inTemplate) {
  3448. return null;
  3449. } else {
  3450. this.recordStrictModeErrors(codePos, ErrorMessages.StrictNumericEscape);
  3451. }
  3452. }
  3453. return String.fromCharCode(octal);
  3454. }
  3455. return String.fromCharCode(ch);
  3456. }
  3457. }
  3458. readHexChar(len, forceLen, throwOnInvalid) {
  3459. const codePos = this.state.pos;
  3460. const n = this.readInt(16, len, forceLen, false);
  3461. if (n === null) {
  3462. if (throwOnInvalid) {
  3463. this.raise(codePos, ErrorMessages.InvalidEscapeSequence);
  3464. } else {
  3465. this.state.pos = codePos - 1;
  3466. }
  3467. }
  3468. return n;
  3469. }
  3470. readWord1(firstCode) {
  3471. this.state.containsEsc = false;
  3472. let word = "";
  3473. const start = this.state.pos;
  3474. let chunkStart = this.state.pos;
  3475. if (firstCode !== undefined) {
  3476. this.state.pos += firstCode <= 0xffff ? 1 : 2;
  3477. }
  3478. while (this.state.pos < this.length) {
  3479. const ch = this.codePointAtPos(this.state.pos);
  3480. if (isIdentifierChar(ch)) {
  3481. this.state.pos += ch <= 0xffff ? 1 : 2;
  3482. } else if (ch === 92) {
  3483. this.state.containsEsc = true;
  3484. word += this.input.slice(chunkStart, this.state.pos);
  3485. const escStart = this.state.pos;
  3486. const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar;
  3487. if (this.input.charCodeAt(++this.state.pos) !== 117) {
  3488. this.raise(this.state.pos, ErrorMessages.MissingUnicodeEscape);
  3489. chunkStart = this.state.pos - 1;
  3490. continue;
  3491. }
  3492. ++this.state.pos;
  3493. const esc = this.readCodePoint(true);
  3494. if (esc !== null) {
  3495. if (!identifierCheck(esc)) {
  3496. this.raise(escStart, ErrorMessages.EscapedCharNotAnIdentifier);
  3497. }
  3498. word += String.fromCodePoint(esc);
  3499. }
  3500. chunkStart = this.state.pos;
  3501. } else {
  3502. break;
  3503. }
  3504. }
  3505. return word + this.input.slice(chunkStart, this.state.pos);
  3506. }
  3507. readWord(firstCode) {
  3508. const word = this.readWord1(firstCode);
  3509. const type = keywords$1.get(word);
  3510. if (type !== undefined) {
  3511. this.finishToken(type, tokenLabelName(type));
  3512. } else {
  3513. this.finishToken(122, word);
  3514. }
  3515. }
  3516. checkKeywordEscapes() {
  3517. const {
  3518. type
  3519. } = this.state;
  3520. if (tokenIsKeyword(type) && this.state.containsEsc) {
  3521. this.raise(this.state.start, ErrorMessages.InvalidEscapedReservedWord, tokenLabelName(type));
  3522. }
  3523. }
  3524. updateContext(prevType) {
  3525. const {
  3526. context,
  3527. type
  3528. } = this.state;
  3529. switch (type) {
  3530. case 8:
  3531. context.pop();
  3532. break;
  3533. case 5:
  3534. case 7:
  3535. case 23:
  3536. context.push(types.brace);
  3537. break;
  3538. case 22:
  3539. if (context[context.length - 1] === types.template) {
  3540. context.pop();
  3541. } else {
  3542. context.push(types.template);
  3543. }
  3544. break;
  3545. }
  3546. }
  3547. }
  3548. class ClassScope {
  3549. constructor() {
  3550. this.privateNames = new Set();
  3551. this.loneAccessors = new Map();
  3552. this.undefinedPrivateNames = new Map();
  3553. }
  3554. }
  3555. class ClassScopeHandler {
  3556. constructor(raise) {
  3557. this.stack = [];
  3558. this.undefinedPrivateNames = new Map();
  3559. this.raise = raise;
  3560. }
  3561. current() {
  3562. return this.stack[this.stack.length - 1];
  3563. }
  3564. enter() {
  3565. this.stack.push(new ClassScope());
  3566. }
  3567. exit() {
  3568. const oldClassScope = this.stack.pop();
  3569. const current = this.current();
  3570. for (const [name, pos] of Array.from(oldClassScope.undefinedPrivateNames)) {
  3571. if (current) {
  3572. if (!current.undefinedPrivateNames.has(name)) {
  3573. current.undefinedPrivateNames.set(name, pos);
  3574. }
  3575. } else {
  3576. this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name);
  3577. }
  3578. }
  3579. }
  3580. declarePrivateName(name, elementType, pos) {
  3581. const classScope = this.current();
  3582. let redefined = classScope.privateNames.has(name);
  3583. if (elementType & CLASS_ELEMENT_KIND_ACCESSOR) {
  3584. const accessor = redefined && classScope.loneAccessors.get(name);
  3585. if (accessor) {
  3586. const oldStatic = accessor & CLASS_ELEMENT_FLAG_STATIC;
  3587. const newStatic = elementType & CLASS_ELEMENT_FLAG_STATIC;
  3588. const oldKind = accessor & CLASS_ELEMENT_KIND_ACCESSOR;
  3589. const newKind = elementType & CLASS_ELEMENT_KIND_ACCESSOR;
  3590. redefined = oldKind === newKind || oldStatic !== newStatic;
  3591. if (!redefined) classScope.loneAccessors.delete(name);
  3592. } else if (!redefined) {
  3593. classScope.loneAccessors.set(name, elementType);
  3594. }
  3595. }
  3596. if (redefined) {
  3597. this.raise(pos, ErrorMessages.PrivateNameRedeclaration, name);
  3598. }
  3599. classScope.privateNames.add(name);
  3600. classScope.undefinedPrivateNames.delete(name);
  3601. }
  3602. usePrivateName(name, pos) {
  3603. let classScope;
  3604. for (classScope of this.stack) {
  3605. if (classScope.privateNames.has(name)) return;
  3606. }
  3607. if (classScope) {
  3608. classScope.undefinedPrivateNames.set(name, pos);
  3609. } else {
  3610. this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name);
  3611. }
  3612. }
  3613. }
  3614. const kExpression = 0,
  3615. kMaybeArrowParameterDeclaration = 1,
  3616. kMaybeAsyncArrowParameterDeclaration = 2,
  3617. kParameterDeclaration = 3;
  3618. class ExpressionScope {
  3619. constructor(type = kExpression) {
  3620. this.type = void 0;
  3621. this.type = type;
  3622. }
  3623. canBeArrowParameterDeclaration() {
  3624. return this.type === kMaybeAsyncArrowParameterDeclaration || this.type === kMaybeArrowParameterDeclaration;
  3625. }
  3626. isCertainlyParameterDeclaration() {
  3627. return this.type === kParameterDeclaration;
  3628. }
  3629. }
  3630. class ArrowHeadParsingScope extends ExpressionScope {
  3631. constructor(type) {
  3632. super(type);
  3633. this.errors = new Map();
  3634. }
  3635. recordDeclarationError(pos, template) {
  3636. this.errors.set(pos, template);
  3637. }
  3638. clearDeclarationError(pos) {
  3639. this.errors.delete(pos);
  3640. }
  3641. iterateErrors(iterator) {
  3642. this.errors.forEach(iterator);
  3643. }
  3644. }
  3645. class ExpressionScopeHandler {
  3646. constructor(raise) {
  3647. this.stack = [new ExpressionScope()];
  3648. this.raise = raise;
  3649. }
  3650. enter(scope) {
  3651. this.stack.push(scope);
  3652. }
  3653. exit() {
  3654. this.stack.pop();
  3655. }
  3656. recordParameterInitializerError(pos, template) {
  3657. const {
  3658. stack
  3659. } = this;
  3660. let i = stack.length - 1;
  3661. let scope = stack[i];
  3662. while (!scope.isCertainlyParameterDeclaration()) {
  3663. if (scope.canBeArrowParameterDeclaration()) {
  3664. scope.recordDeclarationError(pos, template);
  3665. } else {
  3666. return;
  3667. }
  3668. scope = stack[--i];
  3669. }
  3670. this.raise(pos, template);
  3671. }
  3672. recordParenthesizedIdentifierError(pos, template) {
  3673. const {
  3674. stack
  3675. } = this;
  3676. const scope = stack[stack.length - 1];
  3677. if (scope.isCertainlyParameterDeclaration()) {
  3678. this.raise(pos, template);
  3679. } else if (scope.canBeArrowParameterDeclaration()) {
  3680. scope.recordDeclarationError(pos, template);
  3681. } else {
  3682. return;
  3683. }
  3684. }
  3685. recordAsyncArrowParametersError(pos, template) {
  3686. const {
  3687. stack
  3688. } = this;
  3689. let i = stack.length - 1;
  3690. let scope = stack[i];
  3691. while (scope.canBeArrowParameterDeclaration()) {
  3692. if (scope.type === kMaybeAsyncArrowParameterDeclaration) {
  3693. scope.recordDeclarationError(pos, template);
  3694. }
  3695. scope = stack[--i];
  3696. }
  3697. }
  3698. validateAsPattern() {
  3699. const {
  3700. stack
  3701. } = this;
  3702. const currentScope = stack[stack.length - 1];
  3703. if (!currentScope.canBeArrowParameterDeclaration()) return;
  3704. currentScope.iterateErrors((template, pos) => {
  3705. this.raise(pos, template);
  3706. let i = stack.length - 2;
  3707. let scope = stack[i];
  3708. while (scope.canBeArrowParameterDeclaration()) {
  3709. scope.clearDeclarationError(pos);
  3710. scope = stack[--i];
  3711. }
  3712. });
  3713. }
  3714. }
  3715. function newParameterDeclarationScope() {
  3716. return new ExpressionScope(kParameterDeclaration);
  3717. }
  3718. function newArrowHeadScope() {
  3719. return new ArrowHeadParsingScope(kMaybeArrowParameterDeclaration);
  3720. }
  3721. function newAsyncArrowScope() {
  3722. return new ArrowHeadParsingScope(kMaybeAsyncArrowParameterDeclaration);
  3723. }
  3724. function newExpressionScope() {
  3725. return new ExpressionScope();
  3726. }
  3727. const PARAM = 0b0000,
  3728. PARAM_YIELD = 0b0001,
  3729. PARAM_AWAIT = 0b0010,
  3730. PARAM_RETURN = 0b0100,
  3731. PARAM_IN = 0b1000;
  3732. class ProductionParameterHandler {
  3733. constructor() {
  3734. this.stacks = [];
  3735. }
  3736. enter(flags) {
  3737. this.stacks.push(flags);
  3738. }
  3739. exit() {
  3740. this.stacks.pop();
  3741. }
  3742. currentFlags() {
  3743. return this.stacks[this.stacks.length - 1];
  3744. }
  3745. get hasAwait() {
  3746. return (this.currentFlags() & PARAM_AWAIT) > 0;
  3747. }
  3748. get hasYield() {
  3749. return (this.currentFlags() & PARAM_YIELD) > 0;
  3750. }
  3751. get hasReturn() {
  3752. return (this.currentFlags() & PARAM_RETURN) > 0;
  3753. }
  3754. get hasIn() {
  3755. return (this.currentFlags() & PARAM_IN) > 0;
  3756. }
  3757. }
  3758. function functionFlags(isAsync, isGenerator) {
  3759. return (isAsync ? PARAM_AWAIT : 0) | (isGenerator ? PARAM_YIELD : 0);
  3760. }
  3761. class UtilParser extends Tokenizer {
  3762. addExtra(node, key, val) {
  3763. if (!node) return;
  3764. const extra = node.extra = node.extra || {};
  3765. extra[key] = val;
  3766. }
  3767. isContextual(token) {
  3768. return this.state.type === token && !this.state.containsEsc;
  3769. }
  3770. isUnparsedContextual(nameStart, name) {
  3771. const nameEnd = nameStart + name.length;
  3772. if (this.input.slice(nameStart, nameEnd) === name) {
  3773. const nextCh = this.input.charCodeAt(nameEnd);
  3774. return !(isIdentifierChar(nextCh) || (nextCh & 0xfc00) === 0xd800);
  3775. }
  3776. return false;
  3777. }
  3778. isLookaheadContextual(name) {
  3779. const next = this.nextTokenStart();
  3780. return this.isUnparsedContextual(next, name);
  3781. }
  3782. eatContextual(token) {
  3783. if (this.isContextual(token)) {
  3784. this.next();
  3785. return true;
  3786. }
  3787. return false;
  3788. }
  3789. expectContextual(token, template) {
  3790. if (!this.eatContextual(token)) this.unexpected(null, template);
  3791. }
  3792. canInsertSemicolon() {
  3793. return this.match(129) || this.match(8) || this.hasPrecedingLineBreak();
  3794. }
  3795. hasPrecedingLineBreak() {
  3796. return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
  3797. }
  3798. hasFollowingLineBreak() {
  3799. skipWhiteSpaceToLineBreak.lastIndex = this.state.end;
  3800. return skipWhiteSpaceToLineBreak.test(this.input);
  3801. }
  3802. isLineTerminator() {
  3803. return this.eat(13) || this.canInsertSemicolon();
  3804. }
  3805. semicolon(allowAsi = true) {
  3806. if (allowAsi ? this.isLineTerminator() : this.eat(13)) return;
  3807. this.raise(this.state.lastTokEnd, ErrorMessages.MissingSemicolon);
  3808. }
  3809. expect(type, pos) {
  3810. this.eat(type) || this.unexpected(pos, type);
  3811. }
  3812. assertNoSpace(message = "Unexpected space.") {
  3813. if (this.state.start > this.state.lastTokEnd) {
  3814. this.raise(this.state.lastTokEnd, {
  3815. code: ErrorCodes.SyntaxError,
  3816. reasonCode: "UnexpectedSpace",
  3817. template: message
  3818. });
  3819. }
  3820. }
  3821. unexpected(pos, messageOrType = {
  3822. code: ErrorCodes.SyntaxError,
  3823. reasonCode: "UnexpectedToken",
  3824. template: "Unexpected token"
  3825. }) {
  3826. if (isTokenType(messageOrType)) {
  3827. messageOrType = {
  3828. code: ErrorCodes.SyntaxError,
  3829. reasonCode: "UnexpectedToken",
  3830. template: `Unexpected token, expected "${tokenLabelName(messageOrType)}"`
  3831. };
  3832. }
  3833. throw this.raise(pos != null ? pos : this.state.start, messageOrType);
  3834. }
  3835. expectPlugin(name, pos) {
  3836. if (!this.hasPlugin(name)) {
  3837. throw this.raiseWithData(pos != null ? pos : this.state.start, {
  3838. missingPlugin: [name]
  3839. }, `This experimental syntax requires enabling the parser plugin: '${name}'`);
  3840. }
  3841. return true;
  3842. }
  3843. expectOnePlugin(names, pos) {
  3844. if (!names.some(n => this.hasPlugin(n))) {
  3845. throw this.raiseWithData(pos != null ? pos : this.state.start, {
  3846. missingPlugin: names
  3847. }, `This experimental syntax requires enabling one of the following parser plugin(s): '${names.join(", ")}'`);
  3848. }
  3849. }
  3850. tryParse(fn, oldState = this.state.clone()) {
  3851. const abortSignal = {
  3852. node: null
  3853. };
  3854. try {
  3855. const node = fn((node = null) => {
  3856. abortSignal.node = node;
  3857. throw abortSignal;
  3858. });
  3859. if (this.state.errors.length > oldState.errors.length) {
  3860. const failState = this.state;
  3861. this.state = oldState;
  3862. this.state.tokensLength = failState.tokensLength;
  3863. return {
  3864. node,
  3865. error: failState.errors[oldState.errors.length],
  3866. thrown: false,
  3867. aborted: false,
  3868. failState
  3869. };
  3870. }
  3871. return {
  3872. node,
  3873. error: null,
  3874. thrown: false,
  3875. aborted: false,
  3876. failState: null
  3877. };
  3878. } catch (error) {
  3879. const failState = this.state;
  3880. this.state = oldState;
  3881. if (error instanceof SyntaxError) {
  3882. return {
  3883. node: null,
  3884. error,
  3885. thrown: true,
  3886. aborted: false,
  3887. failState
  3888. };
  3889. }
  3890. if (error === abortSignal) {
  3891. return {
  3892. node: abortSignal.node,
  3893. error: null,
  3894. thrown: false,
  3895. aborted: true,
  3896. failState
  3897. };
  3898. }
  3899. throw error;
  3900. }
  3901. }
  3902. checkExpressionErrors(refExpressionErrors, andThrow) {
  3903. if (!refExpressionErrors) return false;
  3904. const {
  3905. shorthandAssign,
  3906. doubleProto,
  3907. optionalParameters
  3908. } = refExpressionErrors;
  3909. const hasErrors = shorthandAssign + doubleProto + optionalParameters > -3;
  3910. if (!andThrow) {
  3911. return hasErrors;
  3912. } else if (hasErrors) {
  3913. if (shorthandAssign >= 0) {
  3914. this.unexpected(shorthandAssign);
  3915. }
  3916. if (doubleProto >= 0) {
  3917. this.raise(doubleProto, ErrorMessages.DuplicateProto);
  3918. }
  3919. if (optionalParameters >= 0) {
  3920. this.unexpected(optionalParameters);
  3921. }
  3922. }
  3923. }
  3924. isLiteralPropertyName() {
  3925. return tokenIsLiteralPropertyName(this.state.type);
  3926. }
  3927. isPrivateName(node) {
  3928. return node.type === "PrivateName";
  3929. }
  3930. getPrivateNameSV(node) {
  3931. return node.id.name;
  3932. }
  3933. hasPropertyAsPrivateName(node) {
  3934. return (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") && this.isPrivateName(node.property);
  3935. }
  3936. isOptionalChain(node) {
  3937. return node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression";
  3938. }
  3939. isObjectProperty(node) {
  3940. return node.type === "ObjectProperty";
  3941. }
  3942. isObjectMethod(node) {
  3943. return node.type === "ObjectMethod";
  3944. }
  3945. initializeScopes(inModule = this.options.sourceType === "module") {
  3946. const oldLabels = this.state.labels;
  3947. this.state.labels = [];
  3948. const oldExportedIdentifiers = this.exportedIdentifiers;
  3949. this.exportedIdentifiers = new Set();
  3950. const oldInModule = this.inModule;
  3951. this.inModule = inModule;
  3952. const oldScope = this.scope;
  3953. const ScopeHandler = this.getScopeHandler();
  3954. this.scope = new ScopeHandler(this.raise.bind(this), this.inModule);
  3955. const oldProdParam = this.prodParam;
  3956. this.prodParam = new ProductionParameterHandler();
  3957. const oldClassScope = this.classScope;
  3958. this.classScope = new ClassScopeHandler(this.raise.bind(this));
  3959. const oldExpressionScope = this.expressionScope;
  3960. this.expressionScope = new ExpressionScopeHandler(this.raise.bind(this));
  3961. return () => {
  3962. this.state.labels = oldLabels;
  3963. this.exportedIdentifiers = oldExportedIdentifiers;
  3964. this.inModule = oldInModule;
  3965. this.scope = oldScope;
  3966. this.prodParam = oldProdParam;
  3967. this.classScope = oldClassScope;
  3968. this.expressionScope = oldExpressionScope;
  3969. };
  3970. }
  3971. enterInitialScopes() {
  3972. let paramFlags = PARAM;
  3973. if (this.inModule) {
  3974. paramFlags |= PARAM_AWAIT;
  3975. }
  3976. this.scope.enter(SCOPE_PROGRAM);
  3977. this.prodParam.enter(paramFlags);
  3978. }
  3979. }
  3980. class ExpressionErrors {
  3981. constructor() {
  3982. this.shorthandAssign = -1;
  3983. this.doubleProto = -1;
  3984. this.optionalParameters = -1;
  3985. }
  3986. }
  3987. class Node {
  3988. constructor(parser, pos, loc) {
  3989. this.type = "";
  3990. this.start = pos;
  3991. this.end = 0;
  3992. this.loc = new SourceLocation(loc);
  3993. if (parser != null && parser.options.ranges) this.range = [pos, 0];
  3994. if (parser != null && parser.filename) this.loc.filename = parser.filename;
  3995. }
  3996. }
  3997. const NodePrototype = Node.prototype;
  3998. {
  3999. NodePrototype.__clone = function () {
  4000. const newNode = new Node();
  4001. const keys = Object.keys(this);
  4002. for (let i = 0, length = keys.length; i < length; i++) {
  4003. const key = keys[i];
  4004. if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") {
  4005. newNode[key] = this[key];
  4006. }
  4007. }
  4008. return newNode;
  4009. };
  4010. }
  4011. function clonePlaceholder(node) {
  4012. return cloneIdentifier(node);
  4013. }
  4014. function cloneIdentifier(node) {
  4015. const {
  4016. type,
  4017. start,
  4018. end,
  4019. loc,
  4020. range,
  4021. extra,
  4022. name
  4023. } = node;
  4024. const cloned = Object.create(NodePrototype);
  4025. cloned.type = type;
  4026. cloned.start = start;
  4027. cloned.end = end;
  4028. cloned.loc = loc;
  4029. cloned.range = range;
  4030. cloned.extra = extra;
  4031. cloned.name = name;
  4032. if (type === "Placeholder") {
  4033. cloned.expectedNode = node.expectedNode;
  4034. }
  4035. return cloned;
  4036. }
  4037. function cloneStringLiteral(node) {
  4038. const {
  4039. type,
  4040. start,
  4041. end,
  4042. loc,
  4043. range,
  4044. extra
  4045. } = node;
  4046. if (type === "Placeholder") {
  4047. return clonePlaceholder(node);
  4048. }
  4049. const cloned = Object.create(NodePrototype);
  4050. cloned.type = "StringLiteral";
  4051. cloned.start = start;
  4052. cloned.end = end;
  4053. cloned.loc = loc;
  4054. cloned.range = range;
  4055. cloned.extra = extra;
  4056. cloned.value = node.value;
  4057. return cloned;
  4058. }
  4059. class NodeUtils extends UtilParser {
  4060. startNode() {
  4061. return new Node(this, this.state.start, this.state.startLoc);
  4062. }
  4063. startNodeAt(pos, loc) {
  4064. return new Node(this, pos, loc);
  4065. }
  4066. startNodeAtNode(type) {
  4067. return this.startNodeAt(type.start, type.loc.start);
  4068. }
  4069. finishNode(node, type) {
  4070. return this.finishNodeAt(node, type, this.state.lastTokEnd, this.state.lastTokEndLoc);
  4071. }
  4072. finishNodeAt(node, type, pos, loc) {
  4073. node.type = type;
  4074. node.end = pos;
  4075. node.loc.end = loc;
  4076. if (this.options.ranges) node.range[1] = pos;
  4077. if (this.options.attachComment) this.processComment(node);
  4078. return node;
  4079. }
  4080. resetStartLocation(node, start, startLoc) {
  4081. node.start = start;
  4082. node.loc.start = startLoc;
  4083. if (this.options.ranges) node.range[0] = start;
  4084. }
  4085. resetEndLocation(node, end = this.state.lastTokEnd, endLoc = this.state.lastTokEndLoc) {
  4086. node.end = end;
  4087. node.loc.end = endLoc;
  4088. if (this.options.ranges) node.range[1] = end;
  4089. }
  4090. resetStartLocationFromNode(node, locationNode) {
  4091. this.resetStartLocation(node, locationNode.start, locationNode.loc.start);
  4092. }
  4093. }
  4094. const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]);
  4095. const FlowErrors = makeErrorTemplates({
  4096. AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",
  4097. 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.",
  4098. AssignReservedType: "Cannot overwrite reserved type %0.",
  4099. DeclareClassElement: "The `declare` modifier can only appear on class fields.",
  4100. DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.",
  4101. DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement.",
  4102. EnumBooleanMemberNotInitialized: "Boolean enum members need to be initialized. Use either `%0 = true,` or `%0 = false,` in enum `%1`.",
  4103. EnumDuplicateMemberName: "Enum member names need to be unique, but the name `%0` has already been used before in enum `%1`.",
  4104. EnumInconsistentMemberValues: "Enum `%0` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.",
  4105. EnumInvalidExplicitType: "Enum type `%1` is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  4106. EnumInvalidExplicitTypeUnknownSupplied: "Supplied enum type is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  4107. EnumInvalidMemberInitializerPrimaryType: "Enum `%0` has type `%2`, so the initializer of `%1` needs to be a %2 literal.",
  4108. EnumInvalidMemberInitializerSymbolType: "Symbol enum members cannot be initialized. Use `%1,` in enum `%0`.",
  4109. EnumInvalidMemberInitializerUnknownType: "The enum member initializer for `%1` needs to be a literal (either a boolean, number, or string) in enum `%0`.",
  4110. EnumInvalidMemberName: "Enum member names cannot start with lowercase 'a' through 'z'. Instead of using `%0`, consider using `%1`, in enum `%2`.",
  4111. EnumNumberMemberNotInitialized: "Number enum members need to be initialized, e.g. `%1 = 1` in enum `%0`.",
  4112. EnumStringMemberInconsistentlyInitailized: "String enum members need to consistently either all use initializers, or use no initializers, in enum `%0`.",
  4113. GetterMayNotHaveThisParam: "A getter cannot have a `this` parameter.",
  4114. 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.",
  4115. InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type.",
  4116. InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions.",
  4117. InexactVariance: "Explicit inexact syntax cannot have variance.",
  4118. InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`.",
  4119. MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",
  4120. NestedDeclareModule: "`declare module` cannot be used inside another `declare module`.",
  4121. NestedFlowComment: "Cannot have a flow comment inside another flow comment.",
  4122. PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.",
  4123. SetterMayNotHaveThisParam: "A setter cannot have a `this` parameter.",
  4124. SpreadVariance: "Spread properties cannot have variance.",
  4125. ThisParamAnnotationRequired: "A type annotation is required for the `this` parameter.",
  4126. ThisParamBannedInConstructor: "Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.",
  4127. ThisParamMayNotBeOptional: "The `this` parameter cannot be optional.",
  4128. ThisParamMustBeFirst: "The `this` parameter must be the first function parameter.",
  4129. ThisParamNoDefault: "The `this` parameter may not have a default value.",
  4130. TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",
  4131. TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis.",
  4132. UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object.",
  4133. UnexpectedReservedType: "Unexpected reserved type %0.",
  4134. UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new.",
  4135. UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.",
  4136. UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions.",
  4137. UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint".',
  4138. UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration.",
  4139. UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`.",
  4140. UnsupportedDeclareExportKind: "`declare export %0` is not supported. Use `%1` instead.",
  4141. UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module.",
  4142. UnterminatedFlowComment: "Unterminated flow-comment."
  4143. }, ErrorCodes.SyntaxError, "flow");
  4144. function isEsModuleType(bodyElement) {
  4145. return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration");
  4146. }
  4147. function hasTypeImportKind(node) {
  4148. return node.importKind === "type" || node.importKind === "typeof";
  4149. }
  4150. function isMaybeDefaultImport(type) {
  4151. return tokenIsKeywordOrIdentifier(type) && type !== 91;
  4152. }
  4153. const exportSuggestions = {
  4154. const: "declare export var",
  4155. let: "declare export var",
  4156. type: "export type",
  4157. interface: "export interface"
  4158. };
  4159. function partition(list, test) {
  4160. const list1 = [];
  4161. const list2 = [];
  4162. for (let i = 0; i < list.length; i++) {
  4163. (test(list[i], i, list) ? list1 : list2).push(list[i]);
  4164. }
  4165. return [list1, list2];
  4166. }
  4167. const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
  4168. var flow = (superClass => class extends superClass {
  4169. constructor(...args) {
  4170. super(...args);
  4171. this.flowPragma = undefined;
  4172. }
  4173. getScopeHandler() {
  4174. return FlowScopeHandler;
  4175. }
  4176. shouldParseTypes() {
  4177. return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
  4178. }
  4179. shouldParseEnums() {
  4180. return !!this.getPluginOption("flow", "enums");
  4181. }
  4182. finishToken(type, val) {
  4183. if (type !== 123 && type !== 13 && type !== 26) {
  4184. if (this.flowPragma === undefined) {
  4185. this.flowPragma = null;
  4186. }
  4187. }
  4188. return super.finishToken(type, val);
  4189. }
  4190. addComment(comment) {
  4191. if (this.flowPragma === undefined) {
  4192. const matches = FLOW_PRAGMA_REGEX.exec(comment.value);
  4193. if (!matches) ; else if (matches[1] === "flow") {
  4194. this.flowPragma = "flow";
  4195. } else if (matches[1] === "noflow") {
  4196. this.flowPragma = "noflow";
  4197. } else {
  4198. throw new Error("Unexpected flow pragma");
  4199. }
  4200. }
  4201. return super.addComment(comment);
  4202. }
  4203. flowParseTypeInitialiser(tok) {
  4204. const oldInType = this.state.inType;
  4205. this.state.inType = true;
  4206. this.expect(tok || 14);
  4207. const type = this.flowParseType();
  4208. this.state.inType = oldInType;
  4209. return type;
  4210. }
  4211. flowParsePredicate() {
  4212. const node = this.startNode();
  4213. const moduloPos = this.state.start;
  4214. this.next();
  4215. this.expectContextual(101);
  4216. if (this.state.lastTokStart > moduloPos + 1) {
  4217. this.raise(moduloPos, FlowErrors.UnexpectedSpaceBetweenModuloChecks);
  4218. }
  4219. if (this.eat(10)) {
  4220. node.value = this.parseExpression();
  4221. this.expect(11);
  4222. return this.finishNode(node, "DeclaredPredicate");
  4223. } else {
  4224. return this.finishNode(node, "InferredPredicate");
  4225. }
  4226. }
  4227. flowParseTypeAndPredicateInitialiser() {
  4228. const oldInType = this.state.inType;
  4229. this.state.inType = true;
  4230. this.expect(14);
  4231. let type = null;
  4232. let predicate = null;
  4233. if (this.match(48)) {
  4234. this.state.inType = oldInType;
  4235. predicate = this.flowParsePredicate();
  4236. } else {
  4237. type = this.flowParseType();
  4238. this.state.inType = oldInType;
  4239. if (this.match(48)) {
  4240. predicate = this.flowParsePredicate();
  4241. }
  4242. }
  4243. return [type, predicate];
  4244. }
  4245. flowParseDeclareClass(node) {
  4246. this.next();
  4247. this.flowParseInterfaceish(node, true);
  4248. return this.finishNode(node, "DeclareClass");
  4249. }
  4250. flowParseDeclareFunction(node) {
  4251. this.next();
  4252. const id = node.id = this.parseIdentifier();
  4253. const typeNode = this.startNode();
  4254. const typeContainer = this.startNode();
  4255. if (this.match(43)) {
  4256. typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
  4257. } else {
  4258. typeNode.typeParameters = null;
  4259. }
  4260. this.expect(10);
  4261. const tmp = this.flowParseFunctionTypeParams();
  4262. typeNode.params = tmp.params;
  4263. typeNode.rest = tmp.rest;
  4264. typeNode.this = tmp._this;
  4265. this.expect(11);
  4266. [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  4267. typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
  4268. id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
  4269. this.resetEndLocation(id);
  4270. this.semicolon();
  4271. this.scope.declareName(node.id.name, BIND_FLOW_DECLARE_FN, node.id.start);
  4272. return this.finishNode(node, "DeclareFunction");
  4273. }
  4274. flowParseDeclare(node, insideModule) {
  4275. if (this.match(74)) {
  4276. return this.flowParseDeclareClass(node);
  4277. } else if (this.match(62)) {
  4278. return this.flowParseDeclareFunction(node);
  4279. } else if (this.match(68)) {
  4280. return this.flowParseDeclareVariable(node);
  4281. } else if (this.eatContextual(117)) {
  4282. if (this.match(16)) {
  4283. return this.flowParseDeclareModuleExports(node);
  4284. } else {
  4285. if (insideModule) {
  4286. this.raise(this.state.lastTokStart, FlowErrors.NestedDeclareModule);
  4287. }
  4288. return this.flowParseDeclareModule(node);
  4289. }
  4290. } else if (this.isContextual(120)) {
  4291. return this.flowParseDeclareTypeAlias(node);
  4292. } else if (this.isContextual(121)) {
  4293. return this.flowParseDeclareOpaqueType(node);
  4294. } else if (this.isContextual(119)) {
  4295. return this.flowParseDeclareInterface(node);
  4296. } else if (this.match(76)) {
  4297. return this.flowParseDeclareExportDeclaration(node, insideModule);
  4298. } else {
  4299. throw this.unexpected();
  4300. }
  4301. }
  4302. flowParseDeclareVariable(node) {
  4303. this.next();
  4304. node.id = this.flowParseTypeAnnotatableIdentifier(true);
  4305. this.scope.declareName(node.id.name, BIND_VAR, node.id.start);
  4306. this.semicolon();
  4307. return this.finishNode(node, "DeclareVariable");
  4308. }
  4309. flowParseDeclareModule(node) {
  4310. this.scope.enter(SCOPE_OTHER);
  4311. if (this.match(123)) {
  4312. node.id = this.parseExprAtom();
  4313. } else {
  4314. node.id = this.parseIdentifier();
  4315. }
  4316. const bodyNode = node.body = this.startNode();
  4317. const body = bodyNode.body = [];
  4318. this.expect(5);
  4319. while (!this.match(8)) {
  4320. let bodyNode = this.startNode();
  4321. if (this.match(77)) {
  4322. this.next();
  4323. if (!this.isContextual(120) && !this.match(81)) {
  4324. this.raise(this.state.lastTokStart, FlowErrors.InvalidNonTypeImportInDeclareModule);
  4325. }
  4326. this.parseImport(bodyNode);
  4327. } else {
  4328. this.expectContextual(115, FlowErrors.UnsupportedStatementInDeclareModule);
  4329. bodyNode = this.flowParseDeclare(bodyNode, true);
  4330. }
  4331. body.push(bodyNode);
  4332. }
  4333. this.scope.exit();
  4334. this.expect(8);
  4335. this.finishNode(bodyNode, "BlockStatement");
  4336. let kind = null;
  4337. let hasModuleExport = false;
  4338. body.forEach(bodyElement => {
  4339. if (isEsModuleType(bodyElement)) {
  4340. if (kind === "CommonJS") {
  4341. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  4342. }
  4343. kind = "ES";
  4344. } else if (bodyElement.type === "DeclareModuleExports") {
  4345. if (hasModuleExport) {
  4346. this.raise(bodyElement.start, FlowErrors.DuplicateDeclareModuleExports);
  4347. }
  4348. if (kind === "ES") {
  4349. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  4350. }
  4351. kind = "CommonJS";
  4352. hasModuleExport = true;
  4353. }
  4354. });
  4355. node.kind = kind || "CommonJS";
  4356. return this.finishNode(node, "DeclareModule");
  4357. }
  4358. flowParseDeclareExportDeclaration(node, insideModule) {
  4359. this.expect(76);
  4360. if (this.eat(59)) {
  4361. if (this.match(62) || this.match(74)) {
  4362. node.declaration = this.flowParseDeclare(this.startNode());
  4363. } else {
  4364. node.declaration = this.flowParseType();
  4365. this.semicolon();
  4366. }
  4367. node.default = true;
  4368. return this.finishNode(node, "DeclareExportDeclaration");
  4369. } else {
  4370. if (this.match(69) || this.isLet() || (this.isContextual(120) || this.isContextual(119)) && !insideModule) {
  4371. const label = this.state.value;
  4372. const suggestion = exportSuggestions[label];
  4373. throw this.raise(this.state.start, FlowErrors.UnsupportedDeclareExportKind, label, suggestion);
  4374. }
  4375. if (this.match(68) || this.match(62) || this.match(74) || this.isContextual(121)) {
  4376. node.declaration = this.flowParseDeclare(this.startNode());
  4377. node.default = false;
  4378. return this.finishNode(node, "DeclareExportDeclaration");
  4379. } else if (this.match(49) || this.match(5) || this.isContextual(119) || this.isContextual(120) || this.isContextual(121)) {
  4380. node = this.parseExport(node);
  4381. if (node.type === "ExportNamedDeclaration") {
  4382. node.type = "ExportDeclaration";
  4383. node.default = false;
  4384. delete node.exportKind;
  4385. }
  4386. node.type = "Declare" + node.type;
  4387. return node;
  4388. }
  4389. }
  4390. throw this.unexpected();
  4391. }
  4392. flowParseDeclareModuleExports(node) {
  4393. this.next();
  4394. this.expectContextual(102);
  4395. node.typeAnnotation = this.flowParseTypeAnnotation();
  4396. this.semicolon();
  4397. return this.finishNode(node, "DeclareModuleExports");
  4398. }
  4399. flowParseDeclareTypeAlias(node) {
  4400. this.next();
  4401. this.flowParseTypeAlias(node);
  4402. node.type = "DeclareTypeAlias";
  4403. return node;
  4404. }
  4405. flowParseDeclareOpaqueType(node) {
  4406. this.next();
  4407. this.flowParseOpaqueType(node, true);
  4408. node.type = "DeclareOpaqueType";
  4409. return node;
  4410. }
  4411. flowParseDeclareInterface(node) {
  4412. this.next();
  4413. this.flowParseInterfaceish(node);
  4414. return this.finishNode(node, "DeclareInterface");
  4415. }
  4416. flowParseInterfaceish(node, isClass = false) {
  4417. node.id = this.flowParseRestrictedIdentifier(!isClass, true);
  4418. this.scope.declareName(node.id.name, isClass ? BIND_FUNCTION : BIND_LEXICAL, node.id.start);
  4419. if (this.match(43)) {
  4420. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4421. } else {
  4422. node.typeParameters = null;
  4423. }
  4424. node.extends = [];
  4425. node.implements = [];
  4426. node.mixins = [];
  4427. if (this.eat(75)) {
  4428. do {
  4429. node.extends.push(this.flowParseInterfaceExtends());
  4430. } while (!isClass && this.eat(12));
  4431. }
  4432. if (this.isContextual(108)) {
  4433. this.next();
  4434. do {
  4435. node.mixins.push(this.flowParseInterfaceExtends());
  4436. } while (this.eat(12));
  4437. }
  4438. if (this.isContextual(104)) {
  4439. this.next();
  4440. do {
  4441. node.implements.push(this.flowParseInterfaceExtends());
  4442. } while (this.eat(12));
  4443. }
  4444. node.body = this.flowParseObjectType({
  4445. allowStatic: isClass,
  4446. allowExact: false,
  4447. allowSpread: false,
  4448. allowProto: isClass,
  4449. allowInexact: false
  4450. });
  4451. }
  4452. flowParseInterfaceExtends() {
  4453. const node = this.startNode();
  4454. node.id = this.flowParseQualifiedTypeIdentifier();
  4455. if (this.match(43)) {
  4456. node.typeParameters = this.flowParseTypeParameterInstantiation();
  4457. } else {
  4458. node.typeParameters = null;
  4459. }
  4460. return this.finishNode(node, "InterfaceExtends");
  4461. }
  4462. flowParseInterface(node) {
  4463. this.flowParseInterfaceish(node);
  4464. return this.finishNode(node, "InterfaceDeclaration");
  4465. }
  4466. checkNotUnderscore(word) {
  4467. if (word === "_") {
  4468. this.raise(this.state.start, FlowErrors.UnexpectedReservedUnderscore);
  4469. }
  4470. }
  4471. checkReservedType(word, startLoc, declaration) {
  4472. if (!reservedTypes.has(word)) return;
  4473. this.raise(startLoc, declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, word);
  4474. }
  4475. flowParseRestrictedIdentifier(liberal, declaration) {
  4476. this.checkReservedType(this.state.value, this.state.start, declaration);
  4477. return this.parseIdentifier(liberal);
  4478. }
  4479. flowParseTypeAlias(node) {
  4480. node.id = this.flowParseRestrictedIdentifier(false, true);
  4481. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  4482. if (this.match(43)) {
  4483. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4484. } else {
  4485. node.typeParameters = null;
  4486. }
  4487. node.right = this.flowParseTypeInitialiser(27);
  4488. this.semicolon();
  4489. return this.finishNode(node, "TypeAlias");
  4490. }
  4491. flowParseOpaqueType(node, declare) {
  4492. this.expectContextual(120);
  4493. node.id = this.flowParseRestrictedIdentifier(true, true);
  4494. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  4495. if (this.match(43)) {
  4496. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4497. } else {
  4498. node.typeParameters = null;
  4499. }
  4500. node.supertype = null;
  4501. if (this.match(14)) {
  4502. node.supertype = this.flowParseTypeInitialiser(14);
  4503. }
  4504. node.impltype = null;
  4505. if (!declare) {
  4506. node.impltype = this.flowParseTypeInitialiser(27);
  4507. }
  4508. this.semicolon();
  4509. return this.finishNode(node, "OpaqueType");
  4510. }
  4511. flowParseTypeParameter(requireDefault = false) {
  4512. const nodeStart = this.state.start;
  4513. const node = this.startNode();
  4514. const variance = this.flowParseVariance();
  4515. const ident = this.flowParseTypeAnnotatableIdentifier();
  4516. node.name = ident.name;
  4517. node.variance = variance;
  4518. node.bound = ident.typeAnnotation;
  4519. if (this.match(27)) {
  4520. this.eat(27);
  4521. node.default = this.flowParseType();
  4522. } else {
  4523. if (requireDefault) {
  4524. this.raise(nodeStart, FlowErrors.MissingTypeParamDefault);
  4525. }
  4526. }
  4527. return this.finishNode(node, "TypeParameter");
  4528. }
  4529. flowParseTypeParameterDeclaration() {
  4530. const oldInType = this.state.inType;
  4531. const node = this.startNode();
  4532. node.params = [];
  4533. this.state.inType = true;
  4534. if (this.match(43) || this.match(132)) {
  4535. this.next();
  4536. } else {
  4537. this.unexpected();
  4538. }
  4539. let defaultRequired = false;
  4540. do {
  4541. const typeParameter = this.flowParseTypeParameter(defaultRequired);
  4542. node.params.push(typeParameter);
  4543. if (typeParameter.default) {
  4544. defaultRequired = true;
  4545. }
  4546. if (!this.match(44)) {
  4547. this.expect(12);
  4548. }
  4549. } while (!this.match(44));
  4550. this.expect(44);
  4551. this.state.inType = oldInType;
  4552. return this.finishNode(node, "TypeParameterDeclaration");
  4553. }
  4554. flowParseTypeParameterInstantiation() {
  4555. const node = this.startNode();
  4556. const oldInType = this.state.inType;
  4557. node.params = [];
  4558. this.state.inType = true;
  4559. this.expect(43);
  4560. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  4561. this.state.noAnonFunctionType = false;
  4562. while (!this.match(44)) {
  4563. node.params.push(this.flowParseType());
  4564. if (!this.match(44)) {
  4565. this.expect(12);
  4566. }
  4567. }
  4568. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  4569. this.expect(44);
  4570. this.state.inType = oldInType;
  4571. return this.finishNode(node, "TypeParameterInstantiation");
  4572. }
  4573. flowParseTypeParameterInstantiationCallOrNew() {
  4574. const node = this.startNode();
  4575. const oldInType = this.state.inType;
  4576. node.params = [];
  4577. this.state.inType = true;
  4578. this.expect(43);
  4579. while (!this.match(44)) {
  4580. node.params.push(this.flowParseTypeOrImplicitInstantiation());
  4581. if (!this.match(44)) {
  4582. this.expect(12);
  4583. }
  4584. }
  4585. this.expect(44);
  4586. this.state.inType = oldInType;
  4587. return this.finishNode(node, "TypeParameterInstantiation");
  4588. }
  4589. flowParseInterfaceType() {
  4590. const node = this.startNode();
  4591. this.expectContextual(119);
  4592. node.extends = [];
  4593. if (this.eat(75)) {
  4594. do {
  4595. node.extends.push(this.flowParseInterfaceExtends());
  4596. } while (this.eat(12));
  4597. }
  4598. node.body = this.flowParseObjectType({
  4599. allowStatic: false,
  4600. allowExact: false,
  4601. allowSpread: false,
  4602. allowProto: false,
  4603. allowInexact: false
  4604. });
  4605. return this.finishNode(node, "InterfaceTypeAnnotation");
  4606. }
  4607. flowParseObjectPropertyKey() {
  4608. return this.match(124) || this.match(123) ? this.parseExprAtom() : this.parseIdentifier(true);
  4609. }
  4610. flowParseObjectTypeIndexer(node, isStatic, variance) {
  4611. node.static = isStatic;
  4612. if (this.lookahead().type === 14) {
  4613. node.id = this.flowParseObjectPropertyKey();
  4614. node.key = this.flowParseTypeInitialiser();
  4615. } else {
  4616. node.id = null;
  4617. node.key = this.flowParseType();
  4618. }
  4619. this.expect(3);
  4620. node.value = this.flowParseTypeInitialiser();
  4621. node.variance = variance;
  4622. return this.finishNode(node, "ObjectTypeIndexer");
  4623. }
  4624. flowParseObjectTypeInternalSlot(node, isStatic) {
  4625. node.static = isStatic;
  4626. node.id = this.flowParseObjectPropertyKey();
  4627. this.expect(3);
  4628. this.expect(3);
  4629. if (this.match(43) || this.match(10)) {
  4630. node.method = true;
  4631. node.optional = false;
  4632. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  4633. } else {
  4634. node.method = false;
  4635. if (this.eat(17)) {
  4636. node.optional = true;
  4637. }
  4638. node.value = this.flowParseTypeInitialiser();
  4639. }
  4640. return this.finishNode(node, "ObjectTypeInternalSlot");
  4641. }
  4642. flowParseObjectTypeMethodish(node) {
  4643. node.params = [];
  4644. node.rest = null;
  4645. node.typeParameters = null;
  4646. node.this = null;
  4647. if (this.match(43)) {
  4648. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4649. }
  4650. this.expect(10);
  4651. if (this.match(72)) {
  4652. node.this = this.flowParseFunctionTypeParam(true);
  4653. node.this.name = null;
  4654. if (!this.match(11)) {
  4655. this.expect(12);
  4656. }
  4657. }
  4658. while (!this.match(11) && !this.match(21)) {
  4659. node.params.push(this.flowParseFunctionTypeParam(false));
  4660. if (!this.match(11)) {
  4661. this.expect(12);
  4662. }
  4663. }
  4664. if (this.eat(21)) {
  4665. node.rest = this.flowParseFunctionTypeParam(false);
  4666. }
  4667. this.expect(11);
  4668. node.returnType = this.flowParseTypeInitialiser();
  4669. return this.finishNode(node, "FunctionTypeAnnotation");
  4670. }
  4671. flowParseObjectTypeCallProperty(node, isStatic) {
  4672. const valueNode = this.startNode();
  4673. node.static = isStatic;
  4674. node.value = this.flowParseObjectTypeMethodish(valueNode);
  4675. return this.finishNode(node, "ObjectTypeCallProperty");
  4676. }
  4677. flowParseObjectType({
  4678. allowStatic,
  4679. allowExact,
  4680. allowSpread,
  4681. allowProto,
  4682. allowInexact
  4683. }) {
  4684. const oldInType = this.state.inType;
  4685. this.state.inType = true;
  4686. const nodeStart = this.startNode();
  4687. nodeStart.callProperties = [];
  4688. nodeStart.properties = [];
  4689. nodeStart.indexers = [];
  4690. nodeStart.internalSlots = [];
  4691. let endDelim;
  4692. let exact;
  4693. let inexact = false;
  4694. if (allowExact && this.match(6)) {
  4695. this.expect(6);
  4696. endDelim = 9;
  4697. exact = true;
  4698. } else {
  4699. this.expect(5);
  4700. endDelim = 8;
  4701. exact = false;
  4702. }
  4703. nodeStart.exact = exact;
  4704. while (!this.match(endDelim)) {
  4705. let isStatic = false;
  4706. let protoStart = null;
  4707. let inexactStart = null;
  4708. const node = this.startNode();
  4709. if (allowProto && this.isContextual(109)) {
  4710. const lookahead = this.lookahead();
  4711. if (lookahead.type !== 14 && lookahead.type !== 17) {
  4712. this.next();
  4713. protoStart = this.state.start;
  4714. allowStatic = false;
  4715. }
  4716. }
  4717. if (allowStatic && this.isContextual(98)) {
  4718. const lookahead = this.lookahead();
  4719. if (lookahead.type !== 14 && lookahead.type !== 17) {
  4720. this.next();
  4721. isStatic = true;
  4722. }
  4723. }
  4724. const variance = this.flowParseVariance();
  4725. if (this.eat(0)) {
  4726. if (protoStart != null) {
  4727. this.unexpected(protoStart);
  4728. }
  4729. if (this.eat(0)) {
  4730. if (variance) {
  4731. this.unexpected(variance.start);
  4732. }
  4733. nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic));
  4734. } else {
  4735. nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance));
  4736. }
  4737. } else if (this.match(10) || this.match(43)) {
  4738. if (protoStart != null) {
  4739. this.unexpected(protoStart);
  4740. }
  4741. if (variance) {
  4742. this.unexpected(variance.start);
  4743. }
  4744. nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic));
  4745. } else {
  4746. let kind = "init";
  4747. if (this.isContextual(92) || this.isContextual(97)) {
  4748. const lookahead = this.lookahead();
  4749. if (tokenIsLiteralPropertyName(lookahead.type)) {
  4750. kind = this.state.value;
  4751. this.next();
  4752. }
  4753. }
  4754. const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact);
  4755. if (propOrInexact === null) {
  4756. inexact = true;
  4757. inexactStart = this.state.lastTokStart;
  4758. } else {
  4759. nodeStart.properties.push(propOrInexact);
  4760. }
  4761. }
  4762. this.flowObjectTypeSemicolon();
  4763. if (inexactStart && !this.match(8) && !this.match(9)) {
  4764. this.raise(inexactStart, FlowErrors.UnexpectedExplicitInexactInObject);
  4765. }
  4766. }
  4767. this.expect(endDelim);
  4768. if (allowSpread) {
  4769. nodeStart.inexact = inexact;
  4770. }
  4771. const out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
  4772. this.state.inType = oldInType;
  4773. return out;
  4774. }
  4775. flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact) {
  4776. if (this.eat(21)) {
  4777. const isInexactToken = this.match(12) || this.match(13) || this.match(8) || this.match(9);
  4778. if (isInexactToken) {
  4779. if (!allowSpread) {
  4780. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideNonObject);
  4781. } else if (!allowInexact) {
  4782. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideExact);
  4783. }
  4784. if (variance) {
  4785. this.raise(variance.start, FlowErrors.InexactVariance);
  4786. }
  4787. return null;
  4788. }
  4789. if (!allowSpread) {
  4790. this.raise(this.state.lastTokStart, FlowErrors.UnexpectedSpreadType);
  4791. }
  4792. if (protoStart != null) {
  4793. this.unexpected(protoStart);
  4794. }
  4795. if (variance) {
  4796. this.raise(variance.start, FlowErrors.SpreadVariance);
  4797. }
  4798. node.argument = this.flowParseType();
  4799. return this.finishNode(node, "ObjectTypeSpreadProperty");
  4800. } else {
  4801. node.key = this.flowParseObjectPropertyKey();
  4802. node.static = isStatic;
  4803. node.proto = protoStart != null;
  4804. node.kind = kind;
  4805. let optional = false;
  4806. if (this.match(43) || this.match(10)) {
  4807. node.method = true;
  4808. if (protoStart != null) {
  4809. this.unexpected(protoStart);
  4810. }
  4811. if (variance) {
  4812. this.unexpected(variance.start);
  4813. }
  4814. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  4815. if (kind === "get" || kind === "set") {
  4816. this.flowCheckGetterSetterParams(node);
  4817. }
  4818. if (!allowSpread && node.key.name === "constructor" && node.value.this) {
  4819. this.raise(node.value.this.start, FlowErrors.ThisParamBannedInConstructor);
  4820. }
  4821. } else {
  4822. if (kind !== "init") this.unexpected();
  4823. node.method = false;
  4824. if (this.eat(17)) {
  4825. optional = true;
  4826. }
  4827. node.value = this.flowParseTypeInitialiser();
  4828. node.variance = variance;
  4829. }
  4830. node.optional = optional;
  4831. return this.finishNode(node, "ObjectTypeProperty");
  4832. }
  4833. }
  4834. flowCheckGetterSetterParams(property) {
  4835. const paramCount = property.kind === "get" ? 0 : 1;
  4836. const start = property.start;
  4837. const length = property.value.params.length + (property.value.rest ? 1 : 0);
  4838. if (property.value.this) {
  4839. this.raise(property.value.this.start, property.kind === "get" ? FlowErrors.GetterMayNotHaveThisParam : FlowErrors.SetterMayNotHaveThisParam);
  4840. }
  4841. if (length !== paramCount) {
  4842. if (property.kind === "get") {
  4843. this.raise(start, ErrorMessages.BadGetterArity);
  4844. } else {
  4845. this.raise(start, ErrorMessages.BadSetterArity);
  4846. }
  4847. }
  4848. if (property.kind === "set" && property.value.rest) {
  4849. this.raise(start, ErrorMessages.BadSetterRestParameter);
  4850. }
  4851. }
  4852. flowObjectTypeSemicolon() {
  4853. if (!this.eat(13) && !this.eat(12) && !this.match(8) && !this.match(9)) {
  4854. this.unexpected();
  4855. }
  4856. }
  4857. flowParseQualifiedTypeIdentifier(startPos, startLoc, id) {
  4858. startPos = startPos || this.state.start;
  4859. startLoc = startLoc || this.state.startLoc;
  4860. let node = id || this.flowParseRestrictedIdentifier(true);
  4861. while (this.eat(16)) {
  4862. const node2 = this.startNodeAt(startPos, startLoc);
  4863. node2.qualification = node;
  4864. node2.id = this.flowParseRestrictedIdentifier(true);
  4865. node = this.finishNode(node2, "QualifiedTypeIdentifier");
  4866. }
  4867. return node;
  4868. }
  4869. flowParseGenericType(startPos, startLoc, id) {
  4870. const node = this.startNodeAt(startPos, startLoc);
  4871. node.typeParameters = null;
  4872. node.id = this.flowParseQualifiedTypeIdentifier(startPos, startLoc, id);
  4873. if (this.match(43)) {
  4874. node.typeParameters = this.flowParseTypeParameterInstantiation();
  4875. }
  4876. return this.finishNode(node, "GenericTypeAnnotation");
  4877. }
  4878. flowParseTypeofType() {
  4879. const node = this.startNode();
  4880. this.expect(81);
  4881. node.argument = this.flowParsePrimaryType();
  4882. return this.finishNode(node, "TypeofTypeAnnotation");
  4883. }
  4884. flowParseTupleType() {
  4885. const node = this.startNode();
  4886. node.types = [];
  4887. this.expect(0);
  4888. while (this.state.pos < this.length && !this.match(3)) {
  4889. node.types.push(this.flowParseType());
  4890. if (this.match(3)) break;
  4891. this.expect(12);
  4892. }
  4893. this.expect(3);
  4894. return this.finishNode(node, "TupleTypeAnnotation");
  4895. }
  4896. flowParseFunctionTypeParam(first) {
  4897. let name = null;
  4898. let optional = false;
  4899. let typeAnnotation = null;
  4900. const node = this.startNode();
  4901. const lh = this.lookahead();
  4902. const isThis = this.state.type === 72;
  4903. if (lh.type === 14 || lh.type === 17) {
  4904. if (isThis && !first) {
  4905. this.raise(node.start, FlowErrors.ThisParamMustBeFirst);
  4906. }
  4907. name = this.parseIdentifier(isThis);
  4908. if (this.eat(17)) {
  4909. optional = true;
  4910. if (isThis) {
  4911. this.raise(node.start, FlowErrors.ThisParamMayNotBeOptional);
  4912. }
  4913. }
  4914. typeAnnotation = this.flowParseTypeInitialiser();
  4915. } else {
  4916. typeAnnotation = this.flowParseType();
  4917. }
  4918. node.name = name;
  4919. node.optional = optional;
  4920. node.typeAnnotation = typeAnnotation;
  4921. return this.finishNode(node, "FunctionTypeParam");
  4922. }
  4923. reinterpretTypeAsFunctionTypeParam(type) {
  4924. const node = this.startNodeAt(type.start, type.loc.start);
  4925. node.name = null;
  4926. node.optional = false;
  4927. node.typeAnnotation = type;
  4928. return this.finishNode(node, "FunctionTypeParam");
  4929. }
  4930. flowParseFunctionTypeParams(params = []) {
  4931. let rest = null;
  4932. let _this = null;
  4933. if (this.match(72)) {
  4934. _this = this.flowParseFunctionTypeParam(true);
  4935. _this.name = null;
  4936. if (!this.match(11)) {
  4937. this.expect(12);
  4938. }
  4939. }
  4940. while (!this.match(11) && !this.match(21)) {
  4941. params.push(this.flowParseFunctionTypeParam(false));
  4942. if (!this.match(11)) {
  4943. this.expect(12);
  4944. }
  4945. }
  4946. if (this.eat(21)) {
  4947. rest = this.flowParseFunctionTypeParam(false);
  4948. }
  4949. return {
  4950. params,
  4951. rest,
  4952. _this
  4953. };
  4954. }
  4955. flowIdentToTypeAnnotation(startPos, startLoc, node, id) {
  4956. switch (id.name) {
  4957. case "any":
  4958. return this.finishNode(node, "AnyTypeAnnotation");
  4959. case "bool":
  4960. case "boolean":
  4961. return this.finishNode(node, "BooleanTypeAnnotation");
  4962. case "mixed":
  4963. return this.finishNode(node, "MixedTypeAnnotation");
  4964. case "empty":
  4965. return this.finishNode(node, "EmptyTypeAnnotation");
  4966. case "number":
  4967. return this.finishNode(node, "NumberTypeAnnotation");
  4968. case "string":
  4969. return this.finishNode(node, "StringTypeAnnotation");
  4970. case "symbol":
  4971. return this.finishNode(node, "SymbolTypeAnnotation");
  4972. default:
  4973. this.checkNotUnderscore(id.name);
  4974. return this.flowParseGenericType(startPos, startLoc, id);
  4975. }
  4976. }
  4977. flowParsePrimaryType() {
  4978. const startPos = this.state.start;
  4979. const startLoc = this.state.startLoc;
  4980. const node = this.startNode();
  4981. let tmp;
  4982. let type;
  4983. let isGroupedType = false;
  4984. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  4985. switch (this.state.type) {
  4986. case 5:
  4987. return this.flowParseObjectType({
  4988. allowStatic: false,
  4989. allowExact: false,
  4990. allowSpread: true,
  4991. allowProto: false,
  4992. allowInexact: true
  4993. });
  4994. case 6:
  4995. return this.flowParseObjectType({
  4996. allowStatic: false,
  4997. allowExact: true,
  4998. allowSpread: true,
  4999. allowProto: false,
  5000. allowInexact: false
  5001. });
  5002. case 0:
  5003. this.state.noAnonFunctionType = false;
  5004. type = this.flowParseTupleType();
  5005. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  5006. return type;
  5007. case 43:
  5008. node.typeParameters = this.flowParseTypeParameterDeclaration();
  5009. this.expect(10);
  5010. tmp = this.flowParseFunctionTypeParams();
  5011. node.params = tmp.params;
  5012. node.rest = tmp.rest;
  5013. node.this = tmp._this;
  5014. this.expect(11);
  5015. this.expect(19);
  5016. node.returnType = this.flowParseType();
  5017. return this.finishNode(node, "FunctionTypeAnnotation");
  5018. case 10:
  5019. this.next();
  5020. if (!this.match(11) && !this.match(21)) {
  5021. if (tokenIsIdentifier(this.state.type) || this.match(72)) {
  5022. const token = this.lookahead().type;
  5023. isGroupedType = token !== 17 && token !== 14;
  5024. } else {
  5025. isGroupedType = true;
  5026. }
  5027. }
  5028. if (isGroupedType) {
  5029. this.state.noAnonFunctionType = false;
  5030. type = this.flowParseType();
  5031. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  5032. if (this.state.noAnonFunctionType || !(this.match(12) || this.match(11) && this.lookahead().type === 19)) {
  5033. this.expect(11);
  5034. return type;
  5035. } else {
  5036. this.eat(12);
  5037. }
  5038. }
  5039. if (type) {
  5040. tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
  5041. } else {
  5042. tmp = this.flowParseFunctionTypeParams();
  5043. }
  5044. node.params = tmp.params;
  5045. node.rest = tmp.rest;
  5046. node.this = tmp._this;
  5047. this.expect(11);
  5048. this.expect(19);
  5049. node.returnType = this.flowParseType();
  5050. node.typeParameters = null;
  5051. return this.finishNode(node, "FunctionTypeAnnotation");
  5052. case 123:
  5053. return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
  5054. case 79:
  5055. case 80:
  5056. node.value = this.match(79);
  5057. this.next();
  5058. return this.finishNode(node, "BooleanLiteralTypeAnnotation");
  5059. case 47:
  5060. if (this.state.value === "-") {
  5061. this.next();
  5062. if (this.match(124)) {
  5063. return this.parseLiteralAtNode(-this.state.value, "NumberLiteralTypeAnnotation", node);
  5064. }
  5065. if (this.match(125)) {
  5066. return this.parseLiteralAtNode(-this.state.value, "BigIntLiteralTypeAnnotation", node);
  5067. }
  5068. throw this.raise(this.state.start, FlowErrors.UnexpectedSubtractionOperand);
  5069. }
  5070. throw this.unexpected();
  5071. case 124:
  5072. return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
  5073. case 125:
  5074. return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation");
  5075. case 82:
  5076. this.next();
  5077. return this.finishNode(node, "VoidTypeAnnotation");
  5078. case 78:
  5079. this.next();
  5080. return this.finishNode(node, "NullLiteralTypeAnnotation");
  5081. case 72:
  5082. this.next();
  5083. return this.finishNode(node, "ThisTypeAnnotation");
  5084. case 49:
  5085. this.next();
  5086. return this.finishNode(node, "ExistsTypeAnnotation");
  5087. case 81:
  5088. return this.flowParseTypeofType();
  5089. default:
  5090. if (tokenIsKeyword(this.state.type)) {
  5091. const label = tokenLabelName(this.state.type);
  5092. this.next();
  5093. return super.createIdentifier(node, label);
  5094. } else if (tokenIsIdentifier(this.state.type)) {
  5095. if (this.isContextual(119)) {
  5096. return this.flowParseInterfaceType();
  5097. }
  5098. return this.flowIdentToTypeAnnotation(startPos, startLoc, node, this.parseIdentifier());
  5099. }
  5100. }
  5101. throw this.unexpected();
  5102. }
  5103. flowParsePostfixType() {
  5104. const startPos = this.state.start;
  5105. const startLoc = this.state.startLoc;
  5106. let type = this.flowParsePrimaryType();
  5107. let seenOptionalIndexedAccess = false;
  5108. while ((this.match(0) || this.match(18)) && !this.canInsertSemicolon()) {
  5109. const node = this.startNodeAt(startPos, startLoc);
  5110. const optional = this.eat(18);
  5111. seenOptionalIndexedAccess = seenOptionalIndexedAccess || optional;
  5112. this.expect(0);
  5113. if (!optional && this.match(3)) {
  5114. node.elementType = type;
  5115. this.next();
  5116. type = this.finishNode(node, "ArrayTypeAnnotation");
  5117. } else {
  5118. node.objectType = type;
  5119. node.indexType = this.flowParseType();
  5120. this.expect(3);
  5121. if (seenOptionalIndexedAccess) {
  5122. node.optional = optional;
  5123. type = this.finishNode(node, "OptionalIndexedAccessType");
  5124. } else {
  5125. type = this.finishNode(node, "IndexedAccessType");
  5126. }
  5127. }
  5128. }
  5129. return type;
  5130. }
  5131. flowParsePrefixType() {
  5132. const node = this.startNode();
  5133. if (this.eat(17)) {
  5134. node.typeAnnotation = this.flowParsePrefixType();
  5135. return this.finishNode(node, "NullableTypeAnnotation");
  5136. } else {
  5137. return this.flowParsePostfixType();
  5138. }
  5139. }
  5140. flowParseAnonFunctionWithoutParens() {
  5141. const param = this.flowParsePrefixType();
  5142. if (!this.state.noAnonFunctionType && this.eat(19)) {
  5143. const node = this.startNodeAt(param.start, param.loc.start);
  5144. node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
  5145. node.rest = null;
  5146. node.this = null;
  5147. node.returnType = this.flowParseType();
  5148. node.typeParameters = null;
  5149. return this.finishNode(node, "FunctionTypeAnnotation");
  5150. }
  5151. return param;
  5152. }
  5153. flowParseIntersectionType() {
  5154. const node = this.startNode();
  5155. this.eat(41);
  5156. const type = this.flowParseAnonFunctionWithoutParens();
  5157. node.types = [type];
  5158. while (this.eat(41)) {
  5159. node.types.push(this.flowParseAnonFunctionWithoutParens());
  5160. }
  5161. return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
  5162. }
  5163. flowParseUnionType() {
  5164. const node = this.startNode();
  5165. this.eat(39);
  5166. const type = this.flowParseIntersectionType();
  5167. node.types = [type];
  5168. while (this.eat(39)) {
  5169. node.types.push(this.flowParseIntersectionType());
  5170. }
  5171. return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
  5172. }
  5173. flowParseType() {
  5174. const oldInType = this.state.inType;
  5175. this.state.inType = true;
  5176. const type = this.flowParseUnionType();
  5177. this.state.inType = oldInType;
  5178. return type;
  5179. }
  5180. flowParseTypeOrImplicitInstantiation() {
  5181. if (this.state.type === 122 && this.state.value === "_") {
  5182. const startPos = this.state.start;
  5183. const startLoc = this.state.startLoc;
  5184. const node = this.parseIdentifier();
  5185. return this.flowParseGenericType(startPos, startLoc, node);
  5186. } else {
  5187. return this.flowParseType();
  5188. }
  5189. }
  5190. flowParseTypeAnnotation() {
  5191. const node = this.startNode();
  5192. node.typeAnnotation = this.flowParseTypeInitialiser();
  5193. return this.finishNode(node, "TypeAnnotation");
  5194. }
  5195. flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) {
  5196. const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier();
  5197. if (this.match(14)) {
  5198. ident.typeAnnotation = this.flowParseTypeAnnotation();
  5199. this.resetEndLocation(ident);
  5200. }
  5201. return ident;
  5202. }
  5203. typeCastToParameter(node) {
  5204. node.expression.typeAnnotation = node.typeAnnotation;
  5205. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  5206. return node.expression;
  5207. }
  5208. flowParseVariance() {
  5209. let variance = null;
  5210. if (this.match(47)) {
  5211. variance = this.startNode();
  5212. if (this.state.value === "+") {
  5213. variance.kind = "plus";
  5214. } else {
  5215. variance.kind = "minus";
  5216. }
  5217. this.next();
  5218. this.finishNode(variance, "Variance");
  5219. }
  5220. return variance;
  5221. }
  5222. parseFunctionBody(node, allowExpressionBody, isMethod = false) {
  5223. if (allowExpressionBody) {
  5224. return this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod));
  5225. }
  5226. return super.parseFunctionBody(node, false, isMethod);
  5227. }
  5228. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  5229. if (this.match(14)) {
  5230. const typeNode = this.startNode();
  5231. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  5232. node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
  5233. }
  5234. super.parseFunctionBodyAndFinish(node, type, isMethod);
  5235. }
  5236. parseStatement(context, topLevel) {
  5237. if (this.state.strict && this.isContextual(119)) {
  5238. const lookahead = this.lookahead();
  5239. if (tokenIsKeywordOrIdentifier(lookahead.type)) {
  5240. const node = this.startNode();
  5241. this.next();
  5242. return this.flowParseInterface(node);
  5243. }
  5244. } else if (this.shouldParseEnums() && this.isContextual(116)) {
  5245. const node = this.startNode();
  5246. this.next();
  5247. return this.flowParseEnumDeclaration(node);
  5248. }
  5249. const stmt = super.parseStatement(context, topLevel);
  5250. if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {
  5251. this.flowPragma = null;
  5252. }
  5253. return stmt;
  5254. }
  5255. parseExpressionStatement(node, expr) {
  5256. if (expr.type === "Identifier") {
  5257. if (expr.name === "declare") {
  5258. if (this.match(74) || tokenIsIdentifier(this.state.type) || this.match(62) || this.match(68) || this.match(76)) {
  5259. return this.flowParseDeclare(node);
  5260. }
  5261. } else if (tokenIsIdentifier(this.state.type)) {
  5262. if (expr.name === "interface") {
  5263. return this.flowParseInterface(node);
  5264. } else if (expr.name === "type") {
  5265. return this.flowParseTypeAlias(node);
  5266. } else if (expr.name === "opaque") {
  5267. return this.flowParseOpaqueType(node, false);
  5268. }
  5269. }
  5270. }
  5271. return super.parseExpressionStatement(node, expr);
  5272. }
  5273. shouldParseExportDeclaration() {
  5274. const {
  5275. type
  5276. } = this.state;
  5277. if (tokenIsFlowInterfaceOrTypeOrOpaque(type) || this.shouldParseEnums() && type === 116) {
  5278. return !this.state.containsEsc;
  5279. }
  5280. return super.shouldParseExportDeclaration();
  5281. }
  5282. isExportDefaultSpecifier() {
  5283. const {
  5284. type
  5285. } = this.state;
  5286. if (tokenIsFlowInterfaceOrTypeOrOpaque(type) || this.shouldParseEnums() && type === 116) {
  5287. return this.state.containsEsc;
  5288. }
  5289. return super.isExportDefaultSpecifier();
  5290. }
  5291. parseExportDefaultExpression() {
  5292. if (this.shouldParseEnums() && this.isContextual(116)) {
  5293. const node = this.startNode();
  5294. this.next();
  5295. return this.flowParseEnumDeclaration(node);
  5296. }
  5297. return super.parseExportDefaultExpression();
  5298. }
  5299. parseConditional(expr, startPos, startLoc, refExpressionErrors) {
  5300. if (!this.match(17)) return expr;
  5301. if (this.state.maybeInArrowParameters) {
  5302. const nextCh = this.lookaheadCharCode();
  5303. if (nextCh === 44 || nextCh === 61 || nextCh === 58 || nextCh === 41) {
  5304. this.setOptionalParametersError(refExpressionErrors);
  5305. return expr;
  5306. }
  5307. }
  5308. this.expect(17);
  5309. const state = this.state.clone();
  5310. const originalNoArrowAt = this.state.noArrowAt;
  5311. const node = this.startNodeAt(startPos, startLoc);
  5312. let {
  5313. consequent,
  5314. failed
  5315. } = this.tryParseConditionalConsequent();
  5316. let [valid, invalid] = this.getArrowLikeExpressions(consequent);
  5317. if (failed || invalid.length > 0) {
  5318. const noArrowAt = [...originalNoArrowAt];
  5319. if (invalid.length > 0) {
  5320. this.state = state;
  5321. this.state.noArrowAt = noArrowAt;
  5322. for (let i = 0; i < invalid.length; i++) {
  5323. noArrowAt.push(invalid[i].start);
  5324. }
  5325. ({
  5326. consequent,
  5327. failed
  5328. } = this.tryParseConditionalConsequent());
  5329. [valid, invalid] = this.getArrowLikeExpressions(consequent);
  5330. }
  5331. if (failed && valid.length > 1) {
  5332. this.raise(state.start, FlowErrors.AmbiguousConditionalArrow);
  5333. }
  5334. if (failed && valid.length === 1) {
  5335. this.state = state;
  5336. noArrowAt.push(valid[0].start);
  5337. this.state.noArrowAt = noArrowAt;
  5338. ({
  5339. consequent,
  5340. failed
  5341. } = this.tryParseConditionalConsequent());
  5342. }
  5343. }
  5344. this.getArrowLikeExpressions(consequent, true);
  5345. this.state.noArrowAt = originalNoArrowAt;
  5346. this.expect(14);
  5347. node.test = expr;
  5348. node.consequent = consequent;
  5349. node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(undefined, undefined));
  5350. return this.finishNode(node, "ConditionalExpression");
  5351. }
  5352. tryParseConditionalConsequent() {
  5353. this.state.noArrowParamsConversionAt.push(this.state.start);
  5354. const consequent = this.parseMaybeAssignAllowIn();
  5355. const failed = !this.match(14);
  5356. this.state.noArrowParamsConversionAt.pop();
  5357. return {
  5358. consequent,
  5359. failed
  5360. };
  5361. }
  5362. getArrowLikeExpressions(node, disallowInvalid) {
  5363. const stack = [node];
  5364. const arrows = [];
  5365. while (stack.length !== 0) {
  5366. const node = stack.pop();
  5367. if (node.type === "ArrowFunctionExpression") {
  5368. if (node.typeParameters || !node.returnType) {
  5369. this.finishArrowValidation(node);
  5370. } else {
  5371. arrows.push(node);
  5372. }
  5373. stack.push(node.body);
  5374. } else if (node.type === "ConditionalExpression") {
  5375. stack.push(node.consequent);
  5376. stack.push(node.alternate);
  5377. }
  5378. }
  5379. if (disallowInvalid) {
  5380. arrows.forEach(node => this.finishArrowValidation(node));
  5381. return [arrows, []];
  5382. }
  5383. return partition(arrows, node => node.params.every(param => this.isAssignable(param, true)));
  5384. }
  5385. finishArrowValidation(node) {
  5386. var _node$extra;
  5387. this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingComma, false);
  5388. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  5389. super.checkParams(node, false, true);
  5390. this.scope.exit();
  5391. }
  5392. forwardNoArrowParamsConversionAt(node, parse) {
  5393. let result;
  5394. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  5395. this.state.noArrowParamsConversionAt.push(this.state.start);
  5396. result = parse();
  5397. this.state.noArrowParamsConversionAt.pop();
  5398. } else {
  5399. result = parse();
  5400. }
  5401. return result;
  5402. }
  5403. parseParenItem(node, startPos, startLoc) {
  5404. node = super.parseParenItem(node, startPos, startLoc);
  5405. if (this.eat(17)) {
  5406. node.optional = true;
  5407. this.resetEndLocation(node);
  5408. }
  5409. if (this.match(14)) {
  5410. const typeCastNode = this.startNodeAt(startPos, startLoc);
  5411. typeCastNode.expression = node;
  5412. typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
  5413. return this.finishNode(typeCastNode, "TypeCastExpression");
  5414. }
  5415. return node;
  5416. }
  5417. assertModuleNodeAllowed(node) {
  5418. if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") {
  5419. return;
  5420. }
  5421. super.assertModuleNodeAllowed(node);
  5422. }
  5423. parseExport(node) {
  5424. const decl = super.parseExport(node);
  5425. if (decl.type === "ExportNamedDeclaration" || decl.type === "ExportAllDeclaration") {
  5426. decl.exportKind = decl.exportKind || "value";
  5427. }
  5428. return decl;
  5429. }
  5430. parseExportDeclaration(node) {
  5431. if (this.isContextual(120)) {
  5432. node.exportKind = "type";
  5433. const declarationNode = this.startNode();
  5434. this.next();
  5435. if (this.match(5)) {
  5436. node.specifiers = this.parseExportSpecifiers(true);
  5437. this.parseExportFrom(node);
  5438. return null;
  5439. } else {
  5440. return this.flowParseTypeAlias(declarationNode);
  5441. }
  5442. } else if (this.isContextual(121)) {
  5443. node.exportKind = "type";
  5444. const declarationNode = this.startNode();
  5445. this.next();
  5446. return this.flowParseOpaqueType(declarationNode, false);
  5447. } else if (this.isContextual(119)) {
  5448. node.exportKind = "type";
  5449. const declarationNode = this.startNode();
  5450. this.next();
  5451. return this.flowParseInterface(declarationNode);
  5452. } else if (this.shouldParseEnums() && this.isContextual(116)) {
  5453. node.exportKind = "value";
  5454. const declarationNode = this.startNode();
  5455. this.next();
  5456. return this.flowParseEnumDeclaration(declarationNode);
  5457. } else {
  5458. return super.parseExportDeclaration(node);
  5459. }
  5460. }
  5461. eatExportStar(node) {
  5462. if (super.eatExportStar(...arguments)) return true;
  5463. if (this.isContextual(120) && this.lookahead().type === 49) {
  5464. node.exportKind = "type";
  5465. this.next();
  5466. this.next();
  5467. return true;
  5468. }
  5469. return false;
  5470. }
  5471. maybeParseExportNamespaceSpecifier(node) {
  5472. const pos = this.state.start;
  5473. const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);
  5474. if (hasNamespace && node.exportKind === "type") {
  5475. this.unexpected(pos);
  5476. }
  5477. return hasNamespace;
  5478. }
  5479. parseClassId(node, isStatement, optionalId) {
  5480. super.parseClassId(node, isStatement, optionalId);
  5481. if (this.match(43)) {
  5482. node.typeParameters = this.flowParseTypeParameterDeclaration();
  5483. }
  5484. }
  5485. parseClassMember(classBody, member, state) {
  5486. const pos = this.state.start;
  5487. if (this.isContextual(115)) {
  5488. if (this.parseClassMemberFromModifier(classBody, member)) {
  5489. return;
  5490. }
  5491. member.declare = true;
  5492. }
  5493. super.parseClassMember(classBody, member, state);
  5494. if (member.declare) {
  5495. if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty" && member.type !== "PropertyDefinition") {
  5496. this.raise(pos, FlowErrors.DeclareClassElement);
  5497. } else if (member.value) {
  5498. this.raise(member.value.start, FlowErrors.DeclareClassFieldInitializer);
  5499. }
  5500. }
  5501. }
  5502. isIterator(word) {
  5503. return word === "iterator" || word === "asyncIterator";
  5504. }
  5505. readIterator() {
  5506. const word = super.readWord1();
  5507. const fullWord = "@@" + word;
  5508. if (!this.isIterator(word) || !this.state.inType) {
  5509. this.raise(this.state.pos, ErrorMessages.InvalidIdentifier, fullWord);
  5510. }
  5511. this.finishToken(122, fullWord);
  5512. }
  5513. getTokenFromCode(code) {
  5514. const next = this.input.charCodeAt(this.state.pos + 1);
  5515. if (code === 123 && next === 124) {
  5516. return this.finishOp(6, 2);
  5517. } else if (this.state.inType && (code === 62 || code === 60)) {
  5518. return this.finishOp(code === 62 ? 44 : 43, 1);
  5519. } else if (this.state.inType && code === 63) {
  5520. if (next === 46) {
  5521. return this.finishOp(18, 2);
  5522. }
  5523. return this.finishOp(17, 1);
  5524. } else if (isIteratorStart(code, next)) {
  5525. this.state.pos += 2;
  5526. return this.readIterator();
  5527. } else {
  5528. return super.getTokenFromCode(code);
  5529. }
  5530. }
  5531. isAssignable(node, isBinding) {
  5532. if (node.type === "TypeCastExpression") {
  5533. return this.isAssignable(node.expression, isBinding);
  5534. } else {
  5535. return super.isAssignable(node, isBinding);
  5536. }
  5537. }
  5538. toAssignable(node, isLHS = false) {
  5539. if (node.type === "TypeCastExpression") {
  5540. return super.toAssignable(this.typeCastToParameter(node), isLHS);
  5541. } else {
  5542. return super.toAssignable(node, isLHS);
  5543. }
  5544. }
  5545. toAssignableList(exprList, trailingCommaPos, isLHS) {
  5546. for (let i = 0; i < exprList.length; i++) {
  5547. const expr = exprList[i];
  5548. if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") {
  5549. exprList[i] = this.typeCastToParameter(expr);
  5550. }
  5551. }
  5552. return super.toAssignableList(exprList, trailingCommaPos, isLHS);
  5553. }
  5554. toReferencedList(exprList, isParenthesizedExpr) {
  5555. for (let i = 0; i < exprList.length; i++) {
  5556. var _expr$extra;
  5557. const expr = exprList[i];
  5558. if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) != null && _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) {
  5559. this.raise(expr.typeAnnotation.start, FlowErrors.TypeCastInPattern);
  5560. }
  5561. }
  5562. return exprList;
  5563. }
  5564. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  5565. const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors);
  5566. if (canBePattern && !this.state.maybeInArrowParameters) {
  5567. this.toReferencedList(node.elements);
  5568. }
  5569. return node;
  5570. }
  5571. checkLVal(expr, ...args) {
  5572. if (expr.type !== "TypeCastExpression") {
  5573. return super.checkLVal(expr, ...args);
  5574. }
  5575. }
  5576. parseClassProperty(node) {
  5577. if (this.match(14)) {
  5578. node.typeAnnotation = this.flowParseTypeAnnotation();
  5579. }
  5580. return super.parseClassProperty(node);
  5581. }
  5582. parseClassPrivateProperty(node) {
  5583. if (this.match(14)) {
  5584. node.typeAnnotation = this.flowParseTypeAnnotation();
  5585. }
  5586. return super.parseClassPrivateProperty(node);
  5587. }
  5588. isClassMethod() {
  5589. return this.match(43) || super.isClassMethod();
  5590. }
  5591. isClassProperty() {
  5592. return this.match(14) || super.isClassProperty();
  5593. }
  5594. isNonstaticConstructor(method) {
  5595. return !this.match(14) && super.isNonstaticConstructor(method);
  5596. }
  5597. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  5598. if (method.variance) {
  5599. this.unexpected(method.variance.start);
  5600. }
  5601. delete method.variance;
  5602. if (this.match(43)) {
  5603. method.typeParameters = this.flowParseTypeParameterDeclaration();
  5604. }
  5605. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  5606. if (method.params && isConstructor) {
  5607. const params = method.params;
  5608. if (params.length > 0 && this.isThisParam(params[0])) {
  5609. this.raise(method.start, FlowErrors.ThisParamBannedInConstructor);
  5610. }
  5611. } else if (method.type === "MethodDefinition" && isConstructor && method.value.params) {
  5612. const params = method.value.params;
  5613. if (params.length > 0 && this.isThisParam(params[0])) {
  5614. this.raise(method.start, FlowErrors.ThisParamBannedInConstructor);
  5615. }
  5616. }
  5617. }
  5618. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  5619. if (method.variance) {
  5620. this.unexpected(method.variance.start);
  5621. }
  5622. delete method.variance;
  5623. if (this.match(43)) {
  5624. method.typeParameters = this.flowParseTypeParameterDeclaration();
  5625. }
  5626. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  5627. }
  5628. parseClassSuper(node) {
  5629. super.parseClassSuper(node);
  5630. if (node.superClass && this.match(43)) {
  5631. node.superTypeParameters = this.flowParseTypeParameterInstantiation();
  5632. }
  5633. if (this.isContextual(104)) {
  5634. this.next();
  5635. const implemented = node.implements = [];
  5636. do {
  5637. const node = this.startNode();
  5638. node.id = this.flowParseRestrictedIdentifier(true);
  5639. if (this.match(43)) {
  5640. node.typeParameters = this.flowParseTypeParameterInstantiation();
  5641. } else {
  5642. node.typeParameters = null;
  5643. }
  5644. implemented.push(this.finishNode(node, "ClassImplements"));
  5645. } while (this.eat(12));
  5646. }
  5647. }
  5648. checkGetterSetterParams(method) {
  5649. super.checkGetterSetterParams(method);
  5650. const params = this.getObjectOrClassMethodParams(method);
  5651. if (params.length > 0) {
  5652. const param = params[0];
  5653. if (this.isThisParam(param) && method.kind === "get") {
  5654. this.raise(param.start, FlowErrors.GetterMayNotHaveThisParam);
  5655. } else if (this.isThisParam(param)) {
  5656. this.raise(param.start, FlowErrors.SetterMayNotHaveThisParam);
  5657. }
  5658. }
  5659. }
  5660. parsePropertyNamePrefixOperator(node) {
  5661. node.variance = this.flowParseVariance();
  5662. }
  5663. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  5664. if (prop.variance) {
  5665. this.unexpected(prop.variance.start);
  5666. }
  5667. delete prop.variance;
  5668. let typeParameters;
  5669. if (this.match(43) && !isAccessor) {
  5670. typeParameters = this.flowParseTypeParameterDeclaration();
  5671. if (!this.match(10)) this.unexpected();
  5672. }
  5673. super.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  5674. if (typeParameters) {
  5675. (prop.value || prop).typeParameters = typeParameters;
  5676. }
  5677. }
  5678. parseAssignableListItemTypes(param) {
  5679. if (this.eat(17)) {
  5680. if (param.type !== "Identifier") {
  5681. this.raise(param.start, FlowErrors.PatternIsOptional);
  5682. }
  5683. if (this.isThisParam(param)) {
  5684. this.raise(param.start, FlowErrors.ThisParamMayNotBeOptional);
  5685. }
  5686. param.optional = true;
  5687. }
  5688. if (this.match(14)) {
  5689. param.typeAnnotation = this.flowParseTypeAnnotation();
  5690. } else if (this.isThisParam(param)) {
  5691. this.raise(param.start, FlowErrors.ThisParamAnnotationRequired);
  5692. }
  5693. if (this.match(27) && this.isThisParam(param)) {
  5694. this.raise(param.start, FlowErrors.ThisParamNoDefault);
  5695. }
  5696. this.resetEndLocation(param);
  5697. return param;
  5698. }
  5699. parseMaybeDefault(startPos, startLoc, left) {
  5700. const node = super.parseMaybeDefault(startPos, startLoc, left);
  5701. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  5702. this.raise(node.typeAnnotation.start, FlowErrors.TypeBeforeInitializer);
  5703. }
  5704. return node;
  5705. }
  5706. shouldParseDefaultImport(node) {
  5707. if (!hasTypeImportKind(node)) {
  5708. return super.shouldParseDefaultImport(node);
  5709. }
  5710. return isMaybeDefaultImport(this.state.type);
  5711. }
  5712. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  5713. specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier();
  5714. this.checkLVal(specifier.local, contextDescription, BIND_LEXICAL);
  5715. node.specifiers.push(this.finishNode(specifier, type));
  5716. }
  5717. maybeParseDefaultImportSpecifier(node) {
  5718. node.importKind = "value";
  5719. let kind = null;
  5720. if (this.match(81)) {
  5721. kind = "typeof";
  5722. } else if (this.isContextual(120)) {
  5723. kind = "type";
  5724. }
  5725. if (kind) {
  5726. const lh = this.lookahead();
  5727. const {
  5728. type
  5729. } = lh;
  5730. if (kind === "type" && type === 49) {
  5731. this.unexpected(lh.start);
  5732. }
  5733. if (isMaybeDefaultImport(type) || type === 5 || type === 49) {
  5734. this.next();
  5735. node.importKind = kind;
  5736. }
  5737. }
  5738. return super.maybeParseDefaultImportSpecifier(node);
  5739. }
  5740. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly) {
  5741. const firstIdent = specifier.imported;
  5742. let specifierTypeKind = null;
  5743. if (firstIdent.type === "Identifier") {
  5744. if (firstIdent.name === "type") {
  5745. specifierTypeKind = "type";
  5746. } else if (firstIdent.name === "typeof") {
  5747. specifierTypeKind = "typeof";
  5748. }
  5749. }
  5750. let isBinding = false;
  5751. if (this.isContextual(87) && !this.isLookaheadContextual("as")) {
  5752. const as_ident = this.parseIdentifier(true);
  5753. if (specifierTypeKind !== null && !tokenIsKeywordOrIdentifier(this.state.type)) {
  5754. specifier.imported = as_ident;
  5755. specifier.importKind = specifierTypeKind;
  5756. specifier.local = cloneIdentifier(as_ident);
  5757. } else {
  5758. specifier.imported = firstIdent;
  5759. specifier.importKind = null;
  5760. specifier.local = this.parseIdentifier();
  5761. }
  5762. } else {
  5763. if (specifierTypeKind !== null && tokenIsKeywordOrIdentifier(this.state.type)) {
  5764. specifier.imported = this.parseIdentifier(true);
  5765. specifier.importKind = specifierTypeKind;
  5766. } else {
  5767. if (importedIsString) {
  5768. throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, firstIdent.value);
  5769. }
  5770. specifier.imported = firstIdent;
  5771. specifier.importKind = null;
  5772. }
  5773. if (this.eatContextual(87)) {
  5774. specifier.local = this.parseIdentifier();
  5775. } else {
  5776. isBinding = true;
  5777. specifier.local = cloneIdentifier(specifier.imported);
  5778. }
  5779. }
  5780. const specifierIsTypeImport = hasTypeImportKind(specifier);
  5781. if (isInTypeOnlyImport && specifierIsTypeImport) {
  5782. this.raise(specifier.start, FlowErrors.ImportTypeShorthandOnlyInPureImport);
  5783. }
  5784. if (isInTypeOnlyImport || specifierIsTypeImport) {
  5785. this.checkReservedType(specifier.local.name, specifier.local.start, true);
  5786. }
  5787. if (isBinding && !isInTypeOnlyImport && !specifierIsTypeImport) {
  5788. this.checkReservedWord(specifier.local.name, specifier.start, true, true);
  5789. }
  5790. this.checkLVal(specifier.local, "import specifier", BIND_LEXICAL);
  5791. return this.finishNode(specifier, "ImportSpecifier");
  5792. }
  5793. parseBindingAtom() {
  5794. switch (this.state.type) {
  5795. case 72:
  5796. return this.parseIdentifier(true);
  5797. default:
  5798. return super.parseBindingAtom();
  5799. }
  5800. }
  5801. parseFunctionParams(node, allowModifiers) {
  5802. const kind = node.kind;
  5803. if (kind !== "get" && kind !== "set" && this.match(43)) {
  5804. node.typeParameters = this.flowParseTypeParameterDeclaration();
  5805. }
  5806. super.parseFunctionParams(node, allowModifiers);
  5807. }
  5808. parseVarId(decl, kind) {
  5809. super.parseVarId(decl, kind);
  5810. if (this.match(14)) {
  5811. decl.id.typeAnnotation = this.flowParseTypeAnnotation();
  5812. this.resetEndLocation(decl.id);
  5813. }
  5814. }
  5815. parseAsyncArrowFromCallExpression(node, call) {
  5816. if (this.match(14)) {
  5817. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  5818. this.state.noAnonFunctionType = true;
  5819. node.returnType = this.flowParseTypeAnnotation();
  5820. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  5821. }
  5822. return super.parseAsyncArrowFromCallExpression(node, call);
  5823. }
  5824. shouldParseAsyncArrow() {
  5825. return this.match(14) || super.shouldParseAsyncArrow();
  5826. }
  5827. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  5828. var _jsx;
  5829. let state = null;
  5830. let jsx;
  5831. if (this.hasPlugin("jsx") && (this.match(132) || this.match(43))) {
  5832. state = this.state.clone();
  5833. jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
  5834. if (!jsx.error) return jsx.node;
  5835. const {
  5836. context
  5837. } = this.state;
  5838. const curContext = context[context.length - 1];
  5839. if (curContext === types.j_oTag) {
  5840. context.length -= 2;
  5841. } else if (curContext === types.j_expr) {
  5842. context.length -= 1;
  5843. }
  5844. }
  5845. if ((_jsx = jsx) != null && _jsx.error || this.match(43)) {
  5846. var _jsx2, _jsx3;
  5847. state = state || this.state.clone();
  5848. let typeParameters;
  5849. const arrow = this.tryParse(abort => {
  5850. var _arrowExpression$extr;
  5851. typeParameters = this.flowParseTypeParameterDeclaration();
  5852. const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => {
  5853. const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  5854. this.resetStartLocationFromNode(result, typeParameters);
  5855. return result;
  5856. });
  5857. if ((_arrowExpression$extr = arrowExpression.extra) != null && _arrowExpression$extr.parenthesized) abort();
  5858. const expr = this.maybeUnwrapTypeCastExpression(arrowExpression);
  5859. if (expr.type !== "ArrowFunctionExpression") abort();
  5860. expr.typeParameters = typeParameters;
  5861. this.resetStartLocationFromNode(expr, typeParameters);
  5862. return arrowExpression;
  5863. }, state);
  5864. let arrowExpression = null;
  5865. if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") {
  5866. if (!arrow.error && !arrow.aborted) {
  5867. if (arrow.node.async) {
  5868. this.raise(typeParameters.start, FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction);
  5869. }
  5870. return arrow.node;
  5871. }
  5872. arrowExpression = arrow.node;
  5873. }
  5874. if ((_jsx2 = jsx) != null && _jsx2.node) {
  5875. this.state = jsx.failState;
  5876. return jsx.node;
  5877. }
  5878. if (arrowExpression) {
  5879. this.state = arrow.failState;
  5880. return arrowExpression;
  5881. }
  5882. if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error;
  5883. if (arrow.thrown) throw arrow.error;
  5884. throw this.raise(typeParameters.start, FlowErrors.UnexpectedTokenAfterTypeParameter);
  5885. }
  5886. return super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  5887. }
  5888. parseArrow(node) {
  5889. if (this.match(14)) {
  5890. const result = this.tryParse(() => {
  5891. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  5892. this.state.noAnonFunctionType = true;
  5893. const typeNode = this.startNode();
  5894. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  5895. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  5896. if (this.canInsertSemicolon()) this.unexpected();
  5897. if (!this.match(19)) this.unexpected();
  5898. return typeNode;
  5899. });
  5900. if (result.thrown) return null;
  5901. if (result.error) this.state = result.failState;
  5902. node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null;
  5903. }
  5904. return super.parseArrow(node);
  5905. }
  5906. shouldParseArrow(params) {
  5907. return this.match(14) || super.shouldParseArrow(params);
  5908. }
  5909. setArrowFunctionParameters(node, params) {
  5910. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  5911. node.params = params;
  5912. } else {
  5913. super.setArrowFunctionParameters(node, params);
  5914. }
  5915. }
  5916. checkParams(node, allowDuplicates, isArrowFunction) {
  5917. if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  5918. return;
  5919. }
  5920. for (let i = 0; i < node.params.length; i++) {
  5921. if (this.isThisParam(node.params[i]) && i > 0) {
  5922. this.raise(node.params[i].start, FlowErrors.ThisParamMustBeFirst);
  5923. }
  5924. }
  5925. return super.checkParams(...arguments);
  5926. }
  5927. parseParenAndDistinguishExpression(canBeArrow) {
  5928. return super.parseParenAndDistinguishExpression(canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1);
  5929. }
  5930. parseSubscripts(base, startPos, startLoc, noCalls) {
  5931. if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.indexOf(startPos) !== -1) {
  5932. this.next();
  5933. const node = this.startNodeAt(startPos, startLoc);
  5934. node.callee = base;
  5935. node.arguments = this.parseCallExpressionArguments(11, false);
  5936. base = this.finishNode(node, "CallExpression");
  5937. } else if (base.type === "Identifier" && base.name === "async" && this.match(43)) {
  5938. const state = this.state.clone();
  5939. const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startPos, startLoc) || abort(), state);
  5940. if (!arrow.error && !arrow.aborted) return arrow.node;
  5941. const result = this.tryParse(() => super.parseSubscripts(base, startPos, startLoc, noCalls), state);
  5942. if (result.node && !result.error) return result.node;
  5943. if (arrow.node) {
  5944. this.state = arrow.failState;
  5945. return arrow.node;
  5946. }
  5947. if (result.node) {
  5948. this.state = result.failState;
  5949. return result.node;
  5950. }
  5951. throw arrow.error || result.error;
  5952. }
  5953. return super.parseSubscripts(base, startPos, startLoc, noCalls);
  5954. }
  5955. parseSubscript(base, startPos, startLoc, noCalls, subscriptState) {
  5956. if (this.match(18) && this.isLookaheadToken_lt()) {
  5957. subscriptState.optionalChainMember = true;
  5958. if (noCalls) {
  5959. subscriptState.stop = true;
  5960. return base;
  5961. }
  5962. this.next();
  5963. const node = this.startNodeAt(startPos, startLoc);
  5964. node.callee = base;
  5965. node.typeArguments = this.flowParseTypeParameterInstantiation();
  5966. this.expect(10);
  5967. node.arguments = this.parseCallExpressionArguments(11, false);
  5968. node.optional = true;
  5969. return this.finishCallExpression(node, true);
  5970. } else if (!noCalls && this.shouldParseTypes() && this.match(43)) {
  5971. const node = this.startNodeAt(startPos, startLoc);
  5972. node.callee = base;
  5973. const result = this.tryParse(() => {
  5974. node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew();
  5975. this.expect(10);
  5976. node.arguments = this.parseCallExpressionArguments(11, false);
  5977. if (subscriptState.optionalChainMember) node.optional = false;
  5978. return this.finishCallExpression(node, subscriptState.optionalChainMember);
  5979. });
  5980. if (result.node) {
  5981. if (result.error) this.state = result.failState;
  5982. return result.node;
  5983. }
  5984. }
  5985. return super.parseSubscript(base, startPos, startLoc, noCalls, subscriptState);
  5986. }
  5987. parseNewArguments(node) {
  5988. let targs = null;
  5989. if (this.shouldParseTypes() && this.match(43)) {
  5990. targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node;
  5991. }
  5992. node.typeArguments = targs;
  5993. super.parseNewArguments(node);
  5994. }
  5995. parseAsyncArrowWithTypeParameters(startPos, startLoc) {
  5996. const node = this.startNodeAt(startPos, startLoc);
  5997. this.parseFunctionParams(node);
  5998. if (!this.parseArrow(node)) return;
  5999. return this.parseArrowExpression(node, undefined, true);
  6000. }
  6001. readToken_mult_modulo(code) {
  6002. const next = this.input.charCodeAt(this.state.pos + 1);
  6003. if (code === 42 && next === 47 && this.state.hasFlowComment) {
  6004. this.state.hasFlowComment = false;
  6005. this.state.pos += 2;
  6006. this.nextToken();
  6007. return;
  6008. }
  6009. super.readToken_mult_modulo(code);
  6010. }
  6011. readToken_pipe_amp(code) {
  6012. const next = this.input.charCodeAt(this.state.pos + 1);
  6013. if (code === 124 && next === 125) {
  6014. this.finishOp(9, 2);
  6015. return;
  6016. }
  6017. super.readToken_pipe_amp(code);
  6018. }
  6019. parseTopLevel(file, program) {
  6020. const fileNode = super.parseTopLevel(file, program);
  6021. if (this.state.hasFlowComment) {
  6022. this.raise(this.state.pos, FlowErrors.UnterminatedFlowComment);
  6023. }
  6024. return fileNode;
  6025. }
  6026. skipBlockComment() {
  6027. if (this.hasPlugin("flowComments") && this.skipFlowComment()) {
  6028. if (this.state.hasFlowComment) {
  6029. this.unexpected(null, FlowErrors.NestedFlowComment);
  6030. }
  6031. this.hasFlowCommentCompletion();
  6032. this.state.pos += this.skipFlowComment();
  6033. this.state.hasFlowComment = true;
  6034. return;
  6035. }
  6036. if (this.state.hasFlowComment) {
  6037. const end = this.input.indexOf("*-/", this.state.pos += 2);
  6038. if (end === -1) {
  6039. throw this.raise(this.state.pos - 2, ErrorMessages.UnterminatedComment);
  6040. }
  6041. this.state.pos = end + 3;
  6042. return;
  6043. }
  6044. return super.skipBlockComment();
  6045. }
  6046. skipFlowComment() {
  6047. const {
  6048. pos
  6049. } = this.state;
  6050. let shiftToFirstNonWhiteSpace = 2;
  6051. while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) {
  6052. shiftToFirstNonWhiteSpace++;
  6053. }
  6054. const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);
  6055. const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);
  6056. if (ch2 === 58 && ch3 === 58) {
  6057. return shiftToFirstNonWhiteSpace + 2;
  6058. }
  6059. if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") {
  6060. return shiftToFirstNonWhiteSpace + 12;
  6061. }
  6062. if (ch2 === 58 && ch3 !== 58) {
  6063. return shiftToFirstNonWhiteSpace;
  6064. }
  6065. return false;
  6066. }
  6067. hasFlowCommentCompletion() {
  6068. const end = this.input.indexOf("*/", this.state.pos);
  6069. if (end === -1) {
  6070. throw this.raise(this.state.pos, ErrorMessages.UnterminatedComment);
  6071. }
  6072. }
  6073. flowEnumErrorBooleanMemberNotInitialized(pos, {
  6074. enumName,
  6075. memberName
  6076. }) {
  6077. this.raise(pos, FlowErrors.EnumBooleanMemberNotInitialized, memberName, enumName);
  6078. }
  6079. flowEnumErrorInvalidMemberName(pos, {
  6080. enumName,
  6081. memberName
  6082. }) {
  6083. const suggestion = memberName[0].toUpperCase() + memberName.slice(1);
  6084. this.raise(pos, FlowErrors.EnumInvalidMemberName, memberName, suggestion, enumName);
  6085. }
  6086. flowEnumErrorDuplicateMemberName(pos, {
  6087. enumName,
  6088. memberName
  6089. }) {
  6090. this.raise(pos, FlowErrors.EnumDuplicateMemberName, memberName, enumName);
  6091. }
  6092. flowEnumErrorInconsistentMemberValues(pos, {
  6093. enumName
  6094. }) {
  6095. this.raise(pos, FlowErrors.EnumInconsistentMemberValues, enumName);
  6096. }
  6097. flowEnumErrorInvalidExplicitType(pos, {
  6098. enumName,
  6099. suppliedType
  6100. }) {
  6101. return this.raise(pos, suppliedType === null ? FlowErrors.EnumInvalidExplicitTypeUnknownSupplied : FlowErrors.EnumInvalidExplicitType, enumName, suppliedType);
  6102. }
  6103. flowEnumErrorInvalidMemberInitializer(pos, {
  6104. enumName,
  6105. explicitType,
  6106. memberName
  6107. }) {
  6108. let message = null;
  6109. switch (explicitType) {
  6110. case "boolean":
  6111. case "number":
  6112. case "string":
  6113. message = FlowErrors.EnumInvalidMemberInitializerPrimaryType;
  6114. break;
  6115. case "symbol":
  6116. message = FlowErrors.EnumInvalidMemberInitializerSymbolType;
  6117. break;
  6118. default:
  6119. message = FlowErrors.EnumInvalidMemberInitializerUnknownType;
  6120. }
  6121. return this.raise(pos, message, enumName, memberName, explicitType);
  6122. }
  6123. flowEnumErrorNumberMemberNotInitialized(pos, {
  6124. enumName,
  6125. memberName
  6126. }) {
  6127. this.raise(pos, FlowErrors.EnumNumberMemberNotInitialized, enumName, memberName);
  6128. }
  6129. flowEnumErrorStringMemberInconsistentlyInitailized(pos, {
  6130. enumName
  6131. }) {
  6132. this.raise(pos, FlowErrors.EnumStringMemberInconsistentlyInitailized, enumName);
  6133. }
  6134. flowEnumMemberInit() {
  6135. const startPos = this.state.start;
  6136. const endOfInit = () => this.match(12) || this.match(8);
  6137. switch (this.state.type) {
  6138. case 124:
  6139. {
  6140. const literal = this.parseNumericLiteral(this.state.value);
  6141. if (endOfInit()) {
  6142. return {
  6143. type: "number",
  6144. pos: literal.start,
  6145. value: literal
  6146. };
  6147. }
  6148. return {
  6149. type: "invalid",
  6150. pos: startPos
  6151. };
  6152. }
  6153. case 123:
  6154. {
  6155. const literal = this.parseStringLiteral(this.state.value);
  6156. if (endOfInit()) {
  6157. return {
  6158. type: "string",
  6159. pos: literal.start,
  6160. value: literal
  6161. };
  6162. }
  6163. return {
  6164. type: "invalid",
  6165. pos: startPos
  6166. };
  6167. }
  6168. case 79:
  6169. case 80:
  6170. {
  6171. const literal = this.parseBooleanLiteral(this.match(79));
  6172. if (endOfInit()) {
  6173. return {
  6174. type: "boolean",
  6175. pos: literal.start,
  6176. value: literal
  6177. };
  6178. }
  6179. return {
  6180. type: "invalid",
  6181. pos: startPos
  6182. };
  6183. }
  6184. default:
  6185. return {
  6186. type: "invalid",
  6187. pos: startPos
  6188. };
  6189. }
  6190. }
  6191. flowEnumMemberRaw() {
  6192. const pos = this.state.start;
  6193. const id = this.parseIdentifier(true);
  6194. const init = this.eat(27) ? this.flowEnumMemberInit() : {
  6195. type: "none",
  6196. pos
  6197. };
  6198. return {
  6199. id,
  6200. init
  6201. };
  6202. }
  6203. flowEnumCheckExplicitTypeMismatch(pos, context, expectedType) {
  6204. const {
  6205. explicitType
  6206. } = context;
  6207. if (explicitType === null) {
  6208. return;
  6209. }
  6210. if (explicitType !== expectedType) {
  6211. this.flowEnumErrorInvalidMemberInitializer(pos, context);
  6212. }
  6213. }
  6214. flowEnumMembers({
  6215. enumName,
  6216. explicitType
  6217. }) {
  6218. const seenNames = new Set();
  6219. const members = {
  6220. booleanMembers: [],
  6221. numberMembers: [],
  6222. stringMembers: [],
  6223. defaultedMembers: []
  6224. };
  6225. let hasUnknownMembers = false;
  6226. while (!this.match(8)) {
  6227. if (this.eat(21)) {
  6228. hasUnknownMembers = true;
  6229. break;
  6230. }
  6231. const memberNode = this.startNode();
  6232. const {
  6233. id,
  6234. init
  6235. } = this.flowEnumMemberRaw();
  6236. const memberName = id.name;
  6237. if (memberName === "") {
  6238. continue;
  6239. }
  6240. if (/^[a-z]/.test(memberName)) {
  6241. this.flowEnumErrorInvalidMemberName(id.start, {
  6242. enumName,
  6243. memberName
  6244. });
  6245. }
  6246. if (seenNames.has(memberName)) {
  6247. this.flowEnumErrorDuplicateMemberName(id.start, {
  6248. enumName,
  6249. memberName
  6250. });
  6251. }
  6252. seenNames.add(memberName);
  6253. const context = {
  6254. enumName,
  6255. explicitType,
  6256. memberName
  6257. };
  6258. memberNode.id = id;
  6259. switch (init.type) {
  6260. case "boolean":
  6261. {
  6262. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "boolean");
  6263. memberNode.init = init.value;
  6264. members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember"));
  6265. break;
  6266. }
  6267. case "number":
  6268. {
  6269. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "number");
  6270. memberNode.init = init.value;
  6271. members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember"));
  6272. break;
  6273. }
  6274. case "string":
  6275. {
  6276. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "string");
  6277. memberNode.init = init.value;
  6278. members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember"));
  6279. break;
  6280. }
  6281. case "invalid":
  6282. {
  6283. throw this.flowEnumErrorInvalidMemberInitializer(init.pos, context);
  6284. }
  6285. case "none":
  6286. {
  6287. switch (explicitType) {
  6288. case "boolean":
  6289. this.flowEnumErrorBooleanMemberNotInitialized(init.pos, context);
  6290. break;
  6291. case "number":
  6292. this.flowEnumErrorNumberMemberNotInitialized(init.pos, context);
  6293. break;
  6294. default:
  6295. members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember"));
  6296. }
  6297. }
  6298. }
  6299. if (!this.match(8)) {
  6300. this.expect(12);
  6301. }
  6302. }
  6303. return {
  6304. members,
  6305. hasUnknownMembers
  6306. };
  6307. }
  6308. flowEnumStringMembers(initializedMembers, defaultedMembers, {
  6309. enumName
  6310. }) {
  6311. if (initializedMembers.length === 0) {
  6312. return defaultedMembers;
  6313. } else if (defaultedMembers.length === 0) {
  6314. return initializedMembers;
  6315. } else if (defaultedMembers.length > initializedMembers.length) {
  6316. for (const member of initializedMembers) {
  6317. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  6318. enumName
  6319. });
  6320. }
  6321. return defaultedMembers;
  6322. } else {
  6323. for (const member of defaultedMembers) {
  6324. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  6325. enumName
  6326. });
  6327. }
  6328. return initializedMembers;
  6329. }
  6330. }
  6331. flowEnumParseExplicitType({
  6332. enumName
  6333. }) {
  6334. if (this.eatContextual(95)) {
  6335. if (!tokenIsIdentifier(this.state.type)) {
  6336. throw this.flowEnumErrorInvalidExplicitType(this.state.start, {
  6337. enumName,
  6338. suppliedType: null
  6339. });
  6340. }
  6341. const {
  6342. value
  6343. } = this.state;
  6344. this.next();
  6345. if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") {
  6346. this.flowEnumErrorInvalidExplicitType(this.state.start, {
  6347. enumName,
  6348. suppliedType: value
  6349. });
  6350. }
  6351. return value;
  6352. }
  6353. return null;
  6354. }
  6355. flowEnumBody(node, {
  6356. enumName,
  6357. nameLoc
  6358. }) {
  6359. const explicitType = this.flowEnumParseExplicitType({
  6360. enumName
  6361. });
  6362. this.expect(5);
  6363. const {
  6364. members,
  6365. hasUnknownMembers
  6366. } = this.flowEnumMembers({
  6367. enumName,
  6368. explicitType
  6369. });
  6370. node.hasUnknownMembers = hasUnknownMembers;
  6371. switch (explicitType) {
  6372. case "boolean":
  6373. node.explicitType = true;
  6374. node.members = members.booleanMembers;
  6375. this.expect(8);
  6376. return this.finishNode(node, "EnumBooleanBody");
  6377. case "number":
  6378. node.explicitType = true;
  6379. node.members = members.numberMembers;
  6380. this.expect(8);
  6381. return this.finishNode(node, "EnumNumberBody");
  6382. case "string":
  6383. node.explicitType = true;
  6384. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  6385. enumName
  6386. });
  6387. this.expect(8);
  6388. return this.finishNode(node, "EnumStringBody");
  6389. case "symbol":
  6390. node.members = members.defaultedMembers;
  6391. this.expect(8);
  6392. return this.finishNode(node, "EnumSymbolBody");
  6393. default:
  6394. {
  6395. const empty = () => {
  6396. node.members = [];
  6397. this.expect(8);
  6398. return this.finishNode(node, "EnumStringBody");
  6399. };
  6400. node.explicitType = false;
  6401. const boolsLen = members.booleanMembers.length;
  6402. const numsLen = members.numberMembers.length;
  6403. const strsLen = members.stringMembers.length;
  6404. const defaultedLen = members.defaultedMembers.length;
  6405. if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {
  6406. return empty();
  6407. } else if (!boolsLen && !numsLen) {
  6408. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  6409. enumName
  6410. });
  6411. this.expect(8);
  6412. return this.finishNode(node, "EnumStringBody");
  6413. } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {
  6414. for (const member of members.defaultedMembers) {
  6415. this.flowEnumErrorBooleanMemberNotInitialized(member.start, {
  6416. enumName,
  6417. memberName: member.id.name
  6418. });
  6419. }
  6420. node.members = members.booleanMembers;
  6421. this.expect(8);
  6422. return this.finishNode(node, "EnumBooleanBody");
  6423. } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {
  6424. for (const member of members.defaultedMembers) {
  6425. this.flowEnumErrorNumberMemberNotInitialized(member.start, {
  6426. enumName,
  6427. memberName: member.id.name
  6428. });
  6429. }
  6430. node.members = members.numberMembers;
  6431. this.expect(8);
  6432. return this.finishNode(node, "EnumNumberBody");
  6433. } else {
  6434. this.flowEnumErrorInconsistentMemberValues(nameLoc, {
  6435. enumName
  6436. });
  6437. return empty();
  6438. }
  6439. }
  6440. }
  6441. }
  6442. flowParseEnumDeclaration(node) {
  6443. const id = this.parseIdentifier();
  6444. node.id = id;
  6445. node.body = this.flowEnumBody(this.startNode(), {
  6446. enumName: id.name,
  6447. nameLoc: id.start
  6448. });
  6449. return this.finishNode(node, "EnumDeclaration");
  6450. }
  6451. isLookaheadToken_lt() {
  6452. const next = this.nextTokenStart();
  6453. if (this.input.charCodeAt(next) === 60) {
  6454. const afterNext = this.input.charCodeAt(next + 1);
  6455. return afterNext !== 60 && afterNext !== 61;
  6456. }
  6457. return false;
  6458. }
  6459. maybeUnwrapTypeCastExpression(node) {
  6460. return node.type === "TypeCastExpression" ? node.expression : node;
  6461. }
  6462. });
  6463. const entities = {
  6464. quot: "\u0022",
  6465. amp: "&",
  6466. apos: "\u0027",
  6467. lt: "<",
  6468. gt: ">",
  6469. nbsp: "\u00A0",
  6470. iexcl: "\u00A1",
  6471. cent: "\u00A2",
  6472. pound: "\u00A3",
  6473. curren: "\u00A4",
  6474. yen: "\u00A5",
  6475. brvbar: "\u00A6",
  6476. sect: "\u00A7",
  6477. uml: "\u00A8",
  6478. copy: "\u00A9",
  6479. ordf: "\u00AA",
  6480. laquo: "\u00AB",
  6481. not: "\u00AC",
  6482. shy: "\u00AD",
  6483. reg: "\u00AE",
  6484. macr: "\u00AF",
  6485. deg: "\u00B0",
  6486. plusmn: "\u00B1",
  6487. sup2: "\u00B2",
  6488. sup3: "\u00B3",
  6489. acute: "\u00B4",
  6490. micro: "\u00B5",
  6491. para: "\u00B6",
  6492. middot: "\u00B7",
  6493. cedil: "\u00B8",
  6494. sup1: "\u00B9",
  6495. ordm: "\u00BA",
  6496. raquo: "\u00BB",
  6497. frac14: "\u00BC",
  6498. frac12: "\u00BD",
  6499. frac34: "\u00BE",
  6500. iquest: "\u00BF",
  6501. Agrave: "\u00C0",
  6502. Aacute: "\u00C1",
  6503. Acirc: "\u00C2",
  6504. Atilde: "\u00C3",
  6505. Auml: "\u00C4",
  6506. Aring: "\u00C5",
  6507. AElig: "\u00C6",
  6508. Ccedil: "\u00C7",
  6509. Egrave: "\u00C8",
  6510. Eacute: "\u00C9",
  6511. Ecirc: "\u00CA",
  6512. Euml: "\u00CB",
  6513. Igrave: "\u00CC",
  6514. Iacute: "\u00CD",
  6515. Icirc: "\u00CE",
  6516. Iuml: "\u00CF",
  6517. ETH: "\u00D0",
  6518. Ntilde: "\u00D1",
  6519. Ograve: "\u00D2",
  6520. Oacute: "\u00D3",
  6521. Ocirc: "\u00D4",
  6522. Otilde: "\u00D5",
  6523. Ouml: "\u00D6",
  6524. times: "\u00D7",
  6525. Oslash: "\u00D8",
  6526. Ugrave: "\u00D9",
  6527. Uacute: "\u00DA",
  6528. Ucirc: "\u00DB",
  6529. Uuml: "\u00DC",
  6530. Yacute: "\u00DD",
  6531. THORN: "\u00DE",
  6532. szlig: "\u00DF",
  6533. agrave: "\u00E0",
  6534. aacute: "\u00E1",
  6535. acirc: "\u00E2",
  6536. atilde: "\u00E3",
  6537. auml: "\u00E4",
  6538. aring: "\u00E5",
  6539. aelig: "\u00E6",
  6540. ccedil: "\u00E7",
  6541. egrave: "\u00E8",
  6542. eacute: "\u00E9",
  6543. ecirc: "\u00EA",
  6544. euml: "\u00EB",
  6545. igrave: "\u00EC",
  6546. iacute: "\u00ED",
  6547. icirc: "\u00EE",
  6548. iuml: "\u00EF",
  6549. eth: "\u00F0",
  6550. ntilde: "\u00F1",
  6551. ograve: "\u00F2",
  6552. oacute: "\u00F3",
  6553. ocirc: "\u00F4",
  6554. otilde: "\u00F5",
  6555. ouml: "\u00F6",
  6556. divide: "\u00F7",
  6557. oslash: "\u00F8",
  6558. ugrave: "\u00F9",
  6559. uacute: "\u00FA",
  6560. ucirc: "\u00FB",
  6561. uuml: "\u00FC",
  6562. yacute: "\u00FD",
  6563. thorn: "\u00FE",
  6564. yuml: "\u00FF",
  6565. OElig: "\u0152",
  6566. oelig: "\u0153",
  6567. Scaron: "\u0160",
  6568. scaron: "\u0161",
  6569. Yuml: "\u0178",
  6570. fnof: "\u0192",
  6571. circ: "\u02C6",
  6572. tilde: "\u02DC",
  6573. Alpha: "\u0391",
  6574. Beta: "\u0392",
  6575. Gamma: "\u0393",
  6576. Delta: "\u0394",
  6577. Epsilon: "\u0395",
  6578. Zeta: "\u0396",
  6579. Eta: "\u0397",
  6580. Theta: "\u0398",
  6581. Iota: "\u0399",
  6582. Kappa: "\u039A",
  6583. Lambda: "\u039B",
  6584. Mu: "\u039C",
  6585. Nu: "\u039D",
  6586. Xi: "\u039E",
  6587. Omicron: "\u039F",
  6588. Pi: "\u03A0",
  6589. Rho: "\u03A1",
  6590. Sigma: "\u03A3",
  6591. Tau: "\u03A4",
  6592. Upsilon: "\u03A5",
  6593. Phi: "\u03A6",
  6594. Chi: "\u03A7",
  6595. Psi: "\u03A8",
  6596. Omega: "\u03A9",
  6597. alpha: "\u03B1",
  6598. beta: "\u03B2",
  6599. gamma: "\u03B3",
  6600. delta: "\u03B4",
  6601. epsilon: "\u03B5",
  6602. zeta: "\u03B6",
  6603. eta: "\u03B7",
  6604. theta: "\u03B8",
  6605. iota: "\u03B9",
  6606. kappa: "\u03BA",
  6607. lambda: "\u03BB",
  6608. mu: "\u03BC",
  6609. nu: "\u03BD",
  6610. xi: "\u03BE",
  6611. omicron: "\u03BF",
  6612. pi: "\u03C0",
  6613. rho: "\u03C1",
  6614. sigmaf: "\u03C2",
  6615. sigma: "\u03C3",
  6616. tau: "\u03C4",
  6617. upsilon: "\u03C5",
  6618. phi: "\u03C6",
  6619. chi: "\u03C7",
  6620. psi: "\u03C8",
  6621. omega: "\u03C9",
  6622. thetasym: "\u03D1",
  6623. upsih: "\u03D2",
  6624. piv: "\u03D6",
  6625. ensp: "\u2002",
  6626. emsp: "\u2003",
  6627. thinsp: "\u2009",
  6628. zwnj: "\u200C",
  6629. zwj: "\u200D",
  6630. lrm: "\u200E",
  6631. rlm: "\u200F",
  6632. ndash: "\u2013",
  6633. mdash: "\u2014",
  6634. lsquo: "\u2018",
  6635. rsquo: "\u2019",
  6636. sbquo: "\u201A",
  6637. ldquo: "\u201C",
  6638. rdquo: "\u201D",
  6639. bdquo: "\u201E",
  6640. dagger: "\u2020",
  6641. Dagger: "\u2021",
  6642. bull: "\u2022",
  6643. hellip: "\u2026",
  6644. permil: "\u2030",
  6645. prime: "\u2032",
  6646. Prime: "\u2033",
  6647. lsaquo: "\u2039",
  6648. rsaquo: "\u203A",
  6649. oline: "\u203E",
  6650. frasl: "\u2044",
  6651. euro: "\u20AC",
  6652. image: "\u2111",
  6653. weierp: "\u2118",
  6654. real: "\u211C",
  6655. trade: "\u2122",
  6656. alefsym: "\u2135",
  6657. larr: "\u2190",
  6658. uarr: "\u2191",
  6659. rarr: "\u2192",
  6660. darr: "\u2193",
  6661. harr: "\u2194",
  6662. crarr: "\u21B5",
  6663. lArr: "\u21D0",
  6664. uArr: "\u21D1",
  6665. rArr: "\u21D2",
  6666. dArr: "\u21D3",
  6667. hArr: "\u21D4",
  6668. forall: "\u2200",
  6669. part: "\u2202",
  6670. exist: "\u2203",
  6671. empty: "\u2205",
  6672. nabla: "\u2207",
  6673. isin: "\u2208",
  6674. notin: "\u2209",
  6675. ni: "\u220B",
  6676. prod: "\u220F",
  6677. sum: "\u2211",
  6678. minus: "\u2212",
  6679. lowast: "\u2217",
  6680. radic: "\u221A",
  6681. prop: "\u221D",
  6682. infin: "\u221E",
  6683. ang: "\u2220",
  6684. and: "\u2227",
  6685. or: "\u2228",
  6686. cap: "\u2229",
  6687. cup: "\u222A",
  6688. int: "\u222B",
  6689. there4: "\u2234",
  6690. sim: "\u223C",
  6691. cong: "\u2245",
  6692. asymp: "\u2248",
  6693. ne: "\u2260",
  6694. equiv: "\u2261",
  6695. le: "\u2264",
  6696. ge: "\u2265",
  6697. sub: "\u2282",
  6698. sup: "\u2283",
  6699. nsub: "\u2284",
  6700. sube: "\u2286",
  6701. supe: "\u2287",
  6702. oplus: "\u2295",
  6703. otimes: "\u2297",
  6704. perp: "\u22A5",
  6705. sdot: "\u22C5",
  6706. lceil: "\u2308",
  6707. rceil: "\u2309",
  6708. lfloor: "\u230A",
  6709. rfloor: "\u230B",
  6710. lang: "\u2329",
  6711. rang: "\u232A",
  6712. loz: "\u25CA",
  6713. spades: "\u2660",
  6714. clubs: "\u2663",
  6715. hearts: "\u2665",
  6716. diams: "\u2666"
  6717. };
  6718. const HEX_NUMBER = /^[\da-fA-F]+$/;
  6719. const DECIMAL_NUMBER = /^\d+$/;
  6720. const JsxErrors = makeErrorTemplates({
  6721. AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression.",
  6722. MissingClosingTagElement: "Expected corresponding JSX closing tag for <%0>.",
  6723. MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>.",
  6724. UnexpectedSequenceExpression: "Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?",
  6725. UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text.",
  6726. UnterminatedJsxContent: "Unterminated JSX contents.",
  6727. UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"
  6728. }, ErrorCodes.SyntaxError, "jsx");
  6729. types.j_oTag = new TokContext("<tag");
  6730. types.j_cTag = new TokContext("</tag");
  6731. types.j_expr = new TokContext("<tag>...</tag>", true);
  6732. function isFragment(object) {
  6733. return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false;
  6734. }
  6735. function getQualifiedJSXName(object) {
  6736. if (object.type === "JSXIdentifier") {
  6737. return object.name;
  6738. }
  6739. if (object.type === "JSXNamespacedName") {
  6740. return object.namespace.name + ":" + object.name.name;
  6741. }
  6742. if (object.type === "JSXMemberExpression") {
  6743. return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property);
  6744. }
  6745. throw new Error("Node had unexpected type: " + object.type);
  6746. }
  6747. var jsx = (superClass => class extends superClass {
  6748. jsxReadToken() {
  6749. let out = "";
  6750. let chunkStart = this.state.pos;
  6751. for (;;) {
  6752. if (this.state.pos >= this.length) {
  6753. throw this.raise(this.state.start, JsxErrors.UnterminatedJsxContent);
  6754. }
  6755. const ch = this.input.charCodeAt(this.state.pos);
  6756. switch (ch) {
  6757. case 60:
  6758. case 123:
  6759. if (this.state.pos === this.state.start) {
  6760. if (ch === 60 && this.state.canStartJSXElement) {
  6761. ++this.state.pos;
  6762. return this.finishToken(132);
  6763. }
  6764. return super.getTokenFromCode(ch);
  6765. }
  6766. out += this.input.slice(chunkStart, this.state.pos);
  6767. return this.finishToken(131, out);
  6768. case 38:
  6769. out += this.input.slice(chunkStart, this.state.pos);
  6770. out += this.jsxReadEntity();
  6771. chunkStart = this.state.pos;
  6772. break;
  6773. case 62:
  6774. case 125:
  6775. default:
  6776. if (isNewLine(ch)) {
  6777. out += this.input.slice(chunkStart, this.state.pos);
  6778. out += this.jsxReadNewLine(true);
  6779. chunkStart = this.state.pos;
  6780. } else {
  6781. ++this.state.pos;
  6782. }
  6783. }
  6784. }
  6785. }
  6786. jsxReadNewLine(normalizeCRLF) {
  6787. const ch = this.input.charCodeAt(this.state.pos);
  6788. let out;
  6789. ++this.state.pos;
  6790. if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) {
  6791. ++this.state.pos;
  6792. out = normalizeCRLF ? "\n" : "\r\n";
  6793. } else {
  6794. out = String.fromCharCode(ch);
  6795. }
  6796. ++this.state.curLine;
  6797. this.state.lineStart = this.state.pos;
  6798. return out;
  6799. }
  6800. jsxReadString(quote) {
  6801. let out = "";
  6802. let chunkStart = ++this.state.pos;
  6803. for (;;) {
  6804. if (this.state.pos >= this.length) {
  6805. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  6806. }
  6807. const ch = this.input.charCodeAt(this.state.pos);
  6808. if (ch === quote) break;
  6809. if (ch === 38) {
  6810. out += this.input.slice(chunkStart, this.state.pos);
  6811. out += this.jsxReadEntity();
  6812. chunkStart = this.state.pos;
  6813. } else if (isNewLine(ch)) {
  6814. out += this.input.slice(chunkStart, this.state.pos);
  6815. out += this.jsxReadNewLine(false);
  6816. chunkStart = this.state.pos;
  6817. } else {
  6818. ++this.state.pos;
  6819. }
  6820. }
  6821. out += this.input.slice(chunkStart, this.state.pos++);
  6822. return this.finishToken(123, out);
  6823. }
  6824. jsxReadEntity() {
  6825. let str = "";
  6826. let count = 0;
  6827. let entity;
  6828. let ch = this.input[this.state.pos];
  6829. const startPos = ++this.state.pos;
  6830. while (this.state.pos < this.length && count++ < 10) {
  6831. ch = this.input[this.state.pos++];
  6832. if (ch === ";") {
  6833. if (str[0] === "#") {
  6834. if (str[1] === "x") {
  6835. str = str.substr(2);
  6836. if (HEX_NUMBER.test(str)) {
  6837. entity = String.fromCodePoint(parseInt(str, 16));
  6838. }
  6839. } else {
  6840. str = str.substr(1);
  6841. if (DECIMAL_NUMBER.test(str)) {
  6842. entity = String.fromCodePoint(parseInt(str, 10));
  6843. }
  6844. }
  6845. } else {
  6846. entity = entities[str];
  6847. }
  6848. break;
  6849. }
  6850. str += ch;
  6851. }
  6852. if (!entity) {
  6853. this.state.pos = startPos;
  6854. return "&";
  6855. }
  6856. return entity;
  6857. }
  6858. jsxReadWord() {
  6859. let ch;
  6860. const start = this.state.pos;
  6861. do {
  6862. ch = this.input.charCodeAt(++this.state.pos);
  6863. } while (isIdentifierChar(ch) || ch === 45);
  6864. return this.finishToken(130, this.input.slice(start, this.state.pos));
  6865. }
  6866. jsxParseIdentifier() {
  6867. const node = this.startNode();
  6868. if (this.match(130)) {
  6869. node.name = this.state.value;
  6870. } else if (tokenIsKeyword(this.state.type)) {
  6871. node.name = tokenLabelName(this.state.type);
  6872. } else {
  6873. this.unexpected();
  6874. }
  6875. this.next();
  6876. return this.finishNode(node, "JSXIdentifier");
  6877. }
  6878. jsxParseNamespacedName() {
  6879. const startPos = this.state.start;
  6880. const startLoc = this.state.startLoc;
  6881. const name = this.jsxParseIdentifier();
  6882. if (!this.eat(14)) return name;
  6883. const node = this.startNodeAt(startPos, startLoc);
  6884. node.namespace = name;
  6885. node.name = this.jsxParseIdentifier();
  6886. return this.finishNode(node, "JSXNamespacedName");
  6887. }
  6888. jsxParseElementName() {
  6889. const startPos = this.state.start;
  6890. const startLoc = this.state.startLoc;
  6891. let node = this.jsxParseNamespacedName();
  6892. if (node.type === "JSXNamespacedName") {
  6893. return node;
  6894. }
  6895. while (this.eat(16)) {
  6896. const newNode = this.startNodeAt(startPos, startLoc);
  6897. newNode.object = node;
  6898. newNode.property = this.jsxParseIdentifier();
  6899. node = this.finishNode(newNode, "JSXMemberExpression");
  6900. }
  6901. return node;
  6902. }
  6903. jsxParseAttributeValue() {
  6904. let node;
  6905. switch (this.state.type) {
  6906. case 5:
  6907. node = this.startNode();
  6908. this.next();
  6909. node = this.jsxParseExpressionContainer(node);
  6910. if (node.expression.type === "JSXEmptyExpression") {
  6911. this.raise(node.start, JsxErrors.AttributeIsEmpty);
  6912. }
  6913. return node;
  6914. case 132:
  6915. case 123:
  6916. return this.parseExprAtom();
  6917. default:
  6918. throw this.raise(this.state.start, JsxErrors.UnsupportedJsxValue);
  6919. }
  6920. }
  6921. jsxParseEmptyExpression() {
  6922. const node = this.startNodeAt(this.state.lastTokEnd, this.state.lastTokEndLoc);
  6923. return this.finishNodeAt(node, "JSXEmptyExpression", this.state.start, this.state.startLoc);
  6924. }
  6925. jsxParseSpreadChild(node) {
  6926. this.next();
  6927. node.expression = this.parseExpression();
  6928. this.expect(8);
  6929. return this.finishNode(node, "JSXSpreadChild");
  6930. }
  6931. jsxParseExpressionContainer(node) {
  6932. if (this.match(8)) {
  6933. node.expression = this.jsxParseEmptyExpression();
  6934. } else {
  6935. const expression = this.parseExpression();
  6936. node.expression = expression;
  6937. }
  6938. this.expect(8);
  6939. return this.finishNode(node, "JSXExpressionContainer");
  6940. }
  6941. jsxParseAttribute() {
  6942. const node = this.startNode();
  6943. if (this.eat(5)) {
  6944. this.expect(21);
  6945. node.argument = this.parseMaybeAssignAllowIn();
  6946. this.expect(8);
  6947. return this.finishNode(node, "JSXSpreadAttribute");
  6948. }
  6949. node.name = this.jsxParseNamespacedName();
  6950. node.value = this.eat(27) ? this.jsxParseAttributeValue() : null;
  6951. return this.finishNode(node, "JSXAttribute");
  6952. }
  6953. jsxParseOpeningElementAt(startPos, startLoc) {
  6954. const node = this.startNodeAt(startPos, startLoc);
  6955. if (this.match(133)) {
  6956. this.expect(133);
  6957. return this.finishNode(node, "JSXOpeningFragment");
  6958. }
  6959. node.name = this.jsxParseElementName();
  6960. return this.jsxParseOpeningElementAfterName(node);
  6961. }
  6962. jsxParseOpeningElementAfterName(node) {
  6963. const attributes = [];
  6964. while (!this.match(50) && !this.match(133)) {
  6965. attributes.push(this.jsxParseAttribute());
  6966. }
  6967. node.attributes = attributes;
  6968. node.selfClosing = this.eat(50);
  6969. this.expect(133);
  6970. return this.finishNode(node, "JSXOpeningElement");
  6971. }
  6972. jsxParseClosingElementAt(startPos, startLoc) {
  6973. const node = this.startNodeAt(startPos, startLoc);
  6974. if (this.match(133)) {
  6975. this.expect(133);
  6976. return this.finishNode(node, "JSXClosingFragment");
  6977. }
  6978. node.name = this.jsxParseElementName();
  6979. this.expect(133);
  6980. return this.finishNode(node, "JSXClosingElement");
  6981. }
  6982. jsxParseElementAt(startPos, startLoc) {
  6983. const node = this.startNodeAt(startPos, startLoc);
  6984. const children = [];
  6985. const openingElement = this.jsxParseOpeningElementAt(startPos, startLoc);
  6986. let closingElement = null;
  6987. if (!openingElement.selfClosing) {
  6988. contents: for (;;) {
  6989. switch (this.state.type) {
  6990. case 132:
  6991. startPos = this.state.start;
  6992. startLoc = this.state.startLoc;
  6993. this.next();
  6994. if (this.eat(50)) {
  6995. closingElement = this.jsxParseClosingElementAt(startPos, startLoc);
  6996. break contents;
  6997. }
  6998. children.push(this.jsxParseElementAt(startPos, startLoc));
  6999. break;
  7000. case 131:
  7001. children.push(this.parseExprAtom());
  7002. break;
  7003. case 5:
  7004. {
  7005. const node = this.startNode();
  7006. this.next();
  7007. if (this.match(21)) {
  7008. children.push(this.jsxParseSpreadChild(node));
  7009. } else {
  7010. children.push(this.jsxParseExpressionContainer(node));
  7011. }
  7012. break;
  7013. }
  7014. default:
  7015. throw this.unexpected();
  7016. }
  7017. }
  7018. if (isFragment(openingElement) && !isFragment(closingElement)) {
  7019. this.raise(closingElement.start, JsxErrors.MissingClosingTagFragment);
  7020. } else if (!isFragment(openingElement) && isFragment(closingElement)) {
  7021. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  7022. } else if (!isFragment(openingElement) && !isFragment(closingElement)) {
  7023. if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
  7024. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  7025. }
  7026. }
  7027. }
  7028. if (isFragment(openingElement)) {
  7029. node.openingFragment = openingElement;
  7030. node.closingFragment = closingElement;
  7031. } else {
  7032. node.openingElement = openingElement;
  7033. node.closingElement = closingElement;
  7034. }
  7035. node.children = children;
  7036. if (this.match(43)) {
  7037. throw this.raise(this.state.start, JsxErrors.UnwrappedAdjacentJSXElements);
  7038. }
  7039. return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement");
  7040. }
  7041. jsxParseElement() {
  7042. const startPos = this.state.start;
  7043. const startLoc = this.state.startLoc;
  7044. this.next();
  7045. return this.jsxParseElementAt(startPos, startLoc);
  7046. }
  7047. parseExprAtom(refExpressionErrors) {
  7048. if (this.match(131)) {
  7049. return this.parseLiteral(this.state.value, "JSXText");
  7050. } else if (this.match(132)) {
  7051. return this.jsxParseElement();
  7052. } else if (this.match(43) && this.input.charCodeAt(this.state.pos) !== 33) {
  7053. this.replaceToken(132);
  7054. return this.jsxParseElement();
  7055. } else {
  7056. return super.parseExprAtom(refExpressionErrors);
  7057. }
  7058. }
  7059. getTokenFromCode(code) {
  7060. const context = this.curContext();
  7061. if (context === types.j_expr) {
  7062. return this.jsxReadToken();
  7063. }
  7064. if (context === types.j_oTag || context === types.j_cTag) {
  7065. if (isIdentifierStart(code)) {
  7066. return this.jsxReadWord();
  7067. }
  7068. if (code === 62) {
  7069. ++this.state.pos;
  7070. return this.finishToken(133);
  7071. }
  7072. if ((code === 34 || code === 39) && context === types.j_oTag) {
  7073. return this.jsxReadString(code);
  7074. }
  7075. }
  7076. if (code === 60 && this.state.canStartJSXElement && this.input.charCodeAt(this.state.pos + 1) !== 33) {
  7077. ++this.state.pos;
  7078. return this.finishToken(132);
  7079. }
  7080. return super.getTokenFromCode(code);
  7081. }
  7082. updateContext(prevType) {
  7083. super.updateContext(prevType);
  7084. const {
  7085. context,
  7086. type
  7087. } = this.state;
  7088. if (type === 50 && prevType === 132) {
  7089. context.splice(-2, 2, types.j_cTag);
  7090. this.state.canStartJSXElement = false;
  7091. } else if (type === 132) {
  7092. context.push(types.j_expr, types.j_oTag);
  7093. } else if (type === 133) {
  7094. const out = context.pop();
  7095. if (out === types.j_oTag && prevType === 50 || out === types.j_cTag) {
  7096. context.pop();
  7097. this.state.canStartJSXElement = context[context.length - 1] === types.j_expr;
  7098. } else {
  7099. this.state.canStartJSXElement = true;
  7100. }
  7101. } else {
  7102. this.state.canStartJSXElement = tokenComesBeforeExpression(type);
  7103. }
  7104. }
  7105. });
  7106. class TypeScriptScope extends Scope {
  7107. constructor(...args) {
  7108. super(...args);
  7109. this.types = new Set();
  7110. this.enums = new Set();
  7111. this.constEnums = new Set();
  7112. this.classes = new Set();
  7113. this.exportOnlyBindings = new Set();
  7114. }
  7115. }
  7116. class TypeScriptScopeHandler extends ScopeHandler {
  7117. createScope(flags) {
  7118. return new TypeScriptScope(flags);
  7119. }
  7120. declareName(name, bindingType, pos) {
  7121. const scope = this.currentScope();
  7122. if (bindingType & BIND_FLAGS_TS_EXPORT_ONLY) {
  7123. this.maybeExportDefined(scope, name);
  7124. scope.exportOnlyBindings.add(name);
  7125. return;
  7126. }
  7127. super.declareName(...arguments);
  7128. if (bindingType & BIND_KIND_TYPE) {
  7129. if (!(bindingType & BIND_KIND_VALUE)) {
  7130. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  7131. this.maybeExportDefined(scope, name);
  7132. }
  7133. scope.types.add(name);
  7134. }
  7135. if (bindingType & BIND_FLAGS_TS_ENUM) scope.enums.add(name);
  7136. if (bindingType & BIND_FLAGS_TS_CONST_ENUM) scope.constEnums.add(name);
  7137. if (bindingType & BIND_FLAGS_CLASS) scope.classes.add(name);
  7138. }
  7139. isRedeclaredInScope(scope, name, bindingType) {
  7140. if (scope.enums.has(name)) {
  7141. if (bindingType & BIND_FLAGS_TS_ENUM) {
  7142. const isConst = !!(bindingType & BIND_FLAGS_TS_CONST_ENUM);
  7143. const wasConst = scope.constEnums.has(name);
  7144. return isConst !== wasConst;
  7145. }
  7146. return true;
  7147. }
  7148. if (bindingType & BIND_FLAGS_CLASS && scope.classes.has(name)) {
  7149. if (scope.lexical.has(name)) {
  7150. return !!(bindingType & BIND_KIND_VALUE);
  7151. } else {
  7152. return false;
  7153. }
  7154. }
  7155. if (bindingType & BIND_KIND_TYPE && scope.types.has(name)) {
  7156. return true;
  7157. }
  7158. return super.isRedeclaredInScope(...arguments);
  7159. }
  7160. checkLocalExport(id) {
  7161. const topLevelScope = this.scopeStack[0];
  7162. const {
  7163. name
  7164. } = id;
  7165. if (!topLevelScope.types.has(name) && !topLevelScope.exportOnlyBindings.has(name)) {
  7166. super.checkLocalExport(id);
  7167. }
  7168. }
  7169. }
  7170. function nonNull(x) {
  7171. if (x == null) {
  7172. throw new Error(`Unexpected ${x} value.`);
  7173. }
  7174. return x;
  7175. }
  7176. function assert(x) {
  7177. if (!x) {
  7178. throw new Error("Assert fail");
  7179. }
  7180. }
  7181. const TSErrors = makeErrorTemplates({
  7182. AbstractMethodHasImplementation: "Method '%0' cannot have an implementation because it is marked abstract.",
  7183. AbstractPropertyHasInitializer: "Property '%0' cannot have an initializer because it is marked abstract.",
  7184. AccesorCannotDeclareThisParameter: "'get' and 'set' accessors cannot declare 'this' parameters.",
  7185. AccesorCannotHaveTypeParameters: "An accessor cannot have type parameters.",
  7186. ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier.",
  7187. ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier.",
  7188. ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.",
  7189. DeclareAccessor: "'declare' is not allowed in %0ters.",
  7190. DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.",
  7191. DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.",
  7192. DuplicateAccessibilityModifier: "Accessibility modifier already seen.",
  7193. DuplicateModifier: "Duplicate modifier: '%0'.",
  7194. EmptyHeritageClauseType: "'%0' list cannot be empty.",
  7195. EmptyTypeArguments: "Type argument list cannot be empty.",
  7196. EmptyTypeParameters: "Type parameter list cannot be empty.",
  7197. ExpectedAmbientAfterExportDeclare: "'export declare' must be followed by an ambient declaration.",
  7198. ImportAliasHasImportType: "An import alias can not use 'import type'.",
  7199. IncompatibleModifiers: "'%0' modifier cannot be used with '%1' modifier.",
  7200. IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier.",
  7201. IndexSignatureHasAccessibility: "Index signatures cannot have an accessibility modifier ('%0').",
  7202. IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier.",
  7203. IndexSignatureHasOverride: "'override' modifier cannot appear on an index signature.",
  7204. IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier.",
  7205. InvalidModifierOnTypeMember: "'%0' modifier cannot appear on a type member.",
  7206. InvalidModifiersOrder: "'%0' modifier must precede '%1' modifier.",
  7207. InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.",
  7208. MissingInterfaceName: "'interface' declarations must be followed by an identifier.",
  7209. MixedLabeledAndUnlabeledElements: "Tuple members must all have names or all not have names.",
  7210. NonAbstractClassHasAbstractMethod: "Abstract methods can only appear within an abstract class.",
  7211. NonClassMethodPropertyHasAbstractModifer: "'abstract' modifier can only appear on a class, method, or property declaration.",
  7212. OptionalTypeBeforeRequired: "A required element cannot follow an optional element.",
  7213. OverrideNotInSubClass: "This member cannot have an 'override' modifier because its containing class does not extend another class.",
  7214. PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.",
  7215. PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.",
  7216. PrivateElementHasAccessibility: "Private elements cannot have an accessibility modifier ('%0').",
  7217. ReadonlyForMethodSignature: "'readonly' modifier can only appear on a property declaration or index signature.",
  7218. ReservedArrowTypeParam: "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma, as in `<T,>() => ...`.",
  7219. ReservedTypeAssertion: "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.",
  7220. SetAccesorCannotHaveOptionalParameter: "A 'set' accessor cannot have an optional parameter.",
  7221. SetAccesorCannotHaveRestParameter: "A 'set' accessor cannot have rest parameter.",
  7222. SetAccesorCannotHaveReturnType: "A 'set' accessor cannot have a return type annotation.",
  7223. StaticBlockCannotHaveModifier: "Static class blocks cannot have any modifier.",
  7224. TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",
  7225. TypeImportCannotSpecifyDefaultAndNamed: "A type-only import can specify a default import or named bindings, but not both.",
  7226. TypeModifierIsUsedInTypeExports: "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.",
  7227. TypeModifierIsUsedInTypeImports: "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.",
  7228. UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.",
  7229. UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.",
  7230. UnexpectedTypeAnnotation: "Did not expect a type annotation here.",
  7231. UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.",
  7232. UnsupportedImportTypeArgument: "Argument in a type import must be a string literal.",
  7233. UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.",
  7234. UnsupportedSignatureParameterKind: "Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got %0."
  7235. }, ErrorCodes.SyntaxError, "typescript");
  7236. function keywordTypeFromName(value) {
  7237. switch (value) {
  7238. case "any":
  7239. return "TSAnyKeyword";
  7240. case "boolean":
  7241. return "TSBooleanKeyword";
  7242. case "bigint":
  7243. return "TSBigIntKeyword";
  7244. case "never":
  7245. return "TSNeverKeyword";
  7246. case "number":
  7247. return "TSNumberKeyword";
  7248. case "object":
  7249. return "TSObjectKeyword";
  7250. case "string":
  7251. return "TSStringKeyword";
  7252. case "symbol":
  7253. return "TSSymbolKeyword";
  7254. case "undefined":
  7255. return "TSUndefinedKeyword";
  7256. case "unknown":
  7257. return "TSUnknownKeyword";
  7258. default:
  7259. return undefined;
  7260. }
  7261. }
  7262. function tsIsAccessModifier(modifier) {
  7263. return modifier === "private" || modifier === "public" || modifier === "protected";
  7264. }
  7265. var typescript = (superClass => class extends superClass {
  7266. getScopeHandler() {
  7267. return TypeScriptScopeHandler;
  7268. }
  7269. tsIsIdentifier() {
  7270. return tokenIsIdentifier(this.state.type);
  7271. }
  7272. tsTokenCanFollowModifier() {
  7273. return (this.match(0) || this.match(5) || this.match(49) || this.match(21) || this.match(128) || this.isLiteralPropertyName()) && !this.hasPrecedingLineBreak();
  7274. }
  7275. tsNextTokenCanFollowModifier() {
  7276. this.next();
  7277. return this.tsTokenCanFollowModifier();
  7278. }
  7279. tsParseModifier(allowedModifiers, stopOnStartOfClassStaticBlock) {
  7280. if (!tokenIsIdentifier(this.state.type)) {
  7281. return undefined;
  7282. }
  7283. const modifier = this.state.value;
  7284. if (allowedModifiers.indexOf(modifier) !== -1) {
  7285. if (stopOnStartOfClassStaticBlock && this.tsIsStartOfStaticBlocks()) {
  7286. return undefined;
  7287. }
  7288. if (this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {
  7289. return modifier;
  7290. }
  7291. }
  7292. return undefined;
  7293. }
  7294. tsParseModifiers(modified, allowedModifiers, disallowedModifiers, errorTemplate, stopOnStartOfClassStaticBlock) {
  7295. const enforceOrder = (pos, modifier, before, after) => {
  7296. if (modifier === before && modified[after]) {
  7297. this.raise(pos, TSErrors.InvalidModifiersOrder, before, after);
  7298. }
  7299. };
  7300. const incompatible = (pos, modifier, mod1, mod2) => {
  7301. if (modified[mod1] && modifier === mod2 || modified[mod2] && modifier === mod1) {
  7302. this.raise(pos, TSErrors.IncompatibleModifiers, mod1, mod2);
  7303. }
  7304. };
  7305. for (;;) {
  7306. const startPos = this.state.start;
  7307. const modifier = this.tsParseModifier(allowedModifiers.concat(disallowedModifiers != null ? disallowedModifiers : []), stopOnStartOfClassStaticBlock);
  7308. if (!modifier) break;
  7309. if (tsIsAccessModifier(modifier)) {
  7310. if (modified.accessibility) {
  7311. this.raise(startPos, TSErrors.DuplicateAccessibilityModifier);
  7312. } else {
  7313. enforceOrder(startPos, modifier, modifier, "override");
  7314. enforceOrder(startPos, modifier, modifier, "static");
  7315. enforceOrder(startPos, modifier, modifier, "readonly");
  7316. modified.accessibility = modifier;
  7317. }
  7318. } else {
  7319. if (Object.hasOwnProperty.call(modified, modifier)) {
  7320. this.raise(startPos, TSErrors.DuplicateModifier, modifier);
  7321. } else {
  7322. enforceOrder(startPos, modifier, "static", "readonly");
  7323. enforceOrder(startPos, modifier, "static", "override");
  7324. enforceOrder(startPos, modifier, "override", "readonly");
  7325. enforceOrder(startPos, modifier, "abstract", "override");
  7326. incompatible(startPos, modifier, "declare", "override");
  7327. incompatible(startPos, modifier, "static", "abstract");
  7328. }
  7329. modified[modifier] = true;
  7330. }
  7331. if (disallowedModifiers != null && disallowedModifiers.includes(modifier)) {
  7332. this.raise(startPos, errorTemplate, modifier);
  7333. }
  7334. }
  7335. }
  7336. tsIsListTerminator(kind) {
  7337. switch (kind) {
  7338. case "EnumMembers":
  7339. case "TypeMembers":
  7340. return this.match(8);
  7341. case "HeritageClauseElement":
  7342. return this.match(5);
  7343. case "TupleElementTypes":
  7344. return this.match(3);
  7345. case "TypeParametersOrArguments":
  7346. return this.match(44);
  7347. }
  7348. throw new Error("Unreachable");
  7349. }
  7350. tsParseList(kind, parseElement) {
  7351. const result = [];
  7352. while (!this.tsIsListTerminator(kind)) {
  7353. result.push(parseElement());
  7354. }
  7355. return result;
  7356. }
  7357. tsParseDelimitedList(kind, parseElement, refTrailingCommaPos) {
  7358. return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true, refTrailingCommaPos));
  7359. }
  7360. tsParseDelimitedListWorker(kind, parseElement, expectSuccess, refTrailingCommaPos) {
  7361. const result = [];
  7362. let trailingCommaPos = -1;
  7363. for (;;) {
  7364. if (this.tsIsListTerminator(kind)) {
  7365. break;
  7366. }
  7367. trailingCommaPos = -1;
  7368. const element = parseElement();
  7369. if (element == null) {
  7370. return undefined;
  7371. }
  7372. result.push(element);
  7373. if (this.eat(12)) {
  7374. trailingCommaPos = this.state.lastTokStart;
  7375. continue;
  7376. }
  7377. if (this.tsIsListTerminator(kind)) {
  7378. break;
  7379. }
  7380. if (expectSuccess) {
  7381. this.expect(12);
  7382. }
  7383. return undefined;
  7384. }
  7385. if (refTrailingCommaPos) {
  7386. refTrailingCommaPos.value = trailingCommaPos;
  7387. }
  7388. return result;
  7389. }
  7390. tsParseBracketedList(kind, parseElement, bracket, skipFirstToken, refTrailingCommaPos) {
  7391. if (!skipFirstToken) {
  7392. if (bracket) {
  7393. this.expect(0);
  7394. } else {
  7395. this.expect(43);
  7396. }
  7397. }
  7398. const result = this.tsParseDelimitedList(kind, parseElement, refTrailingCommaPos);
  7399. if (bracket) {
  7400. this.expect(3);
  7401. } else {
  7402. this.expect(44);
  7403. }
  7404. return result;
  7405. }
  7406. tsParseImportType() {
  7407. const node = this.startNode();
  7408. this.expect(77);
  7409. this.expect(10);
  7410. if (!this.match(123)) {
  7411. this.raise(this.state.start, TSErrors.UnsupportedImportTypeArgument);
  7412. }
  7413. node.argument = this.parseExprAtom();
  7414. this.expect(11);
  7415. if (this.eat(16)) {
  7416. node.qualifier = this.tsParseEntityName(true);
  7417. }
  7418. if (this.match(43)) {
  7419. node.typeParameters = this.tsParseTypeArguments();
  7420. }
  7421. return this.finishNode(node, "TSImportType");
  7422. }
  7423. tsParseEntityName(allowReservedWords) {
  7424. let entity = this.parseIdentifier();
  7425. while (this.eat(16)) {
  7426. const node = this.startNodeAtNode(entity);
  7427. node.left = entity;
  7428. node.right = this.parseIdentifier(allowReservedWords);
  7429. entity = this.finishNode(node, "TSQualifiedName");
  7430. }
  7431. return entity;
  7432. }
  7433. tsParseTypeReference() {
  7434. const node = this.startNode();
  7435. node.typeName = this.tsParseEntityName(false);
  7436. if (!this.hasPrecedingLineBreak() && this.match(43)) {
  7437. node.typeParameters = this.tsParseTypeArguments();
  7438. }
  7439. return this.finishNode(node, "TSTypeReference");
  7440. }
  7441. tsParseThisTypePredicate(lhs) {
  7442. this.next();
  7443. const node = this.startNodeAtNode(lhs);
  7444. node.parameterName = lhs;
  7445. node.typeAnnotation = this.tsParseTypeAnnotation(false);
  7446. node.asserts = false;
  7447. return this.finishNode(node, "TSTypePredicate");
  7448. }
  7449. tsParseThisTypeNode() {
  7450. const node = this.startNode();
  7451. this.next();
  7452. return this.finishNode(node, "TSThisType");
  7453. }
  7454. tsParseTypeQuery() {
  7455. const node = this.startNode();
  7456. this.expect(81);
  7457. if (this.match(77)) {
  7458. node.exprName = this.tsParseImportType();
  7459. } else {
  7460. node.exprName = this.tsParseEntityName(true);
  7461. }
  7462. return this.finishNode(node, "TSTypeQuery");
  7463. }
  7464. tsParseTypeParameter() {
  7465. const node = this.startNode();
  7466. node.name = this.tsParseTypeParameterName();
  7467. node.constraint = this.tsEatThenParseType(75);
  7468. node.default = this.tsEatThenParseType(27);
  7469. return this.finishNode(node, "TSTypeParameter");
  7470. }
  7471. tsTryParseTypeParameters() {
  7472. if (this.match(43)) {
  7473. return this.tsParseTypeParameters();
  7474. }
  7475. }
  7476. tsParseTypeParameters() {
  7477. const node = this.startNode();
  7478. if (this.match(43) || this.match(132)) {
  7479. this.next();
  7480. } else {
  7481. this.unexpected();
  7482. }
  7483. const refTrailingCommaPos = {
  7484. value: -1
  7485. };
  7486. node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this), false, true, refTrailingCommaPos);
  7487. if (node.params.length === 0) {
  7488. this.raise(node.start, TSErrors.EmptyTypeParameters);
  7489. }
  7490. if (refTrailingCommaPos.value !== -1) {
  7491. this.addExtra(node, "trailingComma", refTrailingCommaPos.value);
  7492. }
  7493. return this.finishNode(node, "TSTypeParameterDeclaration");
  7494. }
  7495. tsTryNextParseConstantContext() {
  7496. if (this.lookahead().type === 69) {
  7497. this.next();
  7498. return this.tsParseTypeReference();
  7499. }
  7500. return null;
  7501. }
  7502. tsFillSignature(returnToken, signature) {
  7503. const returnTokenRequired = returnToken === 19;
  7504. signature.typeParameters = this.tsTryParseTypeParameters();
  7505. this.expect(10);
  7506. signature.parameters = this.tsParseBindingListForSignature();
  7507. if (returnTokenRequired) {
  7508. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  7509. } else if (this.match(returnToken)) {
  7510. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  7511. }
  7512. }
  7513. tsParseBindingListForSignature() {
  7514. return this.parseBindingList(11, 41).map(pattern => {
  7515. if (pattern.type !== "Identifier" && pattern.type !== "RestElement" && pattern.type !== "ObjectPattern" && pattern.type !== "ArrayPattern") {
  7516. this.raise(pattern.start, TSErrors.UnsupportedSignatureParameterKind, pattern.type);
  7517. }
  7518. return pattern;
  7519. });
  7520. }
  7521. tsParseTypeMemberSemicolon() {
  7522. if (!this.eat(12) && !this.isLineTerminator()) {
  7523. this.expect(13);
  7524. }
  7525. }
  7526. tsParseSignatureMember(kind, node) {
  7527. this.tsFillSignature(14, node);
  7528. this.tsParseTypeMemberSemicolon();
  7529. return this.finishNode(node, kind);
  7530. }
  7531. tsIsUnambiguouslyIndexSignature() {
  7532. this.next();
  7533. if (tokenIsIdentifier(this.state.type)) {
  7534. this.next();
  7535. return this.match(14);
  7536. }
  7537. return false;
  7538. }
  7539. tsTryParseIndexSignature(node) {
  7540. if (!(this.match(0) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) {
  7541. return undefined;
  7542. }
  7543. this.expect(0);
  7544. const id = this.parseIdentifier();
  7545. id.typeAnnotation = this.tsParseTypeAnnotation();
  7546. this.resetEndLocation(id);
  7547. this.expect(3);
  7548. node.parameters = [id];
  7549. const type = this.tsTryParseTypeAnnotation();
  7550. if (type) node.typeAnnotation = type;
  7551. this.tsParseTypeMemberSemicolon();
  7552. return this.finishNode(node, "TSIndexSignature");
  7553. }
  7554. tsParsePropertyOrMethodSignature(node, readonly) {
  7555. if (this.eat(17)) node.optional = true;
  7556. const nodeAny = node;
  7557. if (this.match(10) || this.match(43)) {
  7558. if (readonly) {
  7559. this.raise(node.start, TSErrors.ReadonlyForMethodSignature);
  7560. }
  7561. const method = nodeAny;
  7562. if (method.kind && this.match(43)) {
  7563. this.raise(this.state.pos, TSErrors.AccesorCannotHaveTypeParameters);
  7564. }
  7565. this.tsFillSignature(14, method);
  7566. this.tsParseTypeMemberSemicolon();
  7567. if (method.kind === "get") {
  7568. if (method.parameters.length > 0) {
  7569. this.raise(this.state.pos, ErrorMessages.BadGetterArity);
  7570. if (this.isThisParam(method.parameters[0])) {
  7571. this.raise(this.state.pos, TSErrors.AccesorCannotDeclareThisParameter);
  7572. }
  7573. }
  7574. } else if (method.kind === "set") {
  7575. if (method.parameters.length !== 1) {
  7576. this.raise(this.state.pos, ErrorMessages.BadSetterArity);
  7577. } else {
  7578. const firstParameter = method.parameters[0];
  7579. if (this.isThisParam(firstParameter)) {
  7580. this.raise(this.state.pos, TSErrors.AccesorCannotDeclareThisParameter);
  7581. }
  7582. if (firstParameter.type === "Identifier" && firstParameter.optional) {
  7583. this.raise(this.state.pos, TSErrors.SetAccesorCannotHaveOptionalParameter);
  7584. }
  7585. if (firstParameter.type === "RestElement") {
  7586. this.raise(this.state.pos, TSErrors.SetAccesorCannotHaveRestParameter);
  7587. }
  7588. }
  7589. if (method.typeAnnotation) {
  7590. this.raise(method.typeAnnotation.start, TSErrors.SetAccesorCannotHaveReturnType);
  7591. }
  7592. } else {
  7593. method.kind = "method";
  7594. }
  7595. return this.finishNode(method, "TSMethodSignature");
  7596. } else {
  7597. const property = nodeAny;
  7598. if (readonly) property.readonly = true;
  7599. const type = this.tsTryParseTypeAnnotation();
  7600. if (type) property.typeAnnotation = type;
  7601. this.tsParseTypeMemberSemicolon();
  7602. return this.finishNode(property, "TSPropertySignature");
  7603. }
  7604. }
  7605. tsParseTypeMember() {
  7606. const node = this.startNode();
  7607. if (this.match(10) || this.match(43)) {
  7608. return this.tsParseSignatureMember("TSCallSignatureDeclaration", node);
  7609. }
  7610. if (this.match(71)) {
  7611. const id = this.startNode();
  7612. this.next();
  7613. if (this.match(10) || this.match(43)) {
  7614. return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node);
  7615. } else {
  7616. node.key = this.createIdentifier(id, "new");
  7617. return this.tsParsePropertyOrMethodSignature(node, false);
  7618. }
  7619. }
  7620. this.tsParseModifiers(node, ["readonly"], ["declare", "abstract", "private", "protected", "public", "static", "override"], TSErrors.InvalidModifierOnTypeMember);
  7621. const idx = this.tsTryParseIndexSignature(node);
  7622. if (idx) {
  7623. return idx;
  7624. }
  7625. this.parsePropertyName(node);
  7626. if (!node.computed && node.key.type === "Identifier" && (node.key.name === "get" || node.key.name === "set") && this.tsTokenCanFollowModifier()) {
  7627. node.kind = node.key.name;
  7628. this.parsePropertyName(node);
  7629. }
  7630. return this.tsParsePropertyOrMethodSignature(node, !!node.readonly);
  7631. }
  7632. tsParseTypeLiteral() {
  7633. const node = this.startNode();
  7634. node.members = this.tsParseObjectTypeMembers();
  7635. return this.finishNode(node, "TSTypeLiteral");
  7636. }
  7637. tsParseObjectTypeMembers() {
  7638. this.expect(5);
  7639. const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this));
  7640. this.expect(8);
  7641. return members;
  7642. }
  7643. tsIsStartOfMappedType() {
  7644. this.next();
  7645. if (this.eat(47)) {
  7646. return this.isContextual(112);
  7647. }
  7648. if (this.isContextual(112)) {
  7649. this.next();
  7650. }
  7651. if (!this.match(0)) {
  7652. return false;
  7653. }
  7654. this.next();
  7655. if (!this.tsIsIdentifier()) {
  7656. return false;
  7657. }
  7658. this.next();
  7659. return this.match(52);
  7660. }
  7661. tsParseMappedTypeParameter() {
  7662. const node = this.startNode();
  7663. node.name = this.tsParseTypeParameterName();
  7664. node.constraint = this.tsExpectThenParseType(52);
  7665. return this.finishNode(node, "TSTypeParameter");
  7666. }
  7667. tsParseMappedType() {
  7668. const node = this.startNode();
  7669. this.expect(5);
  7670. if (this.match(47)) {
  7671. node.readonly = this.state.value;
  7672. this.next();
  7673. this.expectContextual(112);
  7674. } else if (this.eatContextual(112)) {
  7675. node.readonly = true;
  7676. }
  7677. this.expect(0);
  7678. node.typeParameter = this.tsParseMappedTypeParameter();
  7679. node.nameType = this.eatContextual(87) ? this.tsParseType() : null;
  7680. this.expect(3);
  7681. if (this.match(47)) {
  7682. node.optional = this.state.value;
  7683. this.next();
  7684. this.expect(17);
  7685. } else if (this.eat(17)) {
  7686. node.optional = true;
  7687. }
  7688. node.typeAnnotation = this.tsTryParseType();
  7689. this.semicolon();
  7690. this.expect(8);
  7691. return this.finishNode(node, "TSMappedType");
  7692. }
  7693. tsParseTupleType() {
  7694. const node = this.startNode();
  7695. node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false);
  7696. let seenOptionalElement = false;
  7697. let labeledElements = null;
  7698. node.elementTypes.forEach(elementNode => {
  7699. var _labeledElements;
  7700. let {
  7701. type
  7702. } = elementNode;
  7703. if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) {
  7704. this.raise(elementNode.start, TSErrors.OptionalTypeBeforeRequired);
  7705. }
  7706. seenOptionalElement = seenOptionalElement || type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType";
  7707. if (type === "TSRestType") {
  7708. elementNode = elementNode.typeAnnotation;
  7709. type = elementNode.type;
  7710. }
  7711. const isLabeled = type === "TSNamedTupleMember";
  7712. labeledElements = (_labeledElements = labeledElements) != null ? _labeledElements : isLabeled;
  7713. if (labeledElements !== isLabeled) {
  7714. this.raise(elementNode.start, TSErrors.MixedLabeledAndUnlabeledElements);
  7715. }
  7716. });
  7717. return this.finishNode(node, "TSTupleType");
  7718. }
  7719. tsParseTupleElementType() {
  7720. const {
  7721. start: startPos,
  7722. startLoc
  7723. } = this.state;
  7724. const rest = this.eat(21);
  7725. let type = this.tsParseType();
  7726. const optional = this.eat(17);
  7727. const labeled = this.eat(14);
  7728. if (labeled) {
  7729. const labeledNode = this.startNodeAtNode(type);
  7730. labeledNode.optional = optional;
  7731. if (type.type === "TSTypeReference" && !type.typeParameters && type.typeName.type === "Identifier") {
  7732. labeledNode.label = type.typeName;
  7733. } else {
  7734. this.raise(type.start, TSErrors.InvalidTupleMemberLabel);
  7735. labeledNode.label = type;
  7736. }
  7737. labeledNode.elementType = this.tsParseType();
  7738. type = this.finishNode(labeledNode, "TSNamedTupleMember");
  7739. } else if (optional) {
  7740. const optionalTypeNode = this.startNodeAtNode(type);
  7741. optionalTypeNode.typeAnnotation = type;
  7742. type = this.finishNode(optionalTypeNode, "TSOptionalType");
  7743. }
  7744. if (rest) {
  7745. const restNode = this.startNodeAt(startPos, startLoc);
  7746. restNode.typeAnnotation = type;
  7747. type = this.finishNode(restNode, "TSRestType");
  7748. }
  7749. return type;
  7750. }
  7751. tsParseParenthesizedType() {
  7752. const node = this.startNode();
  7753. this.expect(10);
  7754. node.typeAnnotation = this.tsParseType();
  7755. this.expect(11);
  7756. return this.finishNode(node, "TSParenthesizedType");
  7757. }
  7758. tsParseFunctionOrConstructorType(type, abstract) {
  7759. const node = this.startNode();
  7760. if (type === "TSConstructorType") {
  7761. node.abstract = !!abstract;
  7762. if (abstract) this.next();
  7763. this.next();
  7764. }
  7765. this.tsFillSignature(19, node);
  7766. return this.finishNode(node, type);
  7767. }
  7768. tsParseLiteralTypeNode() {
  7769. const node = this.startNode();
  7770. node.literal = (() => {
  7771. switch (this.state.type) {
  7772. case 124:
  7773. case 125:
  7774. case 123:
  7775. case 79:
  7776. case 80:
  7777. return this.parseExprAtom();
  7778. default:
  7779. throw this.unexpected();
  7780. }
  7781. })();
  7782. return this.finishNode(node, "TSLiteralType");
  7783. }
  7784. tsParseTemplateLiteralType() {
  7785. const node = this.startNode();
  7786. node.literal = this.parseTemplate(false);
  7787. return this.finishNode(node, "TSLiteralType");
  7788. }
  7789. parseTemplateSubstitution() {
  7790. if (this.state.inType) return this.tsParseType();
  7791. return super.parseTemplateSubstitution();
  7792. }
  7793. tsParseThisTypeOrThisTypePredicate() {
  7794. const thisKeyword = this.tsParseThisTypeNode();
  7795. if (this.isContextual(107) && !this.hasPrecedingLineBreak()) {
  7796. return this.tsParseThisTypePredicate(thisKeyword);
  7797. } else {
  7798. return thisKeyword;
  7799. }
  7800. }
  7801. tsParseNonArrayType() {
  7802. switch (this.state.type) {
  7803. case 123:
  7804. case 124:
  7805. case 125:
  7806. case 79:
  7807. case 80:
  7808. return this.tsParseLiteralTypeNode();
  7809. case 47:
  7810. if (this.state.value === "-") {
  7811. const node = this.startNode();
  7812. const nextToken = this.lookahead();
  7813. if (nextToken.type !== 124 && nextToken.type !== 125) {
  7814. throw this.unexpected();
  7815. }
  7816. node.literal = this.parseMaybeUnary();
  7817. return this.finishNode(node, "TSLiteralType");
  7818. }
  7819. break;
  7820. case 72:
  7821. return this.tsParseThisTypeOrThisTypePredicate();
  7822. case 81:
  7823. return this.tsParseTypeQuery();
  7824. case 77:
  7825. return this.tsParseImportType();
  7826. case 5:
  7827. return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral();
  7828. case 0:
  7829. return this.tsParseTupleType();
  7830. case 10:
  7831. return this.tsParseParenthesizedType();
  7832. case 22:
  7833. return this.tsParseTemplateLiteralType();
  7834. default:
  7835. {
  7836. const {
  7837. type
  7838. } = this.state;
  7839. if (tokenIsIdentifier(type) || type === 82 || type === 78) {
  7840. const nodeType = type === 82 ? "TSVoidKeyword" : type === 78 ? "TSNullKeyword" : keywordTypeFromName(this.state.value);
  7841. if (nodeType !== undefined && this.lookaheadCharCode() !== 46) {
  7842. const node = this.startNode();
  7843. this.next();
  7844. return this.finishNode(node, nodeType);
  7845. }
  7846. return this.tsParseTypeReference();
  7847. }
  7848. }
  7849. }
  7850. throw this.unexpected();
  7851. }
  7852. tsParseArrayTypeOrHigher() {
  7853. let type = this.tsParseNonArrayType();
  7854. while (!this.hasPrecedingLineBreak() && this.eat(0)) {
  7855. if (this.match(3)) {
  7856. const node = this.startNodeAtNode(type);
  7857. node.elementType = type;
  7858. this.expect(3);
  7859. type = this.finishNode(node, "TSArrayType");
  7860. } else {
  7861. const node = this.startNodeAtNode(type);
  7862. node.objectType = type;
  7863. node.indexType = this.tsParseType();
  7864. this.expect(3);
  7865. type = this.finishNode(node, "TSIndexedAccessType");
  7866. }
  7867. }
  7868. return type;
  7869. }
  7870. tsParseTypeOperator() {
  7871. const node = this.startNode();
  7872. const operator = this.state.value;
  7873. this.next();
  7874. node.operator = operator;
  7875. node.typeAnnotation = this.tsParseTypeOperatorOrHigher();
  7876. if (operator === "readonly") {
  7877. this.tsCheckTypeAnnotationForReadOnly(node);
  7878. }
  7879. return this.finishNode(node, "TSTypeOperator");
  7880. }
  7881. tsCheckTypeAnnotationForReadOnly(node) {
  7882. switch (node.typeAnnotation.type) {
  7883. case "TSTupleType":
  7884. case "TSArrayType":
  7885. return;
  7886. default:
  7887. this.raise(node.start, TSErrors.UnexpectedReadonly);
  7888. }
  7889. }
  7890. tsParseInferType() {
  7891. const node = this.startNode();
  7892. this.expectContextual(106);
  7893. const typeParameter = this.startNode();
  7894. typeParameter.name = this.tsParseTypeParameterName();
  7895. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  7896. return this.finishNode(node, "TSInferType");
  7897. }
  7898. tsParseTypeOperatorOrHigher() {
  7899. const isTypeOperator = tokenIsTSTypeOperator(this.state.type) && !this.state.containsEsc;
  7900. return isTypeOperator ? this.tsParseTypeOperator() : this.isContextual(106) ? this.tsParseInferType() : this.tsParseArrayTypeOrHigher();
  7901. }
  7902. tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) {
  7903. const node = this.startNode();
  7904. const hasLeadingOperator = this.eat(operator);
  7905. const types = [];
  7906. do {
  7907. types.push(parseConstituentType());
  7908. } while (this.eat(operator));
  7909. if (types.length === 1 && !hasLeadingOperator) {
  7910. return types[0];
  7911. }
  7912. node.types = types;
  7913. return this.finishNode(node, kind);
  7914. }
  7915. tsParseIntersectionTypeOrHigher() {
  7916. return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), 41);
  7917. }
  7918. tsParseUnionTypeOrHigher() {
  7919. return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), 39);
  7920. }
  7921. tsIsStartOfFunctionType() {
  7922. if (this.match(43)) {
  7923. return true;
  7924. }
  7925. return this.match(10) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this));
  7926. }
  7927. tsSkipParameterStart() {
  7928. if (tokenIsIdentifier(this.state.type) || this.match(72)) {
  7929. this.next();
  7930. return true;
  7931. }
  7932. if (this.match(5)) {
  7933. let braceStackCounter = 1;
  7934. this.next();
  7935. while (braceStackCounter > 0) {
  7936. if (this.match(5)) {
  7937. ++braceStackCounter;
  7938. } else if (this.match(8)) {
  7939. --braceStackCounter;
  7940. }
  7941. this.next();
  7942. }
  7943. return true;
  7944. }
  7945. if (this.match(0)) {
  7946. let braceStackCounter = 1;
  7947. this.next();
  7948. while (braceStackCounter > 0) {
  7949. if (this.match(0)) {
  7950. ++braceStackCounter;
  7951. } else if (this.match(3)) {
  7952. --braceStackCounter;
  7953. }
  7954. this.next();
  7955. }
  7956. return true;
  7957. }
  7958. return false;
  7959. }
  7960. tsIsUnambiguouslyStartOfFunctionType() {
  7961. this.next();
  7962. if (this.match(11) || this.match(21)) {
  7963. return true;
  7964. }
  7965. if (this.tsSkipParameterStart()) {
  7966. if (this.match(14) || this.match(12) || this.match(17) || this.match(27)) {
  7967. return true;
  7968. }
  7969. if (this.match(11)) {
  7970. this.next();
  7971. if (this.match(19)) {
  7972. return true;
  7973. }
  7974. }
  7975. }
  7976. return false;
  7977. }
  7978. tsParseTypeOrTypePredicateAnnotation(returnToken) {
  7979. return this.tsInType(() => {
  7980. const t = this.startNode();
  7981. this.expect(returnToken);
  7982. const node = this.startNode();
  7983. const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));
  7984. if (asserts && this.match(72)) {
  7985. let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate();
  7986. if (thisTypePredicate.type === "TSThisType") {
  7987. node.parameterName = thisTypePredicate;
  7988. node.asserts = true;
  7989. node.typeAnnotation = null;
  7990. thisTypePredicate = this.finishNode(node, "TSTypePredicate");
  7991. } else {
  7992. this.resetStartLocationFromNode(thisTypePredicate, node);
  7993. thisTypePredicate.asserts = true;
  7994. }
  7995. t.typeAnnotation = thisTypePredicate;
  7996. return this.finishNode(t, "TSTypeAnnotation");
  7997. }
  7998. const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));
  7999. if (!typePredicateVariable) {
  8000. if (!asserts) {
  8001. return this.tsParseTypeAnnotation(false, t);
  8002. }
  8003. node.parameterName = this.parseIdentifier();
  8004. node.asserts = asserts;
  8005. node.typeAnnotation = null;
  8006. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  8007. return this.finishNode(t, "TSTypeAnnotation");
  8008. }
  8009. const type = this.tsParseTypeAnnotation(false);
  8010. node.parameterName = typePredicateVariable;
  8011. node.typeAnnotation = type;
  8012. node.asserts = asserts;
  8013. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  8014. return this.finishNode(t, "TSTypeAnnotation");
  8015. });
  8016. }
  8017. tsTryParseTypeOrTypePredicateAnnotation() {
  8018. return this.match(14) ? this.tsParseTypeOrTypePredicateAnnotation(14) : undefined;
  8019. }
  8020. tsTryParseTypeAnnotation() {
  8021. return this.match(14) ? this.tsParseTypeAnnotation() : undefined;
  8022. }
  8023. tsTryParseType() {
  8024. return this.tsEatThenParseType(14);
  8025. }
  8026. tsParseTypePredicatePrefix() {
  8027. const id = this.parseIdentifier();
  8028. if (this.isContextual(107) && !this.hasPrecedingLineBreak()) {
  8029. this.next();
  8030. return id;
  8031. }
  8032. }
  8033. tsParseTypePredicateAsserts() {
  8034. if (this.state.type !== 100) {
  8035. return false;
  8036. }
  8037. const containsEsc = this.state.containsEsc;
  8038. this.next();
  8039. if (!tokenIsIdentifier(this.state.type) && !this.match(72)) {
  8040. return false;
  8041. }
  8042. if (containsEsc) {
  8043. this.raise(this.state.lastTokStart, ErrorMessages.InvalidEscapedReservedWord, "asserts");
  8044. }
  8045. return true;
  8046. }
  8047. tsParseTypeAnnotation(eatColon = true, t = this.startNode()) {
  8048. this.tsInType(() => {
  8049. if (eatColon) this.expect(14);
  8050. t.typeAnnotation = this.tsParseType();
  8051. });
  8052. return this.finishNode(t, "TSTypeAnnotation");
  8053. }
  8054. tsParseType() {
  8055. assert(this.state.inType);
  8056. const type = this.tsParseNonConditionalType();
  8057. if (this.hasPrecedingLineBreak() || !this.eat(75)) {
  8058. return type;
  8059. }
  8060. const node = this.startNodeAtNode(type);
  8061. node.checkType = type;
  8062. node.extendsType = this.tsParseNonConditionalType();
  8063. this.expect(17);
  8064. node.trueType = this.tsParseType();
  8065. this.expect(14);
  8066. node.falseType = this.tsParseType();
  8067. return this.finishNode(node, "TSConditionalType");
  8068. }
  8069. isAbstractConstructorSignature() {
  8070. return this.isContextual(114) && this.lookahead().type === 71;
  8071. }
  8072. tsParseNonConditionalType() {
  8073. if (this.tsIsStartOfFunctionType()) {
  8074. return this.tsParseFunctionOrConstructorType("TSFunctionType");
  8075. }
  8076. if (this.match(71)) {
  8077. return this.tsParseFunctionOrConstructorType("TSConstructorType");
  8078. } else if (this.isAbstractConstructorSignature()) {
  8079. return this.tsParseFunctionOrConstructorType("TSConstructorType", true);
  8080. }
  8081. return this.tsParseUnionTypeOrHigher();
  8082. }
  8083. tsParseTypeAssertion() {
  8084. if (this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) {
  8085. this.raise(this.state.start, TSErrors.ReservedTypeAssertion);
  8086. }
  8087. const node = this.startNode();
  8088. const _const = this.tsTryNextParseConstantContext();
  8089. node.typeAnnotation = _const || this.tsNextThenParseType();
  8090. this.expect(44);
  8091. node.expression = this.parseMaybeUnary();
  8092. return this.finishNode(node, "TSTypeAssertion");
  8093. }
  8094. tsParseHeritageClause(descriptor) {
  8095. const originalStart = this.state.start;
  8096. const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", this.tsParseExpressionWithTypeArguments.bind(this));
  8097. if (!delimitedList.length) {
  8098. this.raise(originalStart, TSErrors.EmptyHeritageClauseType, descriptor);
  8099. }
  8100. return delimitedList;
  8101. }
  8102. tsParseExpressionWithTypeArguments() {
  8103. const node = this.startNode();
  8104. node.expression = this.tsParseEntityName(false);
  8105. if (this.match(43)) {
  8106. node.typeParameters = this.tsParseTypeArguments();
  8107. }
  8108. return this.finishNode(node, "TSExpressionWithTypeArguments");
  8109. }
  8110. tsParseInterfaceDeclaration(node) {
  8111. if (tokenIsIdentifier(this.state.type)) {
  8112. node.id = this.parseIdentifier();
  8113. this.checkLVal(node.id, "typescript interface declaration", BIND_TS_INTERFACE);
  8114. } else {
  8115. node.id = null;
  8116. this.raise(this.state.start, TSErrors.MissingInterfaceName);
  8117. }
  8118. node.typeParameters = this.tsTryParseTypeParameters();
  8119. if (this.eat(75)) {
  8120. node.extends = this.tsParseHeritageClause("extends");
  8121. }
  8122. const body = this.startNode();
  8123. body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this));
  8124. node.body = this.finishNode(body, "TSInterfaceBody");
  8125. return this.finishNode(node, "TSInterfaceDeclaration");
  8126. }
  8127. tsParseTypeAliasDeclaration(node) {
  8128. node.id = this.parseIdentifier();
  8129. this.checkLVal(node.id, "typescript type alias", BIND_TS_TYPE);
  8130. node.typeParameters = this.tsTryParseTypeParameters();
  8131. node.typeAnnotation = this.tsInType(() => {
  8132. this.expect(27);
  8133. if (this.isContextual(105) && this.lookahead().type !== 16) {
  8134. const node = this.startNode();
  8135. this.next();
  8136. return this.finishNode(node, "TSIntrinsicKeyword");
  8137. }
  8138. return this.tsParseType();
  8139. });
  8140. this.semicolon();
  8141. return this.finishNode(node, "TSTypeAliasDeclaration");
  8142. }
  8143. tsInNoContext(cb) {
  8144. const oldContext = this.state.context;
  8145. this.state.context = [oldContext[0]];
  8146. try {
  8147. return cb();
  8148. } finally {
  8149. this.state.context = oldContext;
  8150. }
  8151. }
  8152. tsInType(cb) {
  8153. const oldInType = this.state.inType;
  8154. this.state.inType = true;
  8155. try {
  8156. return cb();
  8157. } finally {
  8158. this.state.inType = oldInType;
  8159. }
  8160. }
  8161. tsEatThenParseType(token) {
  8162. return !this.match(token) ? undefined : this.tsNextThenParseType();
  8163. }
  8164. tsExpectThenParseType(token) {
  8165. return this.tsDoThenParseType(() => this.expect(token));
  8166. }
  8167. tsNextThenParseType() {
  8168. return this.tsDoThenParseType(() => this.next());
  8169. }
  8170. tsDoThenParseType(cb) {
  8171. return this.tsInType(() => {
  8172. cb();
  8173. return this.tsParseType();
  8174. });
  8175. }
  8176. tsParseEnumMember() {
  8177. const node = this.startNode();
  8178. node.id = this.match(123) ? this.parseExprAtom() : this.parseIdentifier(true);
  8179. if (this.eat(27)) {
  8180. node.initializer = this.parseMaybeAssignAllowIn();
  8181. }
  8182. return this.finishNode(node, "TSEnumMember");
  8183. }
  8184. tsParseEnumDeclaration(node, isConst) {
  8185. if (isConst) node.const = true;
  8186. node.id = this.parseIdentifier();
  8187. this.checkLVal(node.id, "typescript enum declaration", isConst ? BIND_TS_CONST_ENUM : BIND_TS_ENUM);
  8188. this.expect(5);
  8189. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  8190. this.expect(8);
  8191. return this.finishNode(node, "TSEnumDeclaration");
  8192. }
  8193. tsParseModuleBlock() {
  8194. const node = this.startNode();
  8195. this.scope.enter(SCOPE_OTHER);
  8196. this.expect(5);
  8197. this.parseBlockOrModuleBlockBody(node.body = [], undefined, true, 8);
  8198. this.scope.exit();
  8199. return this.finishNode(node, "TSModuleBlock");
  8200. }
  8201. tsParseModuleOrNamespaceDeclaration(node, nested = false) {
  8202. node.id = this.parseIdentifier();
  8203. if (!nested) {
  8204. this.checkLVal(node.id, "module or namespace declaration", BIND_TS_NAMESPACE);
  8205. }
  8206. if (this.eat(16)) {
  8207. const inner = this.startNode();
  8208. this.tsParseModuleOrNamespaceDeclaration(inner, true);
  8209. node.body = inner;
  8210. } else {
  8211. this.scope.enter(SCOPE_TS_MODULE);
  8212. this.prodParam.enter(PARAM);
  8213. node.body = this.tsParseModuleBlock();
  8214. this.prodParam.exit();
  8215. this.scope.exit();
  8216. }
  8217. return this.finishNode(node, "TSModuleDeclaration");
  8218. }
  8219. tsParseAmbientExternalModuleDeclaration(node) {
  8220. if (this.isContextual(103)) {
  8221. node.global = true;
  8222. node.id = this.parseIdentifier();
  8223. } else if (this.match(123)) {
  8224. node.id = this.parseExprAtom();
  8225. } else {
  8226. this.unexpected();
  8227. }
  8228. if (this.match(5)) {
  8229. this.scope.enter(SCOPE_TS_MODULE);
  8230. this.prodParam.enter(PARAM);
  8231. node.body = this.tsParseModuleBlock();
  8232. this.prodParam.exit();
  8233. this.scope.exit();
  8234. } else {
  8235. this.semicolon();
  8236. }
  8237. return this.finishNode(node, "TSModuleDeclaration");
  8238. }
  8239. tsParseImportEqualsDeclaration(node, isExport) {
  8240. node.isExport = isExport || false;
  8241. node.id = this.parseIdentifier();
  8242. this.checkLVal(node.id, "import equals declaration", BIND_LEXICAL);
  8243. this.expect(27);
  8244. const moduleReference = this.tsParseModuleReference();
  8245. if (node.importKind === "type" && moduleReference.type !== "TSExternalModuleReference") {
  8246. this.raise(moduleReference.start, TSErrors.ImportAliasHasImportType);
  8247. }
  8248. node.moduleReference = moduleReference;
  8249. this.semicolon();
  8250. return this.finishNode(node, "TSImportEqualsDeclaration");
  8251. }
  8252. tsIsExternalModuleReference() {
  8253. return this.isContextual(110) && this.lookaheadCharCode() === 40;
  8254. }
  8255. tsParseModuleReference() {
  8256. return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false);
  8257. }
  8258. tsParseExternalModuleReference() {
  8259. const node = this.startNode();
  8260. this.expectContextual(110);
  8261. this.expect(10);
  8262. if (!this.match(123)) {
  8263. throw this.unexpected();
  8264. }
  8265. node.expression = this.parseExprAtom();
  8266. this.expect(11);
  8267. return this.finishNode(node, "TSExternalModuleReference");
  8268. }
  8269. tsLookAhead(f) {
  8270. const state = this.state.clone();
  8271. const res = f();
  8272. this.state = state;
  8273. return res;
  8274. }
  8275. tsTryParseAndCatch(f) {
  8276. const result = this.tryParse(abort => f() || abort());
  8277. if (result.aborted || !result.node) return undefined;
  8278. if (result.error) this.state = result.failState;
  8279. return result.node;
  8280. }
  8281. tsTryParse(f) {
  8282. const state = this.state.clone();
  8283. const result = f();
  8284. if (result !== undefined && result !== false) {
  8285. return result;
  8286. } else {
  8287. this.state = state;
  8288. return undefined;
  8289. }
  8290. }
  8291. tsTryParseDeclare(nany) {
  8292. if (this.isLineTerminator()) {
  8293. return;
  8294. }
  8295. let starttype = this.state.type;
  8296. let kind;
  8297. if (this.isContextual(93)) {
  8298. starttype = 68;
  8299. kind = "let";
  8300. }
  8301. return this.tsInAmbientContext(() => {
  8302. switch (starttype) {
  8303. case 62:
  8304. nany.declare = true;
  8305. return this.parseFunctionStatement(nany, false, true);
  8306. case 74:
  8307. nany.declare = true;
  8308. return this.parseClass(nany, true, false);
  8309. case 69:
  8310. if (this.match(69) && this.isLookaheadContextual("enum")) {
  8311. this.expect(69);
  8312. this.expectContextual(116);
  8313. return this.tsParseEnumDeclaration(nany, true);
  8314. }
  8315. case 68:
  8316. kind = kind || this.state.value;
  8317. return this.parseVarStatement(nany, kind);
  8318. case 103:
  8319. return this.tsParseAmbientExternalModuleDeclaration(nany);
  8320. default:
  8321. {
  8322. if (tokenIsIdentifier(starttype)) {
  8323. return this.tsParseDeclaration(nany, this.state.value, true);
  8324. }
  8325. }
  8326. }
  8327. });
  8328. }
  8329. tsTryParseExportDeclaration() {
  8330. return this.tsParseDeclaration(this.startNode(), this.state.value, true);
  8331. }
  8332. tsParseExpressionStatement(node, expr) {
  8333. switch (expr.name) {
  8334. case "declare":
  8335. {
  8336. const declaration = this.tsTryParseDeclare(node);
  8337. if (declaration) {
  8338. declaration.declare = true;
  8339. return declaration;
  8340. }
  8341. break;
  8342. }
  8343. case "global":
  8344. if (this.match(5)) {
  8345. this.scope.enter(SCOPE_TS_MODULE);
  8346. this.prodParam.enter(PARAM);
  8347. const mod = node;
  8348. mod.global = true;
  8349. mod.id = expr;
  8350. mod.body = this.tsParseModuleBlock();
  8351. this.scope.exit();
  8352. this.prodParam.exit();
  8353. return this.finishNode(mod, "TSModuleDeclaration");
  8354. }
  8355. break;
  8356. default:
  8357. return this.tsParseDeclaration(node, expr.name, false);
  8358. }
  8359. }
  8360. tsParseDeclaration(node, value, next) {
  8361. switch (value) {
  8362. case "abstract":
  8363. if (this.tsCheckLineTerminator(next) && (this.match(74) || tokenIsIdentifier(this.state.type))) {
  8364. return this.tsParseAbstractDeclaration(node);
  8365. }
  8366. break;
  8367. case "enum":
  8368. if (next || tokenIsIdentifier(this.state.type)) {
  8369. if (next) this.next();
  8370. return this.tsParseEnumDeclaration(node, false);
  8371. }
  8372. break;
  8373. case "interface":
  8374. if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
  8375. return this.tsParseInterfaceDeclaration(node);
  8376. }
  8377. break;
  8378. case "module":
  8379. if (this.tsCheckLineTerminator(next)) {
  8380. if (this.match(123)) {
  8381. return this.tsParseAmbientExternalModuleDeclaration(node);
  8382. } else if (tokenIsIdentifier(this.state.type)) {
  8383. return this.tsParseModuleOrNamespaceDeclaration(node);
  8384. }
  8385. }
  8386. break;
  8387. case "namespace":
  8388. if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
  8389. return this.tsParseModuleOrNamespaceDeclaration(node);
  8390. }
  8391. break;
  8392. case "type":
  8393. if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
  8394. return this.tsParseTypeAliasDeclaration(node);
  8395. }
  8396. break;
  8397. }
  8398. }
  8399. tsCheckLineTerminator(next) {
  8400. if (next) {
  8401. if (this.hasFollowingLineBreak()) return false;
  8402. this.next();
  8403. return true;
  8404. }
  8405. return !this.isLineTerminator();
  8406. }
  8407. tsTryParseGenericAsyncArrowFunction(startPos, startLoc) {
  8408. if (!this.match(43)) {
  8409. return undefined;
  8410. }
  8411. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8412. this.state.maybeInArrowParameters = true;
  8413. const res = this.tsTryParseAndCatch(() => {
  8414. const node = this.startNodeAt(startPos, startLoc);
  8415. node.typeParameters = this.tsParseTypeParameters();
  8416. super.parseFunctionParams(node);
  8417. node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation();
  8418. this.expect(19);
  8419. return node;
  8420. });
  8421. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8422. if (!res) {
  8423. return undefined;
  8424. }
  8425. return this.parseArrowExpression(res, null, true);
  8426. }
  8427. tsParseTypeArguments() {
  8428. const node = this.startNode();
  8429. node.params = this.tsInType(() => this.tsInNoContext(() => {
  8430. this.expect(43);
  8431. return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this));
  8432. }));
  8433. if (node.params.length === 0) {
  8434. this.raise(node.start, TSErrors.EmptyTypeArguments);
  8435. }
  8436. this.expect(44);
  8437. return this.finishNode(node, "TSTypeParameterInstantiation");
  8438. }
  8439. tsIsDeclarationStart() {
  8440. return tokenIsTSDeclarationStart(this.state.type);
  8441. }
  8442. isExportDefaultSpecifier() {
  8443. if (this.tsIsDeclarationStart()) return false;
  8444. return super.isExportDefaultSpecifier();
  8445. }
  8446. parseAssignableListItem(allowModifiers, decorators) {
  8447. const startPos = this.state.start;
  8448. const startLoc = this.state.startLoc;
  8449. let accessibility;
  8450. let readonly = false;
  8451. let override = false;
  8452. if (allowModifiers !== undefined) {
  8453. const modified = {};
  8454. this.tsParseModifiers(modified, ["public", "private", "protected", "override", "readonly"]);
  8455. accessibility = modified.accessibility;
  8456. override = modified.override;
  8457. readonly = modified.readonly;
  8458. if (allowModifiers === false && (accessibility || readonly || override)) {
  8459. this.raise(startPos, TSErrors.UnexpectedParameterModifier);
  8460. }
  8461. }
  8462. const left = this.parseMaybeDefault();
  8463. this.parseAssignableListItemTypes(left);
  8464. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  8465. if (accessibility || readonly || override) {
  8466. const pp = this.startNodeAt(startPos, startLoc);
  8467. if (decorators.length) {
  8468. pp.decorators = decorators;
  8469. }
  8470. if (accessibility) pp.accessibility = accessibility;
  8471. if (readonly) pp.readonly = readonly;
  8472. if (override) pp.override = override;
  8473. if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") {
  8474. this.raise(pp.start, TSErrors.UnsupportedParameterPropertyKind);
  8475. }
  8476. pp.parameter = elt;
  8477. return this.finishNode(pp, "TSParameterProperty");
  8478. }
  8479. if (decorators.length) {
  8480. left.decorators = decorators;
  8481. }
  8482. return elt;
  8483. }
  8484. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  8485. if (this.match(14)) {
  8486. node.returnType = this.tsParseTypeOrTypePredicateAnnotation(14);
  8487. }
  8488. const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" || type === "ClassPrivateMethod" ? "TSDeclareMethod" : undefined;
  8489. if (bodilessType && !this.match(5) && this.isLineTerminator()) {
  8490. this.finishNode(node, bodilessType);
  8491. return;
  8492. }
  8493. if (bodilessType === "TSDeclareFunction" && this.state.isAmbientContext) {
  8494. this.raise(node.start, TSErrors.DeclareFunctionHasImplementation);
  8495. if (node.declare) {
  8496. super.parseFunctionBodyAndFinish(node, bodilessType, isMethod);
  8497. return;
  8498. }
  8499. }
  8500. super.parseFunctionBodyAndFinish(node, type, isMethod);
  8501. }
  8502. registerFunctionStatementId(node) {
  8503. if (!node.body && node.id) {
  8504. this.checkLVal(node.id, "function name", BIND_TS_AMBIENT);
  8505. } else {
  8506. super.registerFunctionStatementId(...arguments);
  8507. }
  8508. }
  8509. tsCheckForInvalidTypeCasts(items) {
  8510. items.forEach(node => {
  8511. if ((node == null ? void 0 : node.type) === "TSTypeCastExpression") {
  8512. this.raise(node.typeAnnotation.start, TSErrors.UnexpectedTypeAnnotation);
  8513. }
  8514. });
  8515. }
  8516. toReferencedList(exprList, isInParens) {
  8517. this.tsCheckForInvalidTypeCasts(exprList);
  8518. return exprList;
  8519. }
  8520. parseArrayLike(...args) {
  8521. const node = super.parseArrayLike(...args);
  8522. if (node.type === "ArrayExpression") {
  8523. this.tsCheckForInvalidTypeCasts(node.elements);
  8524. }
  8525. return node;
  8526. }
  8527. parseSubscript(base, startPos, startLoc, noCalls, state) {
  8528. if (!this.hasPrecedingLineBreak() && this.match(33)) {
  8529. this.state.canStartJSXElement = false;
  8530. this.next();
  8531. const nonNullExpression = this.startNodeAt(startPos, startLoc);
  8532. nonNullExpression.expression = base;
  8533. return this.finishNode(nonNullExpression, "TSNonNullExpression");
  8534. }
  8535. let isOptionalCall = false;
  8536. if (this.match(18) && this.lookaheadCharCode() === 60) {
  8537. if (noCalls) {
  8538. state.stop = true;
  8539. return base;
  8540. }
  8541. state.optionalChainMember = isOptionalCall = true;
  8542. this.next();
  8543. }
  8544. if (this.match(43)) {
  8545. let missingParenErrorPos;
  8546. const result = this.tsTryParseAndCatch(() => {
  8547. if (!noCalls && this.atPossibleAsyncArrow(base)) {
  8548. const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startPos, startLoc);
  8549. if (asyncArrowFn) {
  8550. return asyncArrowFn;
  8551. }
  8552. }
  8553. const node = this.startNodeAt(startPos, startLoc);
  8554. node.callee = base;
  8555. const typeArguments = this.tsParseTypeArguments();
  8556. if (typeArguments) {
  8557. if (isOptionalCall && !this.match(10)) {
  8558. missingParenErrorPos = this.state.pos;
  8559. this.unexpected();
  8560. }
  8561. if (!noCalls && this.eat(10)) {
  8562. node.arguments = this.parseCallExpressionArguments(11, false);
  8563. this.tsCheckForInvalidTypeCasts(node.arguments);
  8564. node.typeParameters = typeArguments;
  8565. if (state.optionalChainMember) {
  8566. node.optional = isOptionalCall;
  8567. }
  8568. return this.finishCallExpression(node, state.optionalChainMember);
  8569. } else if (this.match(22)) {
  8570. const result = this.parseTaggedTemplateExpression(base, startPos, startLoc, state);
  8571. result.typeParameters = typeArguments;
  8572. return result;
  8573. }
  8574. }
  8575. this.unexpected();
  8576. });
  8577. if (missingParenErrorPos) {
  8578. this.unexpected(missingParenErrorPos, 10);
  8579. }
  8580. if (result) return result;
  8581. }
  8582. return super.parseSubscript(base, startPos, startLoc, noCalls, state);
  8583. }
  8584. parseNewArguments(node) {
  8585. if (this.match(43)) {
  8586. const typeParameters = this.tsTryParseAndCatch(() => {
  8587. const args = this.tsParseTypeArguments();
  8588. if (!this.match(10)) this.unexpected();
  8589. return args;
  8590. });
  8591. if (typeParameters) {
  8592. node.typeParameters = typeParameters;
  8593. }
  8594. }
  8595. super.parseNewArguments(node);
  8596. }
  8597. parseExprOp(left, leftStartPos, leftStartLoc, minPrec) {
  8598. if (tokenOperatorPrecedence(52) > minPrec && !this.hasPrecedingLineBreak() && this.isContextual(87)) {
  8599. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  8600. node.expression = left;
  8601. const _const = this.tsTryNextParseConstantContext();
  8602. if (_const) {
  8603. node.typeAnnotation = _const;
  8604. } else {
  8605. node.typeAnnotation = this.tsNextThenParseType();
  8606. }
  8607. this.finishNode(node, "TSAsExpression");
  8608. this.reScan_lt_gt();
  8609. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec);
  8610. }
  8611. return super.parseExprOp(left, leftStartPos, leftStartLoc, minPrec);
  8612. }
  8613. checkReservedWord(word, startLoc, checkKeywords, isBinding) {}
  8614. checkDuplicateExports() {}
  8615. parseImport(node) {
  8616. node.importKind = "value";
  8617. if (tokenIsIdentifier(this.state.type) || this.match(49) || this.match(5)) {
  8618. let ahead = this.lookahead();
  8619. if (this.isContextual(120) && ahead.type !== 12 && ahead.type !== 91 && ahead.type !== 27) {
  8620. node.importKind = "type";
  8621. this.next();
  8622. ahead = this.lookahead();
  8623. }
  8624. if (tokenIsIdentifier(this.state.type) && ahead.type === 27) {
  8625. return this.tsParseImportEqualsDeclaration(node);
  8626. }
  8627. }
  8628. const importNode = super.parseImport(node);
  8629. if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") {
  8630. this.raise(importNode.start, TSErrors.TypeImportCannotSpecifyDefaultAndNamed);
  8631. }
  8632. return importNode;
  8633. }
  8634. parseExport(node) {
  8635. if (this.match(77)) {
  8636. this.next();
  8637. if (this.isContextual(120) && this.lookaheadCharCode() !== 61) {
  8638. node.importKind = "type";
  8639. this.next();
  8640. } else {
  8641. node.importKind = "value";
  8642. }
  8643. return this.tsParseImportEqualsDeclaration(node, true);
  8644. } else if (this.eat(27)) {
  8645. const assign = node;
  8646. assign.expression = this.parseExpression();
  8647. this.semicolon();
  8648. return this.finishNode(assign, "TSExportAssignment");
  8649. } else if (this.eatContextual(87)) {
  8650. const decl = node;
  8651. this.expectContextual(118);
  8652. decl.id = this.parseIdentifier();
  8653. this.semicolon();
  8654. return this.finishNode(decl, "TSNamespaceExportDeclaration");
  8655. } else {
  8656. if (this.isContextual(120) && this.lookahead().type === 5) {
  8657. this.next();
  8658. node.exportKind = "type";
  8659. } else {
  8660. node.exportKind = "value";
  8661. }
  8662. return super.parseExport(node);
  8663. }
  8664. }
  8665. isAbstractClass() {
  8666. return this.isContextual(114) && this.lookahead().type === 74;
  8667. }
  8668. parseExportDefaultExpression() {
  8669. if (this.isAbstractClass()) {
  8670. const cls = this.startNode();
  8671. this.next();
  8672. cls.abstract = true;
  8673. this.parseClass(cls, true, true);
  8674. return cls;
  8675. }
  8676. if (this.match(119)) {
  8677. const interfaceNode = this.startNode();
  8678. this.next();
  8679. const result = this.tsParseInterfaceDeclaration(interfaceNode);
  8680. if (result) return result;
  8681. }
  8682. return super.parseExportDefaultExpression();
  8683. }
  8684. parseStatementContent(context, topLevel) {
  8685. if (this.state.type === 69) {
  8686. const ahead = this.lookahead();
  8687. if (ahead.type === 116) {
  8688. const node = this.startNode();
  8689. this.next();
  8690. this.expectContextual(116);
  8691. return this.tsParseEnumDeclaration(node, true);
  8692. }
  8693. }
  8694. return super.parseStatementContent(context, topLevel);
  8695. }
  8696. parseAccessModifier() {
  8697. return this.tsParseModifier(["public", "protected", "private"]);
  8698. }
  8699. tsHasSomeModifiers(member, modifiers) {
  8700. return modifiers.some(modifier => {
  8701. if (tsIsAccessModifier(modifier)) {
  8702. return member.accessibility === modifier;
  8703. }
  8704. return !!member[modifier];
  8705. });
  8706. }
  8707. tsIsStartOfStaticBlocks() {
  8708. return this.isContextual(98) && this.lookaheadCharCode() === 123;
  8709. }
  8710. parseClassMember(classBody, member, state) {
  8711. const modifiers = ["declare", "private", "public", "protected", "override", "abstract", "readonly", "static"];
  8712. this.tsParseModifiers(member, modifiers, undefined, undefined, true);
  8713. const callParseClassMemberWithIsStatic = () => {
  8714. if (this.tsIsStartOfStaticBlocks()) {
  8715. this.next();
  8716. this.next();
  8717. if (this.tsHasSomeModifiers(member, modifiers)) {
  8718. this.raise(this.state.pos, TSErrors.StaticBlockCannotHaveModifier);
  8719. }
  8720. this.parseClassStaticBlock(classBody, member);
  8721. } else {
  8722. this.parseClassMemberWithIsStatic(classBody, member, state, !!member.static);
  8723. }
  8724. };
  8725. if (member.declare) {
  8726. this.tsInAmbientContext(callParseClassMemberWithIsStatic);
  8727. } else {
  8728. callParseClassMemberWithIsStatic();
  8729. }
  8730. }
  8731. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  8732. const idx = this.tsTryParseIndexSignature(member);
  8733. if (idx) {
  8734. classBody.body.push(idx);
  8735. if (member.abstract) {
  8736. this.raise(member.start, TSErrors.IndexSignatureHasAbstract);
  8737. }
  8738. if (member.accessibility) {
  8739. this.raise(member.start, TSErrors.IndexSignatureHasAccessibility, member.accessibility);
  8740. }
  8741. if (member.declare) {
  8742. this.raise(member.start, TSErrors.IndexSignatureHasDeclare);
  8743. }
  8744. if (member.override) {
  8745. this.raise(member.start, TSErrors.IndexSignatureHasOverride);
  8746. }
  8747. return;
  8748. }
  8749. if (!this.state.inAbstractClass && member.abstract) {
  8750. this.raise(member.start, TSErrors.NonAbstractClassHasAbstractMethod);
  8751. }
  8752. if (member.override) {
  8753. if (!state.hadSuperClass) {
  8754. this.raise(member.start, TSErrors.OverrideNotInSubClass);
  8755. }
  8756. }
  8757. super.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  8758. }
  8759. parsePostMemberNameModifiers(methodOrProp) {
  8760. const optional = this.eat(17);
  8761. if (optional) methodOrProp.optional = true;
  8762. if (methodOrProp.readonly && this.match(10)) {
  8763. this.raise(methodOrProp.start, TSErrors.ClassMethodHasReadonly);
  8764. }
  8765. if (methodOrProp.declare && this.match(10)) {
  8766. this.raise(methodOrProp.start, TSErrors.ClassMethodHasDeclare);
  8767. }
  8768. }
  8769. parseExpressionStatement(node, expr) {
  8770. const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr) : undefined;
  8771. return decl || super.parseExpressionStatement(node, expr);
  8772. }
  8773. shouldParseExportDeclaration() {
  8774. if (this.tsIsDeclarationStart()) return true;
  8775. return super.shouldParseExportDeclaration();
  8776. }
  8777. parseConditional(expr, startPos, startLoc, refExpressionErrors) {
  8778. if (!this.state.maybeInArrowParameters || !this.match(17)) {
  8779. return super.parseConditional(expr, startPos, startLoc, refExpressionErrors);
  8780. }
  8781. const result = this.tryParse(() => super.parseConditional(expr, startPos, startLoc));
  8782. if (!result.node) {
  8783. if (result.error) {
  8784. super.setOptionalParametersError(refExpressionErrors, result.error);
  8785. }
  8786. return expr;
  8787. }
  8788. if (result.error) this.state = result.failState;
  8789. return result.node;
  8790. }
  8791. parseParenItem(node, startPos, startLoc) {
  8792. node = super.parseParenItem(node, startPos, startLoc);
  8793. if (this.eat(17)) {
  8794. node.optional = true;
  8795. this.resetEndLocation(node);
  8796. }
  8797. if (this.match(14)) {
  8798. const typeCastNode = this.startNodeAt(startPos, startLoc);
  8799. typeCastNode.expression = node;
  8800. typeCastNode.typeAnnotation = this.tsParseTypeAnnotation();
  8801. return this.finishNode(typeCastNode, "TSTypeCastExpression");
  8802. }
  8803. return node;
  8804. }
  8805. parseExportDeclaration(node) {
  8806. const startPos = this.state.start;
  8807. const startLoc = this.state.startLoc;
  8808. const isDeclare = this.eatContextual(115);
  8809. if (isDeclare && (this.isContextual(115) || !this.shouldParseExportDeclaration())) {
  8810. throw this.raise(this.state.start, TSErrors.ExpectedAmbientAfterExportDeclare);
  8811. }
  8812. let declaration;
  8813. if (tokenIsIdentifier(this.state.type)) {
  8814. declaration = this.tsTryParseExportDeclaration();
  8815. }
  8816. if (!declaration) {
  8817. declaration = super.parseExportDeclaration(node);
  8818. }
  8819. if (declaration && (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare)) {
  8820. node.exportKind = "type";
  8821. }
  8822. if (declaration && isDeclare) {
  8823. this.resetStartLocation(declaration, startPos, startLoc);
  8824. declaration.declare = true;
  8825. }
  8826. return declaration;
  8827. }
  8828. parseClassId(node, isStatement, optionalId) {
  8829. if ((!isStatement || optionalId) && this.isContextual(104)) {
  8830. return;
  8831. }
  8832. super.parseClassId(node, isStatement, optionalId, node.declare ? BIND_TS_AMBIENT : BIND_CLASS);
  8833. const typeParameters = this.tsTryParseTypeParameters();
  8834. if (typeParameters) node.typeParameters = typeParameters;
  8835. }
  8836. parseClassPropertyAnnotation(node) {
  8837. if (!node.optional && this.eat(33)) {
  8838. node.definite = true;
  8839. }
  8840. const type = this.tsTryParseTypeAnnotation();
  8841. if (type) node.typeAnnotation = type;
  8842. }
  8843. parseClassProperty(node) {
  8844. this.parseClassPropertyAnnotation(node);
  8845. if (this.state.isAmbientContext && this.match(27)) {
  8846. this.raise(this.state.start, TSErrors.DeclareClassFieldHasInitializer);
  8847. }
  8848. if (node.abstract && this.match(27)) {
  8849. const {
  8850. key
  8851. } = node;
  8852. this.raise(this.state.start, TSErrors.AbstractPropertyHasInitializer, key.type === "Identifier" && !node.computed ? key.name : `[${this.input.slice(key.start, key.end)}]`);
  8853. }
  8854. return super.parseClassProperty(node);
  8855. }
  8856. parseClassPrivateProperty(node) {
  8857. if (node.abstract) {
  8858. this.raise(node.start, TSErrors.PrivateElementHasAbstract);
  8859. }
  8860. if (node.accessibility) {
  8861. this.raise(node.start, TSErrors.PrivateElementHasAccessibility, node.accessibility);
  8862. }
  8863. this.parseClassPropertyAnnotation(node);
  8864. return super.parseClassPrivateProperty(node);
  8865. }
  8866. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  8867. const typeParameters = this.tsTryParseTypeParameters();
  8868. if (typeParameters && isConstructor) {
  8869. this.raise(typeParameters.start, TSErrors.ConstructorHasTypeParameters);
  8870. }
  8871. if (method.declare && (method.kind === "get" || method.kind === "set")) {
  8872. this.raise(method.start, TSErrors.DeclareAccessor, method.kind);
  8873. }
  8874. if (typeParameters) method.typeParameters = typeParameters;
  8875. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  8876. }
  8877. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  8878. const typeParameters = this.tsTryParseTypeParameters();
  8879. if (typeParameters) method.typeParameters = typeParameters;
  8880. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  8881. }
  8882. declareClassPrivateMethodInScope(node, kind) {
  8883. if (node.type === "TSDeclareMethod") return;
  8884. if (node.type === "MethodDefinition" && !node.value.body) return;
  8885. super.declareClassPrivateMethodInScope(node, kind);
  8886. }
  8887. parseClassSuper(node) {
  8888. super.parseClassSuper(node);
  8889. if (node.superClass && this.match(43)) {
  8890. node.superTypeParameters = this.tsParseTypeArguments();
  8891. }
  8892. if (this.eatContextual(104)) {
  8893. node.implements = this.tsParseHeritageClause("implements");
  8894. }
  8895. }
  8896. parseObjPropValue(prop, ...args) {
  8897. const typeParameters = this.tsTryParseTypeParameters();
  8898. if (typeParameters) prop.typeParameters = typeParameters;
  8899. super.parseObjPropValue(prop, ...args);
  8900. }
  8901. parseFunctionParams(node, allowModifiers) {
  8902. const typeParameters = this.tsTryParseTypeParameters();
  8903. if (typeParameters) node.typeParameters = typeParameters;
  8904. super.parseFunctionParams(node, allowModifiers);
  8905. }
  8906. parseVarId(decl, kind) {
  8907. super.parseVarId(decl, kind);
  8908. if (decl.id.type === "Identifier" && this.eat(33)) {
  8909. decl.definite = true;
  8910. }
  8911. const type = this.tsTryParseTypeAnnotation();
  8912. if (type) {
  8913. decl.id.typeAnnotation = type;
  8914. this.resetEndLocation(decl.id);
  8915. }
  8916. }
  8917. parseAsyncArrowFromCallExpression(node, call) {
  8918. if (this.match(14)) {
  8919. node.returnType = this.tsParseTypeAnnotation();
  8920. }
  8921. return super.parseAsyncArrowFromCallExpression(node, call);
  8922. }
  8923. parseMaybeAssign(...args) {
  8924. var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2, _jsx4, _typeCast3;
  8925. let state;
  8926. let jsx;
  8927. let typeCast;
  8928. if (this.hasPlugin("jsx") && (this.match(132) || this.match(43))) {
  8929. state = this.state.clone();
  8930. jsx = this.tryParse(() => super.parseMaybeAssign(...args), state);
  8931. if (!jsx.error) return jsx.node;
  8932. const {
  8933. context
  8934. } = this.state;
  8935. if (context[context.length - 1] === types.j_oTag) {
  8936. context.length -= 2;
  8937. } else if (context[context.length - 1] === types.j_expr) {
  8938. context.length -= 1;
  8939. }
  8940. }
  8941. if (!((_jsx = jsx) != null && _jsx.error) && !this.match(43)) {
  8942. return super.parseMaybeAssign(...args);
  8943. }
  8944. let typeParameters;
  8945. state = state || this.state.clone();
  8946. const arrow = this.tryParse(abort => {
  8947. var _expr$extra, _typeParameters;
  8948. typeParameters = this.tsParseTypeParameters();
  8949. const expr = super.parseMaybeAssign(...args);
  8950. if (expr.type !== "ArrowFunctionExpression" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) {
  8951. abort();
  8952. }
  8953. if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) {
  8954. this.resetStartLocationFromNode(expr, typeParameters);
  8955. }
  8956. expr.typeParameters = typeParameters;
  8957. return expr;
  8958. }, state);
  8959. if (!arrow.error && !arrow.aborted) {
  8960. if (typeParameters) this.reportReservedArrowTypeParam(typeParameters);
  8961. return arrow.node;
  8962. }
  8963. if (!jsx) {
  8964. assert(!this.hasPlugin("jsx"));
  8965. typeCast = this.tryParse(() => super.parseMaybeAssign(...args), state);
  8966. if (!typeCast.error) return typeCast.node;
  8967. }
  8968. if ((_jsx2 = jsx) != null && _jsx2.node) {
  8969. this.state = jsx.failState;
  8970. return jsx.node;
  8971. }
  8972. if (arrow.node) {
  8973. this.state = arrow.failState;
  8974. if (typeParameters) this.reportReservedArrowTypeParam(typeParameters);
  8975. return arrow.node;
  8976. }
  8977. if ((_typeCast = typeCast) != null && _typeCast.node) {
  8978. this.state = typeCast.failState;
  8979. return typeCast.node;
  8980. }
  8981. if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error;
  8982. if (arrow.thrown) throw arrow.error;
  8983. if ((_typeCast2 = typeCast) != null && _typeCast2.thrown) throw typeCast.error;
  8984. throw ((_jsx4 = jsx) == null ? void 0 : _jsx4.error) || arrow.error || ((_typeCast3 = typeCast) == null ? void 0 : _typeCast3.error);
  8985. }
  8986. reportReservedArrowTypeParam(node) {
  8987. var _node$extra;
  8988. if (node.params.length === 1 && !((_node$extra = node.extra) != null && _node$extra.trailingComma) && this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) {
  8989. this.raise(node.start, TSErrors.ReservedArrowTypeParam);
  8990. }
  8991. }
  8992. parseMaybeUnary(refExpressionErrors) {
  8993. if (!this.hasPlugin("jsx") && this.match(43)) {
  8994. return this.tsParseTypeAssertion();
  8995. } else {
  8996. return super.parseMaybeUnary(refExpressionErrors);
  8997. }
  8998. }
  8999. parseArrow(node) {
  9000. if (this.match(14)) {
  9001. const result = this.tryParse(abort => {
  9002. const returnType = this.tsParseTypeOrTypePredicateAnnotation(14);
  9003. if (this.canInsertSemicolon() || !this.match(19)) abort();
  9004. return returnType;
  9005. });
  9006. if (result.aborted) return;
  9007. if (!result.thrown) {
  9008. if (result.error) this.state = result.failState;
  9009. node.returnType = result.node;
  9010. }
  9011. }
  9012. return super.parseArrow(node);
  9013. }
  9014. parseAssignableListItemTypes(param) {
  9015. if (this.eat(17)) {
  9016. if (param.type !== "Identifier" && !this.state.isAmbientContext && !this.state.inType) {
  9017. this.raise(param.start, TSErrors.PatternIsOptional);
  9018. }
  9019. param.optional = true;
  9020. }
  9021. const type = this.tsTryParseTypeAnnotation();
  9022. if (type) param.typeAnnotation = type;
  9023. this.resetEndLocation(param);
  9024. return param;
  9025. }
  9026. isAssignable(node, isBinding) {
  9027. switch (node.type) {
  9028. case "TSTypeCastExpression":
  9029. return this.isAssignable(node.expression, isBinding);
  9030. case "TSParameterProperty":
  9031. return true;
  9032. default:
  9033. return super.isAssignable(node, isBinding);
  9034. }
  9035. }
  9036. toAssignable(node, isLHS = false) {
  9037. switch (node.type) {
  9038. case "TSTypeCastExpression":
  9039. return super.toAssignable(this.typeCastToParameter(node), isLHS);
  9040. case "TSParameterProperty":
  9041. return super.toAssignable(node, isLHS);
  9042. case "ParenthesizedExpression":
  9043. return this.toAssignableParenthesizedExpression(node, isLHS);
  9044. case "TSAsExpression":
  9045. case "TSNonNullExpression":
  9046. case "TSTypeAssertion":
  9047. node.expression = this.toAssignable(node.expression, isLHS);
  9048. return node;
  9049. default:
  9050. return super.toAssignable(node, isLHS);
  9051. }
  9052. }
  9053. toAssignableParenthesizedExpression(node, isLHS) {
  9054. switch (node.expression.type) {
  9055. case "TSAsExpression":
  9056. case "TSNonNullExpression":
  9057. case "TSTypeAssertion":
  9058. case "ParenthesizedExpression":
  9059. node.expression = this.toAssignable(node.expression, isLHS);
  9060. return node;
  9061. default:
  9062. return super.toAssignable(node, isLHS);
  9063. }
  9064. }
  9065. checkLVal(expr, contextDescription, ...args) {
  9066. var _expr$extra2;
  9067. switch (expr.type) {
  9068. case "TSTypeCastExpression":
  9069. return;
  9070. case "TSParameterProperty":
  9071. this.checkLVal(expr.parameter, "parameter property", ...args);
  9072. return;
  9073. case "TSAsExpression":
  9074. case "TSTypeAssertion":
  9075. if (!args[0] && contextDescription !== "parenthesized expression" && !((_expr$extra2 = expr.extra) != null && _expr$extra2.parenthesized)) {
  9076. this.raise(expr.start, ErrorMessages.InvalidLhs, contextDescription);
  9077. break;
  9078. }
  9079. this.checkLVal(expr.expression, "parenthesized expression", ...args);
  9080. return;
  9081. case "TSNonNullExpression":
  9082. this.checkLVal(expr.expression, contextDescription, ...args);
  9083. return;
  9084. default:
  9085. super.checkLVal(expr, contextDescription, ...args);
  9086. return;
  9087. }
  9088. }
  9089. parseBindingAtom() {
  9090. switch (this.state.type) {
  9091. case 72:
  9092. return this.parseIdentifier(true);
  9093. default:
  9094. return super.parseBindingAtom();
  9095. }
  9096. }
  9097. parseMaybeDecoratorArguments(expr) {
  9098. if (this.match(43)) {
  9099. const typeArguments = this.tsParseTypeArguments();
  9100. if (this.match(10)) {
  9101. const call = super.parseMaybeDecoratorArguments(expr);
  9102. call.typeParameters = typeArguments;
  9103. return call;
  9104. }
  9105. this.unexpected(this.state.start, 10);
  9106. }
  9107. return super.parseMaybeDecoratorArguments(expr);
  9108. }
  9109. checkCommaAfterRest(close) {
  9110. if (this.state.isAmbientContext && this.match(12) && this.lookaheadCharCode() === close) {
  9111. this.next();
  9112. } else {
  9113. super.checkCommaAfterRest(close);
  9114. }
  9115. }
  9116. isClassMethod() {
  9117. return this.match(43) || super.isClassMethod();
  9118. }
  9119. isClassProperty() {
  9120. return this.match(33) || this.match(14) || super.isClassProperty();
  9121. }
  9122. parseMaybeDefault(...args) {
  9123. const node = super.parseMaybeDefault(...args);
  9124. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  9125. this.raise(node.typeAnnotation.start, TSErrors.TypeAnnotationAfterAssign);
  9126. }
  9127. return node;
  9128. }
  9129. getTokenFromCode(code) {
  9130. if (this.state.inType) {
  9131. if (code === 62) {
  9132. return this.finishOp(44, 1);
  9133. }
  9134. if (code === 60) {
  9135. return this.finishOp(43, 1);
  9136. }
  9137. }
  9138. return super.getTokenFromCode(code);
  9139. }
  9140. reScan_lt_gt() {
  9141. const {
  9142. type
  9143. } = this.state;
  9144. if (type === 43) {
  9145. this.state.pos -= 1;
  9146. this.readToken_lt();
  9147. } else if (type === 44) {
  9148. this.state.pos -= 1;
  9149. this.readToken_gt();
  9150. }
  9151. }
  9152. toAssignableList(exprList) {
  9153. for (let i = 0; i < exprList.length; i++) {
  9154. const expr = exprList[i];
  9155. if (!expr) continue;
  9156. switch (expr.type) {
  9157. case "TSTypeCastExpression":
  9158. exprList[i] = this.typeCastToParameter(expr);
  9159. break;
  9160. case "TSAsExpression":
  9161. case "TSTypeAssertion":
  9162. if (!this.state.maybeInArrowParameters) {
  9163. exprList[i] = this.typeCastToParameter(expr);
  9164. } else {
  9165. this.raise(expr.start, TSErrors.UnexpectedTypeCastInParameter);
  9166. }
  9167. break;
  9168. }
  9169. }
  9170. return super.toAssignableList(...arguments);
  9171. }
  9172. typeCastToParameter(node) {
  9173. node.expression.typeAnnotation = node.typeAnnotation;
  9174. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  9175. return node.expression;
  9176. }
  9177. shouldParseArrow(params) {
  9178. if (this.match(14)) {
  9179. return params.every(expr => this.isAssignable(expr, true));
  9180. }
  9181. return super.shouldParseArrow(params);
  9182. }
  9183. shouldParseAsyncArrow() {
  9184. return this.match(14) || super.shouldParseAsyncArrow();
  9185. }
  9186. canHaveLeadingDecorator() {
  9187. return super.canHaveLeadingDecorator() || this.isAbstractClass();
  9188. }
  9189. jsxParseOpeningElementAfterName(node) {
  9190. if (this.match(43)) {
  9191. const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArguments());
  9192. if (typeArguments) node.typeParameters = typeArguments;
  9193. }
  9194. return super.jsxParseOpeningElementAfterName(node);
  9195. }
  9196. getGetterSetterExpectedParamCount(method) {
  9197. const baseCount = super.getGetterSetterExpectedParamCount(method);
  9198. const params = this.getObjectOrClassMethodParams(method);
  9199. const firstParam = params[0];
  9200. const hasContextParam = firstParam && this.isThisParam(firstParam);
  9201. return hasContextParam ? baseCount + 1 : baseCount;
  9202. }
  9203. parseCatchClauseParam() {
  9204. const param = super.parseCatchClauseParam();
  9205. const type = this.tsTryParseTypeAnnotation();
  9206. if (type) {
  9207. param.typeAnnotation = type;
  9208. this.resetEndLocation(param);
  9209. }
  9210. return param;
  9211. }
  9212. tsInAmbientContext(cb) {
  9213. const oldIsAmbientContext = this.state.isAmbientContext;
  9214. this.state.isAmbientContext = true;
  9215. try {
  9216. return cb();
  9217. } finally {
  9218. this.state.isAmbientContext = oldIsAmbientContext;
  9219. }
  9220. }
  9221. parseClass(node, ...args) {
  9222. const oldInAbstractClass = this.state.inAbstractClass;
  9223. this.state.inAbstractClass = !!node.abstract;
  9224. try {
  9225. return super.parseClass(node, ...args);
  9226. } finally {
  9227. this.state.inAbstractClass = oldInAbstractClass;
  9228. }
  9229. }
  9230. tsParseAbstractDeclaration(node) {
  9231. if (this.match(74)) {
  9232. node.abstract = true;
  9233. return this.parseClass(node, true, false);
  9234. } else if (this.isContextual(119)) {
  9235. if (!this.hasFollowingLineBreak()) {
  9236. node.abstract = true;
  9237. this.raise(node.start, TSErrors.NonClassMethodPropertyHasAbstractModifer);
  9238. this.next();
  9239. return this.tsParseInterfaceDeclaration(node);
  9240. }
  9241. } else {
  9242. this.unexpected(null, 74);
  9243. }
  9244. }
  9245. parseMethod(...args) {
  9246. const method = super.parseMethod(...args);
  9247. if (method.abstract) {
  9248. const hasBody = this.hasPlugin("estree") ? !!method.value.body : !!method.body;
  9249. if (hasBody) {
  9250. const {
  9251. key
  9252. } = method;
  9253. this.raise(method.start, TSErrors.AbstractMethodHasImplementation, key.type === "Identifier" && !method.computed ? key.name : `[${this.input.slice(key.start, key.end)}]`);
  9254. }
  9255. }
  9256. return method;
  9257. }
  9258. tsParseTypeParameterName() {
  9259. const typeName = this.parseIdentifier();
  9260. return typeName.name;
  9261. }
  9262. shouldParseAsAmbientContext() {
  9263. return !!this.getPluginOption("typescript", "dts");
  9264. }
  9265. parse() {
  9266. if (this.shouldParseAsAmbientContext()) {
  9267. this.state.isAmbientContext = true;
  9268. }
  9269. return super.parse();
  9270. }
  9271. getExpression() {
  9272. if (this.shouldParseAsAmbientContext()) {
  9273. this.state.isAmbientContext = true;
  9274. }
  9275. return super.getExpression();
  9276. }
  9277. parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) {
  9278. if (!isString && isMaybeTypeOnly) {
  9279. this.parseTypeOnlyImportExportSpecifier(node, false, isInTypeExport);
  9280. return this.finishNode(node, "ExportSpecifier");
  9281. }
  9282. node.exportKind = "value";
  9283. return super.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly);
  9284. }
  9285. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly) {
  9286. if (!importedIsString && isMaybeTypeOnly) {
  9287. this.parseTypeOnlyImportExportSpecifier(specifier, true, isInTypeOnlyImport);
  9288. return this.finishNode(specifier, "ImportSpecifier");
  9289. }
  9290. specifier.importKind = "value";
  9291. return super.parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly);
  9292. }
  9293. parseTypeOnlyImportExportSpecifier(node, isImport, isInTypeOnlyImportExport) {
  9294. const leftOfAsKey = isImport ? "imported" : "local";
  9295. const rightOfAsKey = isImport ? "local" : "exported";
  9296. let leftOfAs = node[leftOfAsKey];
  9297. let rightOfAs;
  9298. let hasTypeSpecifier = false;
  9299. let canParseAsKeyword = true;
  9300. const pos = leftOfAs.start;
  9301. if (this.isContextual(87)) {
  9302. const firstAs = this.parseIdentifier();
  9303. if (this.isContextual(87)) {
  9304. const secondAs = this.parseIdentifier();
  9305. if (tokenIsKeywordOrIdentifier(this.state.type)) {
  9306. hasTypeSpecifier = true;
  9307. leftOfAs = firstAs;
  9308. rightOfAs = this.parseIdentifier();
  9309. canParseAsKeyword = false;
  9310. } else {
  9311. rightOfAs = secondAs;
  9312. canParseAsKeyword = false;
  9313. }
  9314. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  9315. canParseAsKeyword = false;
  9316. rightOfAs = this.parseIdentifier();
  9317. } else {
  9318. hasTypeSpecifier = true;
  9319. leftOfAs = firstAs;
  9320. }
  9321. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  9322. hasTypeSpecifier = true;
  9323. leftOfAs = this.parseIdentifier();
  9324. }
  9325. if (hasTypeSpecifier && isInTypeOnlyImportExport) {
  9326. this.raise(pos, isImport ? TSErrors.TypeModifierIsUsedInTypeImports : TSErrors.TypeModifierIsUsedInTypeExports);
  9327. }
  9328. node[leftOfAsKey] = leftOfAs;
  9329. node[rightOfAsKey] = rightOfAs;
  9330. const kindKey = isImport ? "importKind" : "exportKind";
  9331. node[kindKey] = hasTypeSpecifier ? "type" : "value";
  9332. if (canParseAsKeyword && this.eatContextual(87)) {
  9333. node[rightOfAsKey] = isImport ? this.parseIdentifier() : this.parseModuleExportName();
  9334. }
  9335. if (!node[rightOfAsKey]) {
  9336. node[rightOfAsKey] = cloneIdentifier(node[leftOfAsKey]);
  9337. }
  9338. if (isImport) {
  9339. this.checkLVal(node[rightOfAsKey], "import specifier", BIND_LEXICAL);
  9340. }
  9341. }
  9342. });
  9343. const PlaceHolderErrors = makeErrorTemplates({
  9344. ClassNameIsRequired: "A class name is required."
  9345. }, ErrorCodes.SyntaxError);
  9346. var placeholders = (superClass => class extends superClass {
  9347. parsePlaceholder(expectedNode) {
  9348. if (this.match(134)) {
  9349. const node = this.startNode();
  9350. this.next();
  9351. this.assertNoSpace("Unexpected space in placeholder.");
  9352. node.name = super.parseIdentifier(true);
  9353. this.assertNoSpace("Unexpected space in placeholder.");
  9354. this.expect(134);
  9355. return this.finishPlaceholder(node, expectedNode);
  9356. }
  9357. }
  9358. finishPlaceholder(node, expectedNode) {
  9359. const isFinished = !!(node.expectedNode && node.type === "Placeholder");
  9360. node.expectedNode = expectedNode;
  9361. return isFinished ? node : this.finishNode(node, "Placeholder");
  9362. }
  9363. getTokenFromCode(code) {
  9364. if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) {
  9365. return this.finishOp(134, 2);
  9366. }
  9367. return super.getTokenFromCode(...arguments);
  9368. }
  9369. parseExprAtom() {
  9370. return this.parsePlaceholder("Expression") || super.parseExprAtom(...arguments);
  9371. }
  9372. parseIdentifier() {
  9373. return this.parsePlaceholder("Identifier") || super.parseIdentifier(...arguments);
  9374. }
  9375. checkReservedWord(word) {
  9376. if (word !== undefined) super.checkReservedWord(...arguments);
  9377. }
  9378. parseBindingAtom() {
  9379. return this.parsePlaceholder("Pattern") || super.parseBindingAtom(...arguments);
  9380. }
  9381. checkLVal(expr) {
  9382. if (expr.type !== "Placeholder") super.checkLVal(...arguments);
  9383. }
  9384. toAssignable(node) {
  9385. if (node && node.type === "Placeholder" && node.expectedNode === "Expression") {
  9386. node.expectedNode = "Pattern";
  9387. return node;
  9388. }
  9389. return super.toAssignable(...arguments);
  9390. }
  9391. isLet(context) {
  9392. if (super.isLet(context)) {
  9393. return true;
  9394. }
  9395. if (!this.isContextual(93)) {
  9396. return false;
  9397. }
  9398. if (context) return false;
  9399. const nextToken = this.lookahead();
  9400. if (nextToken.type === 134) {
  9401. return true;
  9402. }
  9403. return false;
  9404. }
  9405. verifyBreakContinue(node) {
  9406. if (node.label && node.label.type === "Placeholder") return;
  9407. super.verifyBreakContinue(...arguments);
  9408. }
  9409. parseExpressionStatement(node, expr) {
  9410. if (expr.type !== "Placeholder" || expr.extra && expr.extra.parenthesized) {
  9411. return super.parseExpressionStatement(...arguments);
  9412. }
  9413. if (this.match(14)) {
  9414. const stmt = node;
  9415. stmt.label = this.finishPlaceholder(expr, "Identifier");
  9416. this.next();
  9417. stmt.body = this.parseStatement("label");
  9418. return this.finishNode(stmt, "LabeledStatement");
  9419. }
  9420. this.semicolon();
  9421. node.name = expr.name;
  9422. return this.finishPlaceholder(node, "Statement");
  9423. }
  9424. parseBlock() {
  9425. return this.parsePlaceholder("BlockStatement") || super.parseBlock(...arguments);
  9426. }
  9427. parseFunctionId() {
  9428. return this.parsePlaceholder("Identifier") || super.parseFunctionId(...arguments);
  9429. }
  9430. parseClass(node, isStatement, optionalId) {
  9431. const type = isStatement ? "ClassDeclaration" : "ClassExpression";
  9432. this.next();
  9433. this.takeDecorators(node);
  9434. const oldStrict = this.state.strict;
  9435. const placeholder = this.parsePlaceholder("Identifier");
  9436. if (placeholder) {
  9437. if (this.match(75) || this.match(134) || this.match(5)) {
  9438. node.id = placeholder;
  9439. } else if (optionalId || !isStatement) {
  9440. node.id = null;
  9441. node.body = this.finishPlaceholder(placeholder, "ClassBody");
  9442. return this.finishNode(node, type);
  9443. } else {
  9444. this.unexpected(null, PlaceHolderErrors.ClassNameIsRequired);
  9445. }
  9446. } else {
  9447. this.parseClassId(node, isStatement, optionalId);
  9448. }
  9449. this.parseClassSuper(node);
  9450. node.body = this.parsePlaceholder("ClassBody") || this.parseClassBody(!!node.superClass, oldStrict);
  9451. return this.finishNode(node, type);
  9452. }
  9453. parseExport(node) {
  9454. const placeholder = this.parsePlaceholder("Identifier");
  9455. if (!placeholder) return super.parseExport(...arguments);
  9456. if (!this.isContextual(91) && !this.match(12)) {
  9457. node.specifiers = [];
  9458. node.source = null;
  9459. node.declaration = this.finishPlaceholder(placeholder, "Declaration");
  9460. return this.finishNode(node, "ExportNamedDeclaration");
  9461. }
  9462. this.expectPlugin("exportDefaultFrom");
  9463. const specifier = this.startNode();
  9464. specifier.exported = placeholder;
  9465. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  9466. return super.parseExport(node);
  9467. }
  9468. isExportDefaultSpecifier() {
  9469. if (this.match(59)) {
  9470. const next = this.nextTokenStart();
  9471. if (this.isUnparsedContextual(next, "from")) {
  9472. if (this.input.startsWith(tokenLabelName(134), this.nextTokenStartSince(next + 4))) {
  9473. return true;
  9474. }
  9475. }
  9476. }
  9477. return super.isExportDefaultSpecifier();
  9478. }
  9479. maybeParseExportDefaultSpecifier(node) {
  9480. if (node.specifiers && node.specifiers.length > 0) {
  9481. return true;
  9482. }
  9483. return super.maybeParseExportDefaultSpecifier(...arguments);
  9484. }
  9485. checkExport(node) {
  9486. const {
  9487. specifiers
  9488. } = node;
  9489. if (specifiers != null && specifiers.length) {
  9490. node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder");
  9491. }
  9492. super.checkExport(node);
  9493. node.specifiers = specifiers;
  9494. }
  9495. parseImport(node) {
  9496. const placeholder = this.parsePlaceholder("Identifier");
  9497. if (!placeholder) return super.parseImport(...arguments);
  9498. node.specifiers = [];
  9499. if (!this.isContextual(91) && !this.match(12)) {
  9500. node.source = this.finishPlaceholder(placeholder, "StringLiteral");
  9501. this.semicolon();
  9502. return this.finishNode(node, "ImportDeclaration");
  9503. }
  9504. const specifier = this.startNodeAtNode(placeholder);
  9505. specifier.local = placeholder;
  9506. this.finishNode(specifier, "ImportDefaultSpecifier");
  9507. node.specifiers.push(specifier);
  9508. if (this.eat(12)) {
  9509. const hasStarImport = this.maybeParseStarImportSpecifier(node);
  9510. if (!hasStarImport) this.parseNamedImportSpecifiers(node);
  9511. }
  9512. this.expectContextual(91);
  9513. node.source = this.parseImportSource();
  9514. this.semicolon();
  9515. return this.finishNode(node, "ImportDeclaration");
  9516. }
  9517. parseImportSource() {
  9518. return this.parsePlaceholder("StringLiteral") || super.parseImportSource(...arguments);
  9519. }
  9520. });
  9521. var v8intrinsic = (superClass => class extends superClass {
  9522. parseV8Intrinsic() {
  9523. if (this.match(48)) {
  9524. const v8IntrinsicStart = this.state.start;
  9525. const node = this.startNode();
  9526. this.next();
  9527. if (tokenIsIdentifier(this.state.type)) {
  9528. const name = this.parseIdentifierName(this.state.start);
  9529. const identifier = this.createIdentifier(node, name);
  9530. identifier.type = "V8IntrinsicIdentifier";
  9531. if (this.match(10)) {
  9532. return identifier;
  9533. }
  9534. }
  9535. this.unexpected(v8IntrinsicStart);
  9536. }
  9537. }
  9538. parseExprAtom() {
  9539. return this.parseV8Intrinsic() || super.parseExprAtom(...arguments);
  9540. }
  9541. });
  9542. function hasPlugin(plugins, name) {
  9543. return plugins.some(plugin => {
  9544. if (Array.isArray(plugin)) {
  9545. return plugin[0] === name;
  9546. } else {
  9547. return plugin === name;
  9548. }
  9549. });
  9550. }
  9551. function getPluginOption(plugins, name, option) {
  9552. const plugin = plugins.find(plugin => {
  9553. if (Array.isArray(plugin)) {
  9554. return plugin[0] === name;
  9555. } else {
  9556. return plugin === name;
  9557. }
  9558. });
  9559. if (plugin && Array.isArray(plugin)) {
  9560. return plugin[1][option];
  9561. }
  9562. return null;
  9563. }
  9564. const PIPELINE_PROPOSALS = ["minimal", "fsharp", "hack", "smart"];
  9565. const TOPIC_TOKENS = ["^", "%", "#"];
  9566. const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"];
  9567. function validatePlugins(plugins) {
  9568. if (hasPlugin(plugins, "decorators")) {
  9569. if (hasPlugin(plugins, "decorators-legacy")) {
  9570. throw new Error("Cannot use the decorators and decorators-legacy plugin together");
  9571. }
  9572. const decoratorsBeforeExport = getPluginOption(plugins, "decorators", "decoratorsBeforeExport");
  9573. if (decoratorsBeforeExport == null) {
  9574. 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'.");
  9575. } else if (typeof decoratorsBeforeExport !== "boolean") {
  9576. throw new Error("'decoratorsBeforeExport' must be a boolean.");
  9577. }
  9578. }
  9579. if (hasPlugin(plugins, "flow") && hasPlugin(plugins, "typescript")) {
  9580. throw new Error("Cannot combine flow and typescript plugins.");
  9581. }
  9582. if (hasPlugin(plugins, "placeholders") && hasPlugin(plugins, "v8intrinsic")) {
  9583. throw new Error("Cannot combine placeholders and v8intrinsic plugins.");
  9584. }
  9585. if (hasPlugin(plugins, "pipelineOperator")) {
  9586. const proposal = getPluginOption(plugins, "pipelineOperator", "proposal");
  9587. if (!PIPELINE_PROPOSALS.includes(proposal)) {
  9588. const proposalList = PIPELINE_PROPOSALS.map(p => `"${p}"`).join(", ");
  9589. throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${proposalList}.`);
  9590. }
  9591. const tupleSyntaxIsHash = hasPlugin(plugins, "recordAndTuple") && getPluginOption(plugins, "recordAndTuple", "syntaxType") === "hash";
  9592. if (proposal === "hack") {
  9593. if (hasPlugin(plugins, "placeholders")) {
  9594. throw new Error("Cannot combine placeholders plugin and Hack-style pipes.");
  9595. }
  9596. if (hasPlugin(plugins, "v8intrinsic")) {
  9597. throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes.");
  9598. }
  9599. const topicToken = getPluginOption(plugins, "pipelineOperator", "topicToken");
  9600. if (!TOPIC_TOKENS.includes(topicToken)) {
  9601. const tokenList = TOPIC_TOKENS.map(t => `"${t}"`).join(", ");
  9602. throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${tokenList}.`);
  9603. }
  9604. if (topicToken === "#" && tupleSyntaxIsHash) {
  9605. throw new Error('Plugin conflict between `["pipelineOperator", { proposal: "hack", topicToken: "#" }]` and `["recordAndtuple", { syntaxType: "hash"}]`.');
  9606. }
  9607. } else if (proposal === "smart" && tupleSyntaxIsHash) {
  9608. throw new Error('Plugin conflict between `["pipelineOperator", { proposal: "smart" }]` and `["recordAndtuple", { syntaxType: "hash"}]`.');
  9609. }
  9610. }
  9611. if (hasPlugin(plugins, "moduleAttributes")) {
  9612. {
  9613. if (hasPlugin(plugins, "importAssertions")) {
  9614. throw new Error("Cannot combine importAssertions and moduleAttributes plugins.");
  9615. }
  9616. const moduleAttributesVerionPluginOption = getPluginOption(plugins, "moduleAttributes", "version");
  9617. if (moduleAttributesVerionPluginOption !== "may-2020") {
  9618. throw new Error("The 'moduleAttributes' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is 'may-2020'.");
  9619. }
  9620. }
  9621. }
  9622. if (hasPlugin(plugins, "recordAndTuple") && !RECORD_AND_TUPLE_SYNTAX_TYPES.includes(getPluginOption(plugins, "recordAndTuple", "syntaxType"))) {
  9623. throw new Error("'recordAndTuple' requires 'syntaxType' option whose value should be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", "));
  9624. }
  9625. if (hasPlugin(plugins, "asyncDoExpressions") && !hasPlugin(plugins, "doExpressions")) {
  9626. const error = new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins.");
  9627. error.missingPlugins = "doExpressions";
  9628. throw error;
  9629. }
  9630. }
  9631. const mixinPlugins = {
  9632. estree,
  9633. jsx,
  9634. flow,
  9635. typescript,
  9636. v8intrinsic,
  9637. placeholders
  9638. };
  9639. const mixinPluginNames = Object.keys(mixinPlugins);
  9640. const defaultOptions = {
  9641. sourceType: "script",
  9642. sourceFilename: undefined,
  9643. startColumn: 0,
  9644. startLine: 1,
  9645. allowAwaitOutsideFunction: false,
  9646. allowReturnOutsideFunction: false,
  9647. allowImportExportEverywhere: false,
  9648. allowSuperOutsideMethod: false,
  9649. allowUndeclaredExports: false,
  9650. plugins: [],
  9651. strictMode: null,
  9652. ranges: false,
  9653. tokens: false,
  9654. createParenthesizedExpressions: false,
  9655. errorRecovery: false,
  9656. attachComment: true
  9657. };
  9658. function getOptions(opts) {
  9659. const options = {};
  9660. for (const key of Object.keys(defaultOptions)) {
  9661. options[key] = opts && opts[key] != null ? opts[key] : defaultOptions[key];
  9662. }
  9663. return options;
  9664. }
  9665. const unwrapParenthesizedExpression = node => {
  9666. return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node;
  9667. };
  9668. class LValParser extends NodeUtils {
  9669. toAssignable(node, isLHS = false) {
  9670. var _node$extra, _node$extra3;
  9671. let parenthesized = undefined;
  9672. if (node.type === "ParenthesizedExpression" || (_node$extra = node.extra) != null && _node$extra.parenthesized) {
  9673. parenthesized = unwrapParenthesizedExpression(node);
  9674. if (isLHS) {
  9675. if (parenthesized.type === "Identifier") {
  9676. this.expressionScope.recordParenthesizedIdentifierError(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  9677. } else if (parenthesized.type !== "MemberExpression") {
  9678. this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  9679. }
  9680. } else {
  9681. this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  9682. }
  9683. }
  9684. switch (node.type) {
  9685. case "Identifier":
  9686. case "ObjectPattern":
  9687. case "ArrayPattern":
  9688. case "AssignmentPattern":
  9689. case "RestElement":
  9690. break;
  9691. case "ObjectExpression":
  9692. node.type = "ObjectPattern";
  9693. for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) {
  9694. var _node$extra2;
  9695. const prop = node.properties[i];
  9696. const isLast = i === last;
  9697. this.toAssignableObjectExpressionProp(prop, isLast, isLHS);
  9698. if (isLast && prop.type === "RestElement" && (_node$extra2 = node.extra) != null && _node$extra2.trailingComma) {
  9699. this.raiseRestNotLast(node.extra.trailingComma);
  9700. }
  9701. }
  9702. break;
  9703. case "ObjectProperty":
  9704. this.toAssignable(node.value, isLHS);
  9705. break;
  9706. case "SpreadElement":
  9707. {
  9708. this.checkToRestConversion(node);
  9709. node.type = "RestElement";
  9710. const arg = node.argument;
  9711. this.toAssignable(arg, isLHS);
  9712. break;
  9713. }
  9714. case "ArrayExpression":
  9715. node.type = "ArrayPattern";
  9716. this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingComma, isLHS);
  9717. break;
  9718. case "AssignmentExpression":
  9719. if (node.operator !== "=") {
  9720. this.raise(node.left.end, ErrorMessages.MissingEqInAssignment);
  9721. }
  9722. node.type = "AssignmentPattern";
  9723. delete node.operator;
  9724. this.toAssignable(node.left, isLHS);
  9725. break;
  9726. case "ParenthesizedExpression":
  9727. this.toAssignable(parenthesized, isLHS);
  9728. break;
  9729. }
  9730. return node;
  9731. }
  9732. toAssignableObjectExpressionProp(prop, isLast, isLHS) {
  9733. if (prop.type === "ObjectMethod") {
  9734. const error = prop.kind === "get" || prop.kind === "set" ? ErrorMessages.PatternHasAccessor : ErrorMessages.PatternHasMethod;
  9735. this.raise(prop.key.start, error);
  9736. } else if (prop.type === "SpreadElement" && !isLast) {
  9737. this.raiseRestNotLast(prop.start);
  9738. } else {
  9739. this.toAssignable(prop, isLHS);
  9740. }
  9741. }
  9742. toAssignableList(exprList, trailingCommaPos, isLHS) {
  9743. let end = exprList.length;
  9744. if (end) {
  9745. const last = exprList[end - 1];
  9746. if ((last == null ? void 0 : last.type) === "RestElement") {
  9747. --end;
  9748. } else if ((last == null ? void 0 : last.type) === "SpreadElement") {
  9749. last.type = "RestElement";
  9750. let arg = last.argument;
  9751. this.toAssignable(arg, isLHS);
  9752. arg = unwrapParenthesizedExpression(arg);
  9753. if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern" && arg.type !== "ObjectPattern") {
  9754. this.unexpected(arg.start);
  9755. }
  9756. if (trailingCommaPos) {
  9757. this.raiseTrailingCommaAfterRest(trailingCommaPos);
  9758. }
  9759. --end;
  9760. }
  9761. }
  9762. for (let i = 0; i < end; i++) {
  9763. const elt = exprList[i];
  9764. if (elt) {
  9765. this.toAssignable(elt, isLHS);
  9766. if (elt.type === "RestElement") {
  9767. this.raiseRestNotLast(elt.start);
  9768. }
  9769. }
  9770. }
  9771. return exprList;
  9772. }
  9773. isAssignable(node, isBinding) {
  9774. switch (node.type) {
  9775. case "Identifier":
  9776. case "ObjectPattern":
  9777. case "ArrayPattern":
  9778. case "AssignmentPattern":
  9779. case "RestElement":
  9780. return true;
  9781. case "ObjectExpression":
  9782. {
  9783. const last = node.properties.length - 1;
  9784. return node.properties.every((prop, i) => {
  9785. return prop.type !== "ObjectMethod" && (i === last || prop.type !== "SpreadElement") && this.isAssignable(prop);
  9786. });
  9787. }
  9788. case "ObjectProperty":
  9789. return this.isAssignable(node.value);
  9790. case "SpreadElement":
  9791. return this.isAssignable(node.argument);
  9792. case "ArrayExpression":
  9793. return node.elements.every(element => element === null || this.isAssignable(element));
  9794. case "AssignmentExpression":
  9795. return node.operator === "=";
  9796. case "ParenthesizedExpression":
  9797. return this.isAssignable(node.expression);
  9798. case "MemberExpression":
  9799. case "OptionalMemberExpression":
  9800. return !isBinding;
  9801. default:
  9802. return false;
  9803. }
  9804. }
  9805. toReferencedList(exprList, isParenthesizedExpr) {
  9806. return exprList;
  9807. }
  9808. toReferencedListDeep(exprList, isParenthesizedExpr) {
  9809. this.toReferencedList(exprList, isParenthesizedExpr);
  9810. for (const expr of exprList) {
  9811. if ((expr == null ? void 0 : expr.type) === "ArrayExpression") {
  9812. this.toReferencedListDeep(expr.elements);
  9813. }
  9814. }
  9815. }
  9816. parseSpread(refExpressionErrors, refNeedsArrowPos) {
  9817. const node = this.startNode();
  9818. this.next();
  9819. node.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, undefined, refNeedsArrowPos);
  9820. return this.finishNode(node, "SpreadElement");
  9821. }
  9822. parseRestBinding() {
  9823. const node = this.startNode();
  9824. this.next();
  9825. node.argument = this.parseBindingAtom();
  9826. return this.finishNode(node, "RestElement");
  9827. }
  9828. parseBindingAtom() {
  9829. switch (this.state.type) {
  9830. case 0:
  9831. {
  9832. const node = this.startNode();
  9833. this.next();
  9834. node.elements = this.parseBindingList(3, 93, true);
  9835. return this.finishNode(node, "ArrayPattern");
  9836. }
  9837. case 5:
  9838. return this.parseObjectLike(8, true);
  9839. }
  9840. return this.parseIdentifier();
  9841. }
  9842. parseBindingList(close, closeCharCode, allowEmpty, allowModifiers) {
  9843. const elts = [];
  9844. let first = true;
  9845. while (!this.eat(close)) {
  9846. if (first) {
  9847. first = false;
  9848. } else {
  9849. this.expect(12);
  9850. }
  9851. if (allowEmpty && this.match(12)) {
  9852. elts.push(null);
  9853. } else if (this.eat(close)) {
  9854. break;
  9855. } else if (this.match(21)) {
  9856. elts.push(this.parseAssignableListItemTypes(this.parseRestBinding()));
  9857. this.checkCommaAfterRest(closeCharCode);
  9858. this.expect(close);
  9859. break;
  9860. } else {
  9861. const decorators = [];
  9862. if (this.match(24) && this.hasPlugin("decorators")) {
  9863. this.raise(this.state.start, ErrorMessages.UnsupportedParameterDecorator);
  9864. }
  9865. while (this.match(24)) {
  9866. decorators.push(this.parseDecorator());
  9867. }
  9868. elts.push(this.parseAssignableListItem(allowModifiers, decorators));
  9869. }
  9870. }
  9871. return elts;
  9872. }
  9873. parseBindingRestProperty(prop) {
  9874. this.next();
  9875. prop.argument = this.parseIdentifier();
  9876. this.checkCommaAfterRest(125);
  9877. return this.finishNode(prop, "RestElement");
  9878. }
  9879. parseBindingProperty() {
  9880. const prop = this.startNode();
  9881. const {
  9882. type,
  9883. start: startPos,
  9884. startLoc
  9885. } = this.state;
  9886. if (type === 21) {
  9887. return this.parseBindingRestProperty(prop);
  9888. } else {
  9889. this.parsePropertyName(prop);
  9890. }
  9891. prop.method = false;
  9892. this.parseObjPropValue(prop, startPos, startLoc, false, false, true, false);
  9893. return prop;
  9894. }
  9895. parseAssignableListItem(allowModifiers, decorators) {
  9896. const left = this.parseMaybeDefault();
  9897. this.parseAssignableListItemTypes(left);
  9898. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  9899. if (decorators.length) {
  9900. left.decorators = decorators;
  9901. }
  9902. return elt;
  9903. }
  9904. parseAssignableListItemTypes(param) {
  9905. return param;
  9906. }
  9907. parseMaybeDefault(startPos, startLoc, left) {
  9908. var _startLoc, _startPos, _left;
  9909. startLoc = (_startLoc = startLoc) != null ? _startLoc : this.state.startLoc;
  9910. startPos = (_startPos = startPos) != null ? _startPos : this.state.start;
  9911. left = (_left = left) != null ? _left : this.parseBindingAtom();
  9912. if (!this.eat(27)) return left;
  9913. const node = this.startNodeAt(startPos, startLoc);
  9914. node.left = left;
  9915. node.right = this.parseMaybeAssignAllowIn();
  9916. return this.finishNode(node, "AssignmentPattern");
  9917. }
  9918. checkLVal(expr, contextDescription, bindingType = BIND_NONE, checkClashes, disallowLetBinding, strictModeChanged = false) {
  9919. switch (expr.type) {
  9920. case "Identifier":
  9921. {
  9922. const {
  9923. name
  9924. } = expr;
  9925. if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(name, this.inModule) : isStrictBindOnlyReservedWord(name))) {
  9926. this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.StrictEvalArguments : ErrorMessages.StrictEvalArgumentsBinding, name);
  9927. }
  9928. if (checkClashes) {
  9929. if (checkClashes.has(name)) {
  9930. this.raise(expr.start, ErrorMessages.ParamDupe);
  9931. } else {
  9932. checkClashes.add(name);
  9933. }
  9934. }
  9935. if (disallowLetBinding && name === "let") {
  9936. this.raise(expr.start, ErrorMessages.LetInLexicalBinding);
  9937. }
  9938. if (!(bindingType & BIND_NONE)) {
  9939. this.scope.declareName(name, bindingType, expr.start);
  9940. }
  9941. break;
  9942. }
  9943. case "MemberExpression":
  9944. if (bindingType !== BIND_NONE) {
  9945. this.raise(expr.start, ErrorMessages.InvalidPropertyBindingPattern);
  9946. }
  9947. break;
  9948. case "ObjectPattern":
  9949. for (let prop of expr.properties) {
  9950. if (this.isObjectProperty(prop)) prop = prop.value;else if (this.isObjectMethod(prop)) continue;
  9951. this.checkLVal(prop, "object destructuring pattern", bindingType, checkClashes, disallowLetBinding);
  9952. }
  9953. break;
  9954. case "ArrayPattern":
  9955. for (const elem of expr.elements) {
  9956. if (elem) {
  9957. this.checkLVal(elem, "array destructuring pattern", bindingType, checkClashes, disallowLetBinding);
  9958. }
  9959. }
  9960. break;
  9961. case "AssignmentPattern":
  9962. this.checkLVal(expr.left, "assignment pattern", bindingType, checkClashes);
  9963. break;
  9964. case "RestElement":
  9965. this.checkLVal(expr.argument, "rest element", bindingType, checkClashes);
  9966. break;
  9967. case "ParenthesizedExpression":
  9968. this.checkLVal(expr.expression, "parenthesized expression", bindingType, checkClashes);
  9969. break;
  9970. default:
  9971. {
  9972. this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.InvalidLhs : ErrorMessages.InvalidLhsBinding, contextDescription);
  9973. }
  9974. }
  9975. }
  9976. checkToRestConversion(node) {
  9977. if (node.argument.type !== "Identifier" && node.argument.type !== "MemberExpression") {
  9978. this.raise(node.argument.start, ErrorMessages.InvalidRestAssignmentPattern);
  9979. }
  9980. }
  9981. checkCommaAfterRest(close) {
  9982. if (this.match(12)) {
  9983. if (this.lookaheadCharCode() === close) {
  9984. this.raiseTrailingCommaAfterRest(this.state.start);
  9985. } else {
  9986. this.raiseRestNotLast(this.state.start);
  9987. }
  9988. }
  9989. }
  9990. raiseRestNotLast(pos) {
  9991. throw this.raise(pos, ErrorMessages.ElementAfterRest);
  9992. }
  9993. raiseTrailingCommaAfterRest(pos) {
  9994. this.raise(pos, ErrorMessages.RestTrailingComma);
  9995. }
  9996. }
  9997. const invalidHackPipeBodies = new Map([["ArrowFunctionExpression", "arrow function"], ["AssignmentExpression", "assignment"], ["ConditionalExpression", "conditional"], ["YieldExpression", "yield"]]);
  9998. class ExpressionParser extends LValParser {
  9999. checkProto(prop, isRecord, protoRef, refExpressionErrors) {
  10000. if (prop.type === "SpreadElement" || this.isObjectMethod(prop) || prop.computed || prop.shorthand) {
  10001. return;
  10002. }
  10003. const key = prop.key;
  10004. const name = key.type === "Identifier" ? key.name : key.value;
  10005. if (name === "__proto__") {
  10006. if (isRecord) {
  10007. this.raise(key.start, ErrorMessages.RecordNoProto);
  10008. return;
  10009. }
  10010. if (protoRef.used) {
  10011. if (refExpressionErrors) {
  10012. if (refExpressionErrors.doubleProto === -1) {
  10013. refExpressionErrors.doubleProto = key.start;
  10014. }
  10015. } else {
  10016. this.raise(key.start, ErrorMessages.DuplicateProto);
  10017. }
  10018. }
  10019. protoRef.used = true;
  10020. }
  10021. }
  10022. shouldExitDescending(expr, potentialArrowAt) {
  10023. return expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt;
  10024. }
  10025. getExpression() {
  10026. this.enterInitialScopes();
  10027. this.nextToken();
  10028. const expr = this.parseExpression();
  10029. if (!this.match(129)) {
  10030. this.unexpected();
  10031. }
  10032. this.finalizeRemainingComments();
  10033. expr.comments = this.state.comments;
  10034. expr.errors = this.state.errors;
  10035. if (this.options.tokens) {
  10036. expr.tokens = this.tokens;
  10037. }
  10038. return expr;
  10039. }
  10040. parseExpression(disallowIn, refExpressionErrors) {
  10041. if (disallowIn) {
  10042. return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  10043. }
  10044. return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  10045. }
  10046. parseExpressionBase(refExpressionErrors) {
  10047. const startPos = this.state.start;
  10048. const startLoc = this.state.startLoc;
  10049. const expr = this.parseMaybeAssign(refExpressionErrors);
  10050. if (this.match(12)) {
  10051. const node = this.startNodeAt(startPos, startLoc);
  10052. node.expressions = [expr];
  10053. while (this.eat(12)) {
  10054. node.expressions.push(this.parseMaybeAssign(refExpressionErrors));
  10055. }
  10056. this.toReferencedList(node.expressions);
  10057. return this.finishNode(node, "SequenceExpression");
  10058. }
  10059. return expr;
  10060. }
  10061. parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse) {
  10062. return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse));
  10063. }
  10064. parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse) {
  10065. return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse));
  10066. }
  10067. setOptionalParametersError(refExpressionErrors, resultError) {
  10068. var _resultError$pos;
  10069. refExpressionErrors.optionalParameters = (_resultError$pos = resultError == null ? void 0 : resultError.pos) != null ? _resultError$pos : this.state.start;
  10070. }
  10071. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  10072. const startPos = this.state.start;
  10073. const startLoc = this.state.startLoc;
  10074. if (this.isContextual(99)) {
  10075. if (this.prodParam.hasYield) {
  10076. let left = this.parseYield();
  10077. if (afterLeftParse) {
  10078. left = afterLeftParse.call(this, left, startPos, startLoc);
  10079. }
  10080. return left;
  10081. }
  10082. }
  10083. let ownExpressionErrors;
  10084. if (refExpressionErrors) {
  10085. ownExpressionErrors = false;
  10086. } else {
  10087. refExpressionErrors = new ExpressionErrors();
  10088. ownExpressionErrors = true;
  10089. }
  10090. const {
  10091. type
  10092. } = this.state;
  10093. if (type === 10 || tokenIsIdentifier(type)) {
  10094. this.state.potentialArrowAt = this.state.start;
  10095. }
  10096. let left = this.parseMaybeConditional(refExpressionErrors);
  10097. if (afterLeftParse) {
  10098. left = afterLeftParse.call(this, left, startPos, startLoc);
  10099. }
  10100. if (tokenIsAssignment(this.state.type)) {
  10101. const node = this.startNodeAt(startPos, startLoc);
  10102. const operator = this.state.value;
  10103. node.operator = operator;
  10104. if (this.match(27)) {
  10105. node.left = this.toAssignable(left, true);
  10106. if (refExpressionErrors.doubleProto >= startPos) {
  10107. refExpressionErrors.doubleProto = -1;
  10108. }
  10109. if (refExpressionErrors.shorthandAssign >= startPos) {
  10110. refExpressionErrors.shorthandAssign = -1;
  10111. }
  10112. } else {
  10113. node.left = left;
  10114. }
  10115. this.checkLVal(left, "assignment expression");
  10116. this.next();
  10117. node.right = this.parseMaybeAssign();
  10118. return this.finishNode(node, "AssignmentExpression");
  10119. } else if (ownExpressionErrors) {
  10120. this.checkExpressionErrors(refExpressionErrors, true);
  10121. }
  10122. return left;
  10123. }
  10124. parseMaybeConditional(refExpressionErrors) {
  10125. const startPos = this.state.start;
  10126. const startLoc = this.state.startLoc;
  10127. const potentialArrowAt = this.state.potentialArrowAt;
  10128. const expr = this.parseExprOps(refExpressionErrors);
  10129. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  10130. return expr;
  10131. }
  10132. return this.parseConditional(expr, startPos, startLoc, refExpressionErrors);
  10133. }
  10134. parseConditional(expr, startPos, startLoc, refExpressionErrors) {
  10135. if (this.eat(17)) {
  10136. const node = this.startNodeAt(startPos, startLoc);
  10137. node.test = expr;
  10138. node.consequent = this.parseMaybeAssignAllowIn();
  10139. this.expect(14);
  10140. node.alternate = this.parseMaybeAssign();
  10141. return this.finishNode(node, "ConditionalExpression");
  10142. }
  10143. return expr;
  10144. }
  10145. parseMaybeUnaryOrPrivate(refExpressionErrors) {
  10146. return this.match(128) ? this.parsePrivateName() : this.parseMaybeUnary(refExpressionErrors);
  10147. }
  10148. parseExprOps(refExpressionErrors) {
  10149. const startPos = this.state.start;
  10150. const startLoc = this.state.startLoc;
  10151. const potentialArrowAt = this.state.potentialArrowAt;
  10152. const expr = this.parseMaybeUnaryOrPrivate(refExpressionErrors);
  10153. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  10154. return expr;
  10155. }
  10156. return this.parseExprOp(expr, startPos, startLoc, -1);
  10157. }
  10158. parseExprOp(left, leftStartPos, leftStartLoc, minPrec) {
  10159. if (this.isPrivateName(left)) {
  10160. const value = this.getPrivateNameSV(left);
  10161. const {
  10162. start
  10163. } = left;
  10164. if (minPrec >= tokenOperatorPrecedence(52) || !this.prodParam.hasIn || !this.match(52)) {
  10165. this.raise(start, ErrorMessages.PrivateInExpectedIn, value);
  10166. }
  10167. this.classScope.usePrivateName(value, start);
  10168. }
  10169. const op = this.state.type;
  10170. if (tokenIsOperator(op) && (this.prodParam.hasIn || !this.match(52))) {
  10171. let prec = tokenOperatorPrecedence(op);
  10172. if (prec > minPrec) {
  10173. if (op === 35) {
  10174. this.expectPlugin("pipelineOperator");
  10175. if (this.state.inFSharpPipelineDirectBody) {
  10176. return left;
  10177. }
  10178. this.checkPipelineAtInfixOperator(left, leftStartPos);
  10179. }
  10180. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  10181. node.left = left;
  10182. node.operator = this.state.value;
  10183. const logical = op === 37 || op === 38;
  10184. const coalesce = op === 36;
  10185. if (coalesce) {
  10186. prec = tokenOperatorPrecedence(38);
  10187. }
  10188. this.next();
  10189. if (op === 35 && this.getPluginOption("pipelineOperator", "proposal") === "minimal") {
  10190. if (this.state.type === 90 && this.prodParam.hasAwait) {
  10191. throw this.raise(this.state.start, ErrorMessages.UnexpectedAwaitAfterPipelineBody);
  10192. }
  10193. }
  10194. node.right = this.parseExprOpRightExpr(op, prec);
  10195. this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression");
  10196. const nextOp = this.state.type;
  10197. if (coalesce && (nextOp === 37 || nextOp === 38) || logical && nextOp === 36) {
  10198. throw this.raise(this.state.start, ErrorMessages.MixingCoalesceWithLogical);
  10199. }
  10200. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec);
  10201. }
  10202. }
  10203. return left;
  10204. }
  10205. parseExprOpRightExpr(op, prec) {
  10206. const startPos = this.state.start;
  10207. const startLoc = this.state.startLoc;
  10208. switch (op) {
  10209. case 35:
  10210. switch (this.getPluginOption("pipelineOperator", "proposal")) {
  10211. case "hack":
  10212. return this.withTopicBindingContext(() => {
  10213. return this.parseHackPipeBody();
  10214. });
  10215. case "smart":
  10216. return this.withTopicBindingContext(() => {
  10217. if (this.prodParam.hasYield && this.isContextual(99)) {
  10218. throw this.raise(this.state.start, ErrorMessages.PipeBodyIsTighter, this.state.value);
  10219. }
  10220. return this.parseSmartPipelineBodyInStyle(this.parseExprOpBaseRightExpr(op, prec), startPos, startLoc);
  10221. });
  10222. case "fsharp":
  10223. return this.withSoloAwaitPermittingContext(() => {
  10224. return this.parseFSharpPipelineBody(prec);
  10225. });
  10226. }
  10227. default:
  10228. return this.parseExprOpBaseRightExpr(op, prec);
  10229. }
  10230. }
  10231. parseExprOpBaseRightExpr(op, prec) {
  10232. const startPos = this.state.start;
  10233. const startLoc = this.state.startLoc;
  10234. return this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startPos, startLoc, tokenIsRightAssociative(op) ? prec - 1 : prec);
  10235. }
  10236. parseHackPipeBody() {
  10237. var _body$extra;
  10238. const {
  10239. start
  10240. } = this.state;
  10241. const body = this.parseMaybeAssign();
  10242. if (invalidHackPipeBodies.has(body.type) && !((_body$extra = body.extra) != null && _body$extra.parenthesized)) {
  10243. this.raise(start, ErrorMessages.PipeUnparenthesizedBody, invalidHackPipeBodies.get(body.type));
  10244. }
  10245. if (!this.topicReferenceWasUsedInCurrentContext()) {
  10246. this.raise(start, ErrorMessages.PipeTopicUnused);
  10247. }
  10248. return body;
  10249. }
  10250. checkExponentialAfterUnary(node) {
  10251. if (this.match(51)) {
  10252. this.raise(node.argument.start, ErrorMessages.UnexpectedTokenUnaryExponentiation);
  10253. }
  10254. }
  10255. parseMaybeUnary(refExpressionErrors, sawUnary) {
  10256. const startPos = this.state.start;
  10257. const startLoc = this.state.startLoc;
  10258. const isAwait = this.isContextual(90);
  10259. if (isAwait && this.isAwaitAllowed()) {
  10260. this.next();
  10261. const expr = this.parseAwait(startPos, startLoc);
  10262. if (!sawUnary) this.checkExponentialAfterUnary(expr);
  10263. return expr;
  10264. }
  10265. const update = this.match(32);
  10266. const node = this.startNode();
  10267. if (tokenIsPrefix(this.state.type)) {
  10268. node.operator = this.state.value;
  10269. node.prefix = true;
  10270. if (this.match(66)) {
  10271. this.expectPlugin("throwExpressions");
  10272. }
  10273. const isDelete = this.match(83);
  10274. this.next();
  10275. node.argument = this.parseMaybeUnary(null, true);
  10276. this.checkExpressionErrors(refExpressionErrors, true);
  10277. if (this.state.strict && isDelete) {
  10278. const arg = node.argument;
  10279. if (arg.type === "Identifier") {
  10280. this.raise(node.start, ErrorMessages.StrictDelete);
  10281. } else if (this.hasPropertyAsPrivateName(arg)) {
  10282. this.raise(node.start, ErrorMessages.DeletePrivateField);
  10283. }
  10284. }
  10285. if (!update) {
  10286. if (!sawUnary) this.checkExponentialAfterUnary(node);
  10287. return this.finishNode(node, "UnaryExpression");
  10288. }
  10289. }
  10290. const expr = this.parseUpdate(node, update, refExpressionErrors);
  10291. if (isAwait) {
  10292. const {
  10293. type
  10294. } = this.state;
  10295. const startsExpr = this.hasPlugin("v8intrinsic") ? tokenCanStartExpression(type) : tokenCanStartExpression(type) && !this.match(48);
  10296. if (startsExpr && !this.isAmbiguousAwait()) {
  10297. this.raiseOverwrite(startPos, ErrorMessages.AwaitNotInAsyncContext);
  10298. return this.parseAwait(startPos, startLoc);
  10299. }
  10300. }
  10301. return expr;
  10302. }
  10303. parseUpdate(node, update, refExpressionErrors) {
  10304. if (update) {
  10305. this.checkLVal(node.argument, "prefix operation");
  10306. return this.finishNode(node, "UpdateExpression");
  10307. }
  10308. const startPos = this.state.start;
  10309. const startLoc = this.state.startLoc;
  10310. let expr = this.parseExprSubscripts(refExpressionErrors);
  10311. if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
  10312. while (tokenIsPostfix(this.state.type) && !this.canInsertSemicolon()) {
  10313. const node = this.startNodeAt(startPos, startLoc);
  10314. node.operator = this.state.value;
  10315. node.prefix = false;
  10316. node.argument = expr;
  10317. this.checkLVal(expr, "postfix operation");
  10318. this.next();
  10319. expr = this.finishNode(node, "UpdateExpression");
  10320. }
  10321. return expr;
  10322. }
  10323. parseExprSubscripts(refExpressionErrors) {
  10324. const startPos = this.state.start;
  10325. const startLoc = this.state.startLoc;
  10326. const potentialArrowAt = this.state.potentialArrowAt;
  10327. const expr = this.parseExprAtom(refExpressionErrors);
  10328. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  10329. return expr;
  10330. }
  10331. return this.parseSubscripts(expr, startPos, startLoc);
  10332. }
  10333. parseSubscripts(base, startPos, startLoc, noCalls) {
  10334. const state = {
  10335. optionalChainMember: false,
  10336. maybeAsyncArrow: this.atPossibleAsyncArrow(base),
  10337. stop: false
  10338. };
  10339. do {
  10340. base = this.parseSubscript(base, startPos, startLoc, noCalls, state);
  10341. state.maybeAsyncArrow = false;
  10342. } while (!state.stop);
  10343. return base;
  10344. }
  10345. parseSubscript(base, startPos, startLoc, noCalls, state) {
  10346. if (!noCalls && this.eat(15)) {
  10347. return this.parseBind(base, startPos, startLoc, noCalls, state);
  10348. } else if (this.match(22)) {
  10349. return this.parseTaggedTemplateExpression(base, startPos, startLoc, state);
  10350. }
  10351. let optional = false;
  10352. if (this.match(18)) {
  10353. if (noCalls && this.lookaheadCharCode() === 40) {
  10354. state.stop = true;
  10355. return base;
  10356. }
  10357. state.optionalChainMember = optional = true;
  10358. this.next();
  10359. }
  10360. if (!noCalls && this.match(10)) {
  10361. return this.parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional);
  10362. } else {
  10363. const computed = this.eat(0);
  10364. if (computed || optional || this.eat(16)) {
  10365. return this.parseMember(base, startPos, startLoc, state, computed, optional);
  10366. } else {
  10367. state.stop = true;
  10368. return base;
  10369. }
  10370. }
  10371. }
  10372. parseMember(base, startPos, startLoc, state, computed, optional) {
  10373. const node = this.startNodeAt(startPos, startLoc);
  10374. node.object = base;
  10375. node.computed = computed;
  10376. const privateName = !computed && this.match(128) && this.state.value;
  10377. const property = computed ? this.parseExpression() : privateName ? this.parsePrivateName() : this.parseIdentifier(true);
  10378. if (privateName !== false) {
  10379. if (node.object.type === "Super") {
  10380. this.raise(startPos, ErrorMessages.SuperPrivateField);
  10381. }
  10382. this.classScope.usePrivateName(privateName, property.start);
  10383. }
  10384. node.property = property;
  10385. if (computed) {
  10386. this.expect(3);
  10387. }
  10388. if (state.optionalChainMember) {
  10389. node.optional = optional;
  10390. return this.finishNode(node, "OptionalMemberExpression");
  10391. } else {
  10392. return this.finishNode(node, "MemberExpression");
  10393. }
  10394. }
  10395. parseBind(base, startPos, startLoc, noCalls, state) {
  10396. const node = this.startNodeAt(startPos, startLoc);
  10397. node.object = base;
  10398. node.callee = this.parseNoCallExpr();
  10399. state.stop = true;
  10400. return this.parseSubscripts(this.finishNode(node, "BindExpression"), startPos, startLoc, noCalls);
  10401. }
  10402. parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional) {
  10403. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  10404. let refExpressionErrors = null;
  10405. this.state.maybeInArrowParameters = true;
  10406. this.next();
  10407. let node = this.startNodeAt(startPos, startLoc);
  10408. node.callee = base;
  10409. if (state.maybeAsyncArrow) {
  10410. this.expressionScope.enter(newAsyncArrowScope());
  10411. refExpressionErrors = new ExpressionErrors();
  10412. }
  10413. if (state.optionalChainMember) {
  10414. node.optional = optional;
  10415. }
  10416. if (optional) {
  10417. node.arguments = this.parseCallExpressionArguments(11);
  10418. } else {
  10419. node.arguments = this.parseCallExpressionArguments(11, base.type === "Import", base.type !== "Super", node, refExpressionErrors);
  10420. }
  10421. this.finishCallExpression(node, state.optionalChainMember);
  10422. if (state.maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {
  10423. state.stop = true;
  10424. this.expressionScope.validateAsPattern();
  10425. this.expressionScope.exit();
  10426. node = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startPos, startLoc), node);
  10427. } else {
  10428. if (state.maybeAsyncArrow) {
  10429. this.checkExpressionErrors(refExpressionErrors, true);
  10430. this.expressionScope.exit();
  10431. }
  10432. this.toReferencedArguments(node);
  10433. }
  10434. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  10435. return node;
  10436. }
  10437. toReferencedArguments(node, isParenthesizedExpr) {
  10438. this.toReferencedListDeep(node.arguments, isParenthesizedExpr);
  10439. }
  10440. parseTaggedTemplateExpression(base, startPos, startLoc, state) {
  10441. const node = this.startNodeAt(startPos, startLoc);
  10442. node.tag = base;
  10443. node.quasi = this.parseTemplate(true);
  10444. if (state.optionalChainMember) {
  10445. this.raise(startPos, ErrorMessages.OptionalChainingNoTemplate);
  10446. }
  10447. return this.finishNode(node, "TaggedTemplateExpression");
  10448. }
  10449. atPossibleAsyncArrow(base) {
  10450. return base.type === "Identifier" && base.name === "async" && this.state.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && base.start === this.state.potentialArrowAt;
  10451. }
  10452. finishCallExpression(node, optional) {
  10453. if (node.callee.type === "Import") {
  10454. if (node.arguments.length === 2) {
  10455. {
  10456. if (!this.hasPlugin("moduleAttributes")) {
  10457. this.expectPlugin("importAssertions");
  10458. }
  10459. }
  10460. }
  10461. if (node.arguments.length === 0 || node.arguments.length > 2) {
  10462. this.raise(node.start, ErrorMessages.ImportCallArity, this.hasPlugin("importAssertions") || this.hasPlugin("moduleAttributes") ? "one or two arguments" : "one argument");
  10463. } else {
  10464. for (const arg of node.arguments) {
  10465. if (arg.type === "SpreadElement") {
  10466. this.raise(arg.start, ErrorMessages.ImportCallSpreadArgument);
  10467. }
  10468. }
  10469. }
  10470. }
  10471. return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression");
  10472. }
  10473. parseCallExpressionArguments(close, dynamicImport, allowPlaceholder, nodeForExtra, refExpressionErrors) {
  10474. const elts = [];
  10475. let first = true;
  10476. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  10477. this.state.inFSharpPipelineDirectBody = false;
  10478. while (!this.eat(close)) {
  10479. if (first) {
  10480. first = false;
  10481. } else {
  10482. this.expect(12);
  10483. if (this.match(close)) {
  10484. if (dynamicImport && !this.hasPlugin("importAssertions") && !this.hasPlugin("moduleAttributes")) {
  10485. this.raise(this.state.lastTokStart, ErrorMessages.ImportCallArgumentTrailingComma);
  10486. }
  10487. if (nodeForExtra) {
  10488. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  10489. }
  10490. this.next();
  10491. break;
  10492. }
  10493. }
  10494. elts.push(this.parseExprListItem(false, refExpressionErrors, allowPlaceholder));
  10495. }
  10496. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  10497. return elts;
  10498. }
  10499. shouldParseAsyncArrow() {
  10500. return this.match(19) && !this.canInsertSemicolon();
  10501. }
  10502. parseAsyncArrowFromCallExpression(node, call) {
  10503. var _call$extra;
  10504. this.resetPreviousNodeTrailingComments(call);
  10505. this.expect(19);
  10506. this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingComma);
  10507. if (call.innerComments) {
  10508. setInnerComments(node, call.innerComments);
  10509. }
  10510. if (call.callee.trailingComments) {
  10511. setInnerComments(node, call.callee.trailingComments);
  10512. }
  10513. return node;
  10514. }
  10515. parseNoCallExpr() {
  10516. const startPos = this.state.start;
  10517. const startLoc = this.state.startLoc;
  10518. return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  10519. }
  10520. parseExprAtom(refExpressionErrors) {
  10521. let node;
  10522. const {
  10523. type
  10524. } = this.state;
  10525. switch (type) {
  10526. case 73:
  10527. return this.parseSuper();
  10528. case 77:
  10529. node = this.startNode();
  10530. this.next();
  10531. if (this.match(16)) {
  10532. return this.parseImportMetaProperty(node);
  10533. }
  10534. if (!this.match(10)) {
  10535. this.raise(this.state.lastTokStart, ErrorMessages.UnsupportedImport);
  10536. }
  10537. return this.finishNode(node, "Import");
  10538. case 72:
  10539. node = this.startNode();
  10540. this.next();
  10541. return this.finishNode(node, "ThisExpression");
  10542. case 84:
  10543. {
  10544. return this.parseDo(this.startNode(), false);
  10545. }
  10546. case 50:
  10547. case 29:
  10548. {
  10549. this.readRegexp();
  10550. return this.parseRegExpLiteral(this.state.value);
  10551. }
  10552. case 124:
  10553. return this.parseNumericLiteral(this.state.value);
  10554. case 125:
  10555. return this.parseBigIntLiteral(this.state.value);
  10556. case 126:
  10557. return this.parseDecimalLiteral(this.state.value);
  10558. case 123:
  10559. return this.parseStringLiteral(this.state.value);
  10560. case 78:
  10561. return this.parseNullLiteral();
  10562. case 79:
  10563. return this.parseBooleanLiteral(true);
  10564. case 80:
  10565. return this.parseBooleanLiteral(false);
  10566. case 10:
  10567. {
  10568. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  10569. return this.parseParenAndDistinguishExpression(canBeArrow);
  10570. }
  10571. case 2:
  10572. case 1:
  10573. {
  10574. return this.parseArrayLike(this.state.type === 2 ? 4 : 3, false, true);
  10575. }
  10576. case 0:
  10577. {
  10578. return this.parseArrayLike(3, true, false, refExpressionErrors);
  10579. }
  10580. case 6:
  10581. case 7:
  10582. {
  10583. return this.parseObjectLike(this.state.type === 6 ? 9 : 8, false, true);
  10584. }
  10585. case 5:
  10586. {
  10587. return this.parseObjectLike(8, false, false, refExpressionErrors);
  10588. }
  10589. case 62:
  10590. return this.parseFunctionOrFunctionSent();
  10591. case 24:
  10592. this.parseDecorators();
  10593. case 74:
  10594. node = this.startNode();
  10595. this.takeDecorators(node);
  10596. return this.parseClass(node, false);
  10597. case 71:
  10598. return this.parseNewOrNewTarget();
  10599. case 22:
  10600. return this.parseTemplate(false);
  10601. case 15:
  10602. {
  10603. node = this.startNode();
  10604. this.next();
  10605. node.object = null;
  10606. const callee = node.callee = this.parseNoCallExpr();
  10607. if (callee.type === "MemberExpression") {
  10608. return this.finishNode(node, "BindExpression");
  10609. } else {
  10610. throw this.raise(callee.start, ErrorMessages.UnsupportedBind);
  10611. }
  10612. }
  10613. case 128:
  10614. {
  10615. this.raise(this.state.start, ErrorMessages.PrivateInExpectedIn, this.state.value);
  10616. return this.parsePrivateName();
  10617. }
  10618. case 31:
  10619. {
  10620. return this.parseTopicReferenceThenEqualsSign(48, "%");
  10621. }
  10622. case 30:
  10623. {
  10624. return this.parseTopicReferenceThenEqualsSign(40, "^");
  10625. }
  10626. case 40:
  10627. case 48:
  10628. case 25:
  10629. {
  10630. const pipeProposal = this.getPluginOption("pipelineOperator", "proposal");
  10631. if (pipeProposal) {
  10632. return this.parseTopicReference(pipeProposal);
  10633. } else {
  10634. throw this.unexpected();
  10635. }
  10636. }
  10637. case 43:
  10638. {
  10639. const lookaheadCh = this.input.codePointAt(this.nextTokenStart());
  10640. if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) {
  10641. this.expectOnePlugin(["jsx", "flow", "typescript"]);
  10642. break;
  10643. } else {
  10644. throw this.unexpected();
  10645. }
  10646. }
  10647. default:
  10648. if (tokenIsIdentifier(type)) {
  10649. if (this.isContextual(117) && this.lookaheadCharCode() === 123 && !this.hasFollowingLineBreak()) {
  10650. return this.parseModuleExpression();
  10651. }
  10652. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  10653. const containsEsc = this.state.containsEsc;
  10654. const id = this.parseIdentifier();
  10655. if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) {
  10656. const {
  10657. type
  10658. } = this.state;
  10659. if (type === 62) {
  10660. this.resetPreviousNodeTrailingComments(id);
  10661. this.next();
  10662. return this.parseFunction(this.startNodeAtNode(id), undefined, true);
  10663. } else if (tokenIsIdentifier(type)) {
  10664. if (this.lookaheadCharCode() === 61) {
  10665. return this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(id));
  10666. } else {
  10667. return id;
  10668. }
  10669. } else if (type === 84) {
  10670. this.resetPreviousNodeTrailingComments(id);
  10671. return this.parseDo(this.startNodeAtNode(id), true);
  10672. }
  10673. }
  10674. if (canBeArrow && this.match(19) && !this.canInsertSemicolon()) {
  10675. this.next();
  10676. return this.parseArrowExpression(this.startNodeAtNode(id), [id], false);
  10677. }
  10678. return id;
  10679. } else {
  10680. throw this.unexpected();
  10681. }
  10682. }
  10683. }
  10684. parseTopicReferenceThenEqualsSign(topicTokenType, topicTokenValue) {
  10685. const pipeProposal = this.getPluginOption("pipelineOperator", "proposal");
  10686. if (pipeProposal) {
  10687. this.state.type = topicTokenType;
  10688. this.state.value = topicTokenValue;
  10689. this.state.pos--;
  10690. this.state.end--;
  10691. this.state.endLoc.column--;
  10692. return this.parseTopicReference(pipeProposal);
  10693. } else {
  10694. throw this.unexpected();
  10695. }
  10696. }
  10697. parseTopicReference(pipeProposal) {
  10698. const node = this.startNode();
  10699. const start = this.state.start;
  10700. const tokenType = this.state.type;
  10701. this.next();
  10702. return this.finishTopicReference(node, start, pipeProposal, tokenType);
  10703. }
  10704. finishTopicReference(node, start, pipeProposal, tokenType) {
  10705. if (this.testTopicReferenceConfiguration(pipeProposal, start, tokenType)) {
  10706. let nodeType;
  10707. if (pipeProposal === "smart") {
  10708. nodeType = "PipelinePrimaryTopicReference";
  10709. } else {
  10710. nodeType = "TopicReference";
  10711. }
  10712. if (!this.topicReferenceIsAllowedInCurrentContext()) {
  10713. if (pipeProposal === "smart") {
  10714. this.raise(start, ErrorMessages.PrimaryTopicNotAllowed);
  10715. } else {
  10716. this.raise(start, ErrorMessages.PipeTopicUnbound);
  10717. }
  10718. }
  10719. this.registerTopicReference();
  10720. return this.finishNode(node, nodeType);
  10721. } else {
  10722. throw this.raise(start, ErrorMessages.PipeTopicUnconfiguredToken, tokenLabelName(tokenType));
  10723. }
  10724. }
  10725. testTopicReferenceConfiguration(pipeProposal, start, tokenType) {
  10726. switch (pipeProposal) {
  10727. case "hack":
  10728. {
  10729. const pluginTopicToken = this.getPluginOption("pipelineOperator", "topicToken");
  10730. return tokenLabelName(tokenType) === pluginTopicToken;
  10731. }
  10732. case "smart":
  10733. return tokenType === 25;
  10734. default:
  10735. throw this.raise(start, ErrorMessages.PipeTopicRequiresHackPipes);
  10736. }
  10737. }
  10738. parseAsyncArrowUnaryFunction(node) {
  10739. this.prodParam.enter(functionFlags(true, this.prodParam.hasYield));
  10740. const params = [this.parseIdentifier()];
  10741. this.prodParam.exit();
  10742. if (this.hasPrecedingLineBreak()) {
  10743. this.raise(this.state.pos, ErrorMessages.LineTerminatorBeforeArrow);
  10744. }
  10745. this.expect(19);
  10746. this.parseArrowExpression(node, params, true);
  10747. return node;
  10748. }
  10749. parseDo(node, isAsync) {
  10750. this.expectPlugin("doExpressions");
  10751. if (isAsync) {
  10752. this.expectPlugin("asyncDoExpressions");
  10753. }
  10754. node.async = isAsync;
  10755. this.next();
  10756. const oldLabels = this.state.labels;
  10757. this.state.labels = [];
  10758. if (isAsync) {
  10759. this.prodParam.enter(PARAM_AWAIT);
  10760. node.body = this.parseBlock();
  10761. this.prodParam.exit();
  10762. } else {
  10763. node.body = this.parseBlock();
  10764. }
  10765. this.state.labels = oldLabels;
  10766. return this.finishNode(node, "DoExpression");
  10767. }
  10768. parseSuper() {
  10769. const node = this.startNode();
  10770. this.next();
  10771. if (this.match(10) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) {
  10772. this.raise(node.start, ErrorMessages.SuperNotAllowed);
  10773. } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) {
  10774. this.raise(node.start, ErrorMessages.UnexpectedSuper);
  10775. }
  10776. if (!this.match(10) && !this.match(0) && !this.match(16)) {
  10777. this.raise(node.start, ErrorMessages.UnsupportedSuper);
  10778. }
  10779. return this.finishNode(node, "Super");
  10780. }
  10781. parsePrivateName() {
  10782. const node = this.startNode();
  10783. const id = this.startNodeAt(this.state.start + 1, new Position(this.state.curLine, this.state.start + 1 - this.state.lineStart));
  10784. const name = this.state.value;
  10785. this.next();
  10786. node.id = this.createIdentifier(id, name);
  10787. return this.finishNode(node, "PrivateName");
  10788. }
  10789. parseFunctionOrFunctionSent() {
  10790. const node = this.startNode();
  10791. this.next();
  10792. if (this.prodParam.hasYield && this.match(16)) {
  10793. const meta = this.createIdentifier(this.startNodeAtNode(node), "function");
  10794. this.next();
  10795. if (this.match(96)) {
  10796. this.expectPlugin("functionSent");
  10797. } else if (!this.hasPlugin("functionSent")) {
  10798. this.unexpected();
  10799. }
  10800. return this.parseMetaProperty(node, meta, "sent");
  10801. }
  10802. return this.parseFunction(node);
  10803. }
  10804. parseMetaProperty(node, meta, propertyName) {
  10805. node.meta = meta;
  10806. const containsEsc = this.state.containsEsc;
  10807. node.property = this.parseIdentifier(true);
  10808. if (node.property.name !== propertyName || containsEsc) {
  10809. this.raise(node.property.start, ErrorMessages.UnsupportedMetaProperty, meta.name, propertyName);
  10810. }
  10811. return this.finishNode(node, "MetaProperty");
  10812. }
  10813. parseImportMetaProperty(node) {
  10814. const id = this.createIdentifier(this.startNodeAtNode(node), "import");
  10815. this.next();
  10816. if (this.isContextual(94)) {
  10817. if (!this.inModule) {
  10818. this.raise(id.start, SourceTypeModuleErrorMessages.ImportMetaOutsideModule);
  10819. }
  10820. this.sawUnambiguousESM = true;
  10821. }
  10822. return this.parseMetaProperty(node, id, "meta");
  10823. }
  10824. parseLiteralAtNode(value, type, node) {
  10825. this.addExtra(node, "rawValue", value);
  10826. this.addExtra(node, "raw", this.input.slice(node.start, this.state.end));
  10827. node.value = value;
  10828. this.next();
  10829. return this.finishNode(node, type);
  10830. }
  10831. parseLiteral(value, type) {
  10832. const node = this.startNode();
  10833. return this.parseLiteralAtNode(value, type, node);
  10834. }
  10835. parseStringLiteral(value) {
  10836. return this.parseLiteral(value, "StringLiteral");
  10837. }
  10838. parseNumericLiteral(value) {
  10839. return this.parseLiteral(value, "NumericLiteral");
  10840. }
  10841. parseBigIntLiteral(value) {
  10842. return this.parseLiteral(value, "BigIntLiteral");
  10843. }
  10844. parseDecimalLiteral(value) {
  10845. return this.parseLiteral(value, "DecimalLiteral");
  10846. }
  10847. parseRegExpLiteral(value) {
  10848. const node = this.parseLiteral(value.value, "RegExpLiteral");
  10849. node.pattern = value.pattern;
  10850. node.flags = value.flags;
  10851. return node;
  10852. }
  10853. parseBooleanLiteral(value) {
  10854. const node = this.startNode();
  10855. node.value = value;
  10856. this.next();
  10857. return this.finishNode(node, "BooleanLiteral");
  10858. }
  10859. parseNullLiteral() {
  10860. const node = this.startNode();
  10861. this.next();
  10862. return this.finishNode(node, "NullLiteral");
  10863. }
  10864. parseParenAndDistinguishExpression(canBeArrow) {
  10865. const startPos = this.state.start;
  10866. const startLoc = this.state.startLoc;
  10867. let val;
  10868. this.next();
  10869. this.expressionScope.enter(newArrowHeadScope());
  10870. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  10871. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  10872. this.state.maybeInArrowParameters = true;
  10873. this.state.inFSharpPipelineDirectBody = false;
  10874. const innerStartPos = this.state.start;
  10875. const innerStartLoc = this.state.startLoc;
  10876. const exprList = [];
  10877. const refExpressionErrors = new ExpressionErrors();
  10878. let first = true;
  10879. let spreadStart;
  10880. let optionalCommaStart;
  10881. while (!this.match(11)) {
  10882. if (first) {
  10883. first = false;
  10884. } else {
  10885. this.expect(12, refExpressionErrors.optionalParameters === -1 ? null : refExpressionErrors.optionalParameters);
  10886. if (this.match(11)) {
  10887. optionalCommaStart = this.state.start;
  10888. break;
  10889. }
  10890. }
  10891. if (this.match(21)) {
  10892. const spreadNodeStartPos = this.state.start;
  10893. const spreadNodeStartLoc = this.state.startLoc;
  10894. spreadStart = this.state.start;
  10895. exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartPos, spreadNodeStartLoc));
  10896. this.checkCommaAfterRest(41);
  10897. break;
  10898. } else {
  10899. exprList.push(this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem));
  10900. }
  10901. }
  10902. const innerEndPos = this.state.lastTokEnd;
  10903. const innerEndLoc = this.state.lastTokEndLoc;
  10904. this.expect(11);
  10905. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  10906. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  10907. let arrowNode = this.startNodeAt(startPos, startLoc);
  10908. if (canBeArrow && this.shouldParseArrow(exprList) && (arrowNode = this.parseArrow(arrowNode))) {
  10909. this.expressionScope.validateAsPattern();
  10910. this.expressionScope.exit();
  10911. this.parseArrowExpression(arrowNode, exprList, false);
  10912. return arrowNode;
  10913. }
  10914. this.expressionScope.exit();
  10915. if (!exprList.length) {
  10916. this.unexpected(this.state.lastTokStart);
  10917. }
  10918. if (optionalCommaStart) this.unexpected(optionalCommaStart);
  10919. if (spreadStart) this.unexpected(spreadStart);
  10920. this.checkExpressionErrors(refExpressionErrors, true);
  10921. this.toReferencedListDeep(exprList, true);
  10922. if (exprList.length > 1) {
  10923. val = this.startNodeAt(innerStartPos, innerStartLoc);
  10924. val.expressions = exprList;
  10925. this.finishNode(val, "SequenceExpression");
  10926. this.resetEndLocation(val, innerEndPos, innerEndLoc);
  10927. } else {
  10928. val = exprList[0];
  10929. }
  10930. if (!this.options.createParenthesizedExpressions) {
  10931. this.addExtra(val, "parenthesized", true);
  10932. this.addExtra(val, "parenStart", startPos);
  10933. this.takeSurroundingComments(val, startPos, this.state.lastTokEnd);
  10934. return val;
  10935. }
  10936. const parenExpression = this.startNodeAt(startPos, startLoc);
  10937. parenExpression.expression = val;
  10938. this.finishNode(parenExpression, "ParenthesizedExpression");
  10939. return parenExpression;
  10940. }
  10941. shouldParseArrow(params) {
  10942. return !this.canInsertSemicolon();
  10943. }
  10944. parseArrow(node) {
  10945. if (this.eat(19)) {
  10946. return node;
  10947. }
  10948. }
  10949. parseParenItem(node, startPos, startLoc) {
  10950. return node;
  10951. }
  10952. parseNewOrNewTarget() {
  10953. const node = this.startNode();
  10954. this.next();
  10955. if (this.match(16)) {
  10956. const meta = this.createIdentifier(this.startNodeAtNode(node), "new");
  10957. this.next();
  10958. const metaProp = this.parseMetaProperty(node, meta, "target");
  10959. if (!this.scope.inNonArrowFunction && !this.scope.inClass) {
  10960. this.raise(metaProp.start, ErrorMessages.UnexpectedNewTarget);
  10961. }
  10962. return metaProp;
  10963. }
  10964. return this.parseNew(node);
  10965. }
  10966. parseNew(node) {
  10967. node.callee = this.parseNoCallExpr();
  10968. if (node.callee.type === "Import") {
  10969. this.raise(node.callee.start, ErrorMessages.ImportCallNotNewExpression);
  10970. } else if (this.isOptionalChain(node.callee)) {
  10971. this.raise(this.state.lastTokEnd, ErrorMessages.OptionalChainingNoNew);
  10972. } else if (this.eat(18)) {
  10973. this.raise(this.state.start, ErrorMessages.OptionalChainingNoNew);
  10974. }
  10975. this.parseNewArguments(node);
  10976. return this.finishNode(node, "NewExpression");
  10977. }
  10978. parseNewArguments(node) {
  10979. if (this.eat(10)) {
  10980. const args = this.parseExprList(11);
  10981. this.toReferencedList(args);
  10982. node.arguments = args;
  10983. } else {
  10984. node.arguments = [];
  10985. }
  10986. }
  10987. parseTemplateElement(isTagged) {
  10988. const elem = this.startNode();
  10989. if (this.state.value === null) {
  10990. if (!isTagged) {
  10991. this.raise(this.state.start + 1, ErrorMessages.InvalidEscapeSequenceTemplate);
  10992. }
  10993. }
  10994. elem.value = {
  10995. raw: this.input.slice(this.state.start, this.state.end).replace(/\r\n?/g, "\n"),
  10996. cooked: this.state.value
  10997. };
  10998. this.next();
  10999. elem.tail = this.match(22);
  11000. return this.finishNode(elem, "TemplateElement");
  11001. }
  11002. parseTemplate(isTagged) {
  11003. const node = this.startNode();
  11004. this.next();
  11005. node.expressions = [];
  11006. let curElt = this.parseTemplateElement(isTagged);
  11007. node.quasis = [curElt];
  11008. while (!curElt.tail) {
  11009. this.expect(23);
  11010. node.expressions.push(this.parseTemplateSubstitution());
  11011. this.expect(8);
  11012. node.quasis.push(curElt = this.parseTemplateElement(isTagged));
  11013. }
  11014. this.next();
  11015. return this.finishNode(node, "TemplateLiteral");
  11016. }
  11017. parseTemplateSubstitution() {
  11018. return this.parseExpression();
  11019. }
  11020. parseObjectLike(close, isPattern, isRecord, refExpressionErrors) {
  11021. if (isRecord) {
  11022. this.expectPlugin("recordAndTuple");
  11023. }
  11024. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  11025. this.state.inFSharpPipelineDirectBody = false;
  11026. const propHash = Object.create(null);
  11027. let first = true;
  11028. const node = this.startNode();
  11029. node.properties = [];
  11030. this.next();
  11031. while (!this.match(close)) {
  11032. if (first) {
  11033. first = false;
  11034. } else {
  11035. this.expect(12);
  11036. if (this.match(close)) {
  11037. this.addExtra(node, "trailingComma", this.state.lastTokStart);
  11038. break;
  11039. }
  11040. }
  11041. let prop;
  11042. if (isPattern) {
  11043. prop = this.parseBindingProperty();
  11044. } else {
  11045. prop = this.parsePropertyDefinition(refExpressionErrors);
  11046. this.checkProto(prop, isRecord, propHash, refExpressionErrors);
  11047. }
  11048. if (isRecord && !this.isObjectProperty(prop) && prop.type !== "SpreadElement") {
  11049. this.raise(prop.start, ErrorMessages.InvalidRecordProperty);
  11050. }
  11051. if (prop.shorthand) {
  11052. this.addExtra(prop, "shorthand", true);
  11053. }
  11054. node.properties.push(prop);
  11055. }
  11056. this.next();
  11057. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  11058. let type = "ObjectExpression";
  11059. if (isPattern) {
  11060. type = "ObjectPattern";
  11061. } else if (isRecord) {
  11062. type = "RecordExpression";
  11063. }
  11064. return this.finishNode(node, type);
  11065. }
  11066. maybeAsyncOrAccessorProp(prop) {
  11067. return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(0) || this.match(49));
  11068. }
  11069. parsePropertyDefinition(refExpressionErrors) {
  11070. let decorators = [];
  11071. if (this.match(24)) {
  11072. if (this.hasPlugin("decorators")) {
  11073. this.raise(this.state.start, ErrorMessages.UnsupportedPropertyDecorator);
  11074. }
  11075. while (this.match(24)) {
  11076. decorators.push(this.parseDecorator());
  11077. }
  11078. }
  11079. const prop = this.startNode();
  11080. let isAsync = false;
  11081. let isAccessor = false;
  11082. let startPos;
  11083. let startLoc;
  11084. if (this.match(21)) {
  11085. if (decorators.length) this.unexpected();
  11086. return this.parseSpread();
  11087. }
  11088. if (decorators.length) {
  11089. prop.decorators = decorators;
  11090. decorators = [];
  11091. }
  11092. prop.method = false;
  11093. if (refExpressionErrors) {
  11094. startPos = this.state.start;
  11095. startLoc = this.state.startLoc;
  11096. }
  11097. let isGenerator = this.eat(49);
  11098. this.parsePropertyNamePrefixOperator(prop);
  11099. const containsEsc = this.state.containsEsc;
  11100. const key = this.parsePropertyName(prop);
  11101. if (!isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) {
  11102. const keyName = key.name;
  11103. if (keyName === "async" && !this.hasPrecedingLineBreak()) {
  11104. isAsync = true;
  11105. this.resetPreviousNodeTrailingComments(key);
  11106. isGenerator = this.eat(49);
  11107. this.parsePropertyName(prop);
  11108. }
  11109. if (keyName === "get" || keyName === "set") {
  11110. isAccessor = true;
  11111. this.resetPreviousNodeTrailingComments(key);
  11112. prop.kind = keyName;
  11113. if (this.match(49)) {
  11114. isGenerator = true;
  11115. this.raise(this.state.pos, ErrorMessages.AccessorIsGenerator, keyName);
  11116. this.next();
  11117. }
  11118. this.parsePropertyName(prop);
  11119. }
  11120. }
  11121. this.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, false, isAccessor, refExpressionErrors);
  11122. return prop;
  11123. }
  11124. getGetterSetterExpectedParamCount(method) {
  11125. return method.kind === "get" ? 0 : 1;
  11126. }
  11127. getObjectOrClassMethodParams(method) {
  11128. return method.params;
  11129. }
  11130. checkGetterSetterParams(method) {
  11131. var _params;
  11132. const paramCount = this.getGetterSetterExpectedParamCount(method);
  11133. const params = this.getObjectOrClassMethodParams(method);
  11134. const start = method.start;
  11135. if (params.length !== paramCount) {
  11136. if (method.kind === "get") {
  11137. this.raise(start, ErrorMessages.BadGetterArity);
  11138. } else {
  11139. this.raise(start, ErrorMessages.BadSetterArity);
  11140. }
  11141. }
  11142. if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") {
  11143. this.raise(start, ErrorMessages.BadSetterRestParameter);
  11144. }
  11145. }
  11146. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  11147. if (isAccessor) {
  11148. this.parseMethod(prop, isGenerator, false, false, false, "ObjectMethod");
  11149. this.checkGetterSetterParams(prop);
  11150. return prop;
  11151. }
  11152. if (isAsync || isGenerator || this.match(10)) {
  11153. if (isPattern) this.unexpected();
  11154. prop.kind = "method";
  11155. prop.method = true;
  11156. return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod");
  11157. }
  11158. }
  11159. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  11160. prop.shorthand = false;
  11161. if (this.eat(14)) {
  11162. prop.value = isPattern ? this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssignAllowIn(refExpressionErrors);
  11163. return this.finishNode(prop, "ObjectProperty");
  11164. }
  11165. if (!prop.computed && prop.key.type === "Identifier") {
  11166. this.checkReservedWord(prop.key.name, prop.key.start, true, false);
  11167. if (isPattern) {
  11168. prop.value = this.parseMaybeDefault(startPos, startLoc, cloneIdentifier(prop.key));
  11169. } else if (this.match(27) && refExpressionErrors) {
  11170. if (refExpressionErrors.shorthandAssign === -1) {
  11171. refExpressionErrors.shorthandAssign = this.state.start;
  11172. }
  11173. prop.value = this.parseMaybeDefault(startPos, startLoc, cloneIdentifier(prop.key));
  11174. } else {
  11175. prop.value = cloneIdentifier(prop.key);
  11176. }
  11177. prop.shorthand = true;
  11178. return this.finishNode(prop, "ObjectProperty");
  11179. }
  11180. }
  11181. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  11182. const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) || this.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  11183. if (!node) this.unexpected();
  11184. return node;
  11185. }
  11186. parsePropertyName(prop) {
  11187. if (this.eat(0)) {
  11188. prop.computed = true;
  11189. prop.key = this.parseMaybeAssignAllowIn();
  11190. this.expect(3);
  11191. } else {
  11192. const {
  11193. type,
  11194. value
  11195. } = this.state;
  11196. let key;
  11197. if (tokenIsKeywordOrIdentifier(type)) {
  11198. key = this.parseIdentifier(true);
  11199. } else {
  11200. switch (type) {
  11201. case 124:
  11202. key = this.parseNumericLiteral(value);
  11203. break;
  11204. case 123:
  11205. key = this.parseStringLiteral(value);
  11206. break;
  11207. case 125:
  11208. key = this.parseBigIntLiteral(value);
  11209. break;
  11210. case 126:
  11211. key = this.parseDecimalLiteral(value);
  11212. break;
  11213. case 128:
  11214. {
  11215. const privateKeyPos = this.state.start + 1;
  11216. this.raise(privateKeyPos, ErrorMessages.UnexpectedPrivateField);
  11217. key = this.parsePrivateName();
  11218. break;
  11219. }
  11220. default:
  11221. throw this.unexpected();
  11222. }
  11223. }
  11224. prop.key = key;
  11225. if (type !== 128) {
  11226. prop.computed = false;
  11227. }
  11228. }
  11229. return prop.key;
  11230. }
  11231. initFunction(node, isAsync) {
  11232. node.id = null;
  11233. node.generator = false;
  11234. node.async = !!isAsync;
  11235. }
  11236. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  11237. this.initFunction(node, isAsync);
  11238. node.generator = !!isGenerator;
  11239. const allowModifiers = isConstructor;
  11240. this.scope.enter(SCOPE_FUNCTION | SCOPE_SUPER | (inClassScope ? SCOPE_CLASS : 0) | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  11241. this.prodParam.enter(functionFlags(isAsync, node.generator));
  11242. this.parseFunctionParams(node, allowModifiers);
  11243. this.parseFunctionBodyAndFinish(node, type, true);
  11244. this.prodParam.exit();
  11245. this.scope.exit();
  11246. return node;
  11247. }
  11248. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  11249. if (isTuple) {
  11250. this.expectPlugin("recordAndTuple");
  11251. }
  11252. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  11253. this.state.inFSharpPipelineDirectBody = false;
  11254. const node = this.startNode();
  11255. this.next();
  11256. node.elements = this.parseExprList(close, !isTuple, refExpressionErrors, node);
  11257. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  11258. return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression");
  11259. }
  11260. parseArrowExpression(node, params, isAsync, trailingCommaPos) {
  11261. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  11262. let flags = functionFlags(isAsync, false);
  11263. if (!this.match(0) && this.prodParam.hasIn) {
  11264. flags |= PARAM_IN;
  11265. }
  11266. this.prodParam.enter(flags);
  11267. this.initFunction(node, isAsync);
  11268. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  11269. if (params) {
  11270. this.state.maybeInArrowParameters = true;
  11271. this.setArrowFunctionParameters(node, params, trailingCommaPos);
  11272. }
  11273. this.state.maybeInArrowParameters = false;
  11274. this.parseFunctionBody(node, true);
  11275. this.prodParam.exit();
  11276. this.scope.exit();
  11277. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  11278. return this.finishNode(node, "ArrowFunctionExpression");
  11279. }
  11280. setArrowFunctionParameters(node, params, trailingCommaPos) {
  11281. node.params = this.toAssignableList(params, trailingCommaPos, false);
  11282. }
  11283. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  11284. this.parseFunctionBody(node, false, isMethod);
  11285. this.finishNode(node, type);
  11286. }
  11287. parseFunctionBody(node, allowExpression, isMethod = false) {
  11288. const isExpression = allowExpression && !this.match(5);
  11289. this.expressionScope.enter(newExpressionScope());
  11290. if (isExpression) {
  11291. node.body = this.parseMaybeAssign();
  11292. this.checkParams(node, false, allowExpression, false);
  11293. } else {
  11294. const oldStrict = this.state.strict;
  11295. const oldLabels = this.state.labels;
  11296. this.state.labels = [];
  11297. this.prodParam.enter(this.prodParam.currentFlags() | PARAM_RETURN);
  11298. node.body = this.parseBlock(true, false, hasStrictModeDirective => {
  11299. const nonSimple = !this.isSimpleParamList(node.params);
  11300. if (hasStrictModeDirective && nonSimple) {
  11301. const errorPos = (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.end : node.start;
  11302. this.raise(errorPos, ErrorMessages.IllegalLanguageModeDirective);
  11303. }
  11304. const strictModeChanged = !oldStrict && this.state.strict;
  11305. this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged);
  11306. if (this.state.strict && node.id) {
  11307. this.checkLVal(node.id, "function name", BIND_OUTSIDE, undefined, undefined, strictModeChanged);
  11308. }
  11309. });
  11310. this.prodParam.exit();
  11311. this.state.labels = oldLabels;
  11312. }
  11313. this.expressionScope.exit();
  11314. }
  11315. isSimpleParamList(params) {
  11316. for (let i = 0, len = params.length; i < len; i++) {
  11317. if (params[i].type !== "Identifier") return false;
  11318. }
  11319. return true;
  11320. }
  11321. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  11322. const checkClashes = new Set();
  11323. for (const param of node.params) {
  11324. this.checkLVal(param, "function parameter list", BIND_VAR, allowDuplicates ? null : checkClashes, undefined, strictModeChanged);
  11325. }
  11326. }
  11327. parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) {
  11328. const elts = [];
  11329. let first = true;
  11330. while (!this.eat(close)) {
  11331. if (first) {
  11332. first = false;
  11333. } else {
  11334. this.expect(12);
  11335. if (this.match(close)) {
  11336. if (nodeForExtra) {
  11337. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  11338. }
  11339. this.next();
  11340. break;
  11341. }
  11342. }
  11343. elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors));
  11344. }
  11345. return elts;
  11346. }
  11347. parseExprListItem(allowEmpty, refExpressionErrors, allowPlaceholder) {
  11348. let elt;
  11349. if (this.match(12)) {
  11350. if (!allowEmpty) {
  11351. this.raise(this.state.pos, ErrorMessages.UnexpectedToken, ",");
  11352. }
  11353. elt = null;
  11354. } else if (this.match(21)) {
  11355. const spreadNodeStartPos = this.state.start;
  11356. const spreadNodeStartLoc = this.state.startLoc;
  11357. elt = this.parseParenItem(this.parseSpread(refExpressionErrors), spreadNodeStartPos, spreadNodeStartLoc);
  11358. } else if (this.match(17)) {
  11359. this.expectPlugin("partialApplication");
  11360. if (!allowPlaceholder) {
  11361. this.raise(this.state.start, ErrorMessages.UnexpectedArgumentPlaceholder);
  11362. }
  11363. const node = this.startNode();
  11364. this.next();
  11365. elt = this.finishNode(node, "ArgumentPlaceholder");
  11366. } else {
  11367. elt = this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem);
  11368. }
  11369. return elt;
  11370. }
  11371. parseIdentifier(liberal) {
  11372. const node = this.startNode();
  11373. const name = this.parseIdentifierName(node.start, liberal);
  11374. return this.createIdentifier(node, name);
  11375. }
  11376. createIdentifier(node, name) {
  11377. node.name = name;
  11378. node.loc.identifierName = name;
  11379. return this.finishNode(node, "Identifier");
  11380. }
  11381. parseIdentifierName(pos, liberal) {
  11382. let name;
  11383. const {
  11384. start,
  11385. type
  11386. } = this.state;
  11387. if (tokenIsKeywordOrIdentifier(type)) {
  11388. name = this.state.value;
  11389. } else {
  11390. throw this.unexpected();
  11391. }
  11392. const tokenIsKeyword = tokenKeywordOrIdentifierIsKeyword(type);
  11393. if (liberal) {
  11394. if (tokenIsKeyword) {
  11395. this.replaceToken(122);
  11396. }
  11397. } else {
  11398. this.checkReservedWord(name, start, tokenIsKeyword, false);
  11399. }
  11400. this.next();
  11401. return name;
  11402. }
  11403. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  11404. if (word.length > 10) {
  11405. return;
  11406. }
  11407. if (!canBeReservedWord(word)) {
  11408. return;
  11409. }
  11410. if (word === "yield") {
  11411. if (this.prodParam.hasYield) {
  11412. this.raise(startLoc, ErrorMessages.YieldBindingIdentifier);
  11413. return;
  11414. }
  11415. } else if (word === "await") {
  11416. if (this.prodParam.hasAwait) {
  11417. this.raise(startLoc, ErrorMessages.AwaitBindingIdentifier);
  11418. return;
  11419. } else if (this.scope.inStaticBlock) {
  11420. this.raise(startLoc, ErrorMessages.AwaitBindingIdentifierInStaticBlock);
  11421. return;
  11422. } else {
  11423. this.expressionScope.recordAsyncArrowParametersError(startLoc, ErrorMessages.AwaitBindingIdentifier);
  11424. }
  11425. } else if (word === "arguments") {
  11426. if (this.scope.inClassAndNotInNonArrowFunction) {
  11427. this.raise(startLoc, ErrorMessages.ArgumentsInClass);
  11428. return;
  11429. }
  11430. }
  11431. if (checkKeywords && isKeyword(word)) {
  11432. this.raise(startLoc, ErrorMessages.UnexpectedKeyword, word);
  11433. return;
  11434. }
  11435. const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord;
  11436. if (reservedTest(word, this.inModule)) {
  11437. this.raise(startLoc, ErrorMessages.UnexpectedReservedWord, word);
  11438. }
  11439. }
  11440. isAwaitAllowed() {
  11441. if (this.prodParam.hasAwait) return true;
  11442. if (this.options.allowAwaitOutsideFunction && !this.scope.inFunction) {
  11443. return true;
  11444. }
  11445. return false;
  11446. }
  11447. parseAwait(startPos, startLoc) {
  11448. const node = this.startNodeAt(startPos, startLoc);
  11449. this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.AwaitExpressionFormalParameter);
  11450. if (this.eat(49)) {
  11451. this.raise(node.start, ErrorMessages.ObsoleteAwaitStar);
  11452. }
  11453. if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) {
  11454. if (this.isAmbiguousAwait()) {
  11455. this.ambiguousScriptDifferentAst = true;
  11456. } else {
  11457. this.sawUnambiguousESM = true;
  11458. }
  11459. }
  11460. if (!this.state.soloAwait) {
  11461. node.argument = this.parseMaybeUnary(null, true);
  11462. }
  11463. return this.finishNode(node, "AwaitExpression");
  11464. }
  11465. isAmbiguousAwait() {
  11466. 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);
  11467. }
  11468. parseYield() {
  11469. const node = this.startNode();
  11470. this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.YieldInParameter);
  11471. this.next();
  11472. let delegating = false;
  11473. let argument = null;
  11474. if (!this.hasPrecedingLineBreak()) {
  11475. delegating = this.eat(49);
  11476. switch (this.state.type) {
  11477. case 13:
  11478. case 129:
  11479. case 8:
  11480. case 11:
  11481. case 3:
  11482. case 9:
  11483. case 14:
  11484. case 12:
  11485. if (!delegating) break;
  11486. default:
  11487. argument = this.parseMaybeAssign();
  11488. }
  11489. }
  11490. node.delegate = delegating;
  11491. node.argument = argument;
  11492. return this.finishNode(node, "YieldExpression");
  11493. }
  11494. checkPipelineAtInfixOperator(left, leftStartPos) {
  11495. if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
  11496. if (left.type === "SequenceExpression") {
  11497. this.raise(leftStartPos, ErrorMessages.PipelineHeadSequenceExpression);
  11498. }
  11499. }
  11500. }
  11501. checkHackPipeBodyEarlyErrors(startPos) {
  11502. if (!this.topicReferenceWasUsedInCurrentContext()) {
  11503. this.raise(startPos, ErrorMessages.PipeTopicUnused);
  11504. }
  11505. }
  11506. parseSmartPipelineBodyInStyle(childExpr, startPos, startLoc) {
  11507. const bodyNode = this.startNodeAt(startPos, startLoc);
  11508. if (this.isSimpleReference(childExpr)) {
  11509. bodyNode.callee = childExpr;
  11510. return this.finishNode(bodyNode, "PipelineBareFunction");
  11511. } else {
  11512. this.checkSmartPipeTopicBodyEarlyErrors(startPos);
  11513. bodyNode.expression = childExpr;
  11514. return this.finishNode(bodyNode, "PipelineTopicExpression");
  11515. }
  11516. }
  11517. isSimpleReference(expression) {
  11518. switch (expression.type) {
  11519. case "MemberExpression":
  11520. return !expression.computed && this.isSimpleReference(expression.object);
  11521. case "Identifier":
  11522. return true;
  11523. default:
  11524. return false;
  11525. }
  11526. }
  11527. checkSmartPipeTopicBodyEarlyErrors(startPos) {
  11528. if (this.match(19)) {
  11529. throw this.raise(this.state.start, ErrorMessages.PipelineBodyNoArrow);
  11530. } else if (!this.topicReferenceWasUsedInCurrentContext()) {
  11531. this.raise(startPos, ErrorMessages.PipelineTopicUnused);
  11532. }
  11533. }
  11534. withTopicBindingContext(callback) {
  11535. const outerContextTopicState = this.state.topicContext;
  11536. this.state.topicContext = {
  11537. maxNumOfResolvableTopics: 1,
  11538. maxTopicIndex: null
  11539. };
  11540. try {
  11541. return callback();
  11542. } finally {
  11543. this.state.topicContext = outerContextTopicState;
  11544. }
  11545. }
  11546. withSmartMixTopicForbiddingContext(callback) {
  11547. const proposal = this.getPluginOption("pipelineOperator", "proposal");
  11548. if (proposal === "smart") {
  11549. const outerContextTopicState = this.state.topicContext;
  11550. this.state.topicContext = {
  11551. maxNumOfResolvableTopics: 0,
  11552. maxTopicIndex: null
  11553. };
  11554. try {
  11555. return callback();
  11556. } finally {
  11557. this.state.topicContext = outerContextTopicState;
  11558. }
  11559. } else {
  11560. return callback();
  11561. }
  11562. }
  11563. withSoloAwaitPermittingContext(callback) {
  11564. const outerContextSoloAwaitState = this.state.soloAwait;
  11565. this.state.soloAwait = true;
  11566. try {
  11567. return callback();
  11568. } finally {
  11569. this.state.soloAwait = outerContextSoloAwaitState;
  11570. }
  11571. }
  11572. allowInAnd(callback) {
  11573. const flags = this.prodParam.currentFlags();
  11574. const prodParamToSet = PARAM_IN & ~flags;
  11575. if (prodParamToSet) {
  11576. this.prodParam.enter(flags | PARAM_IN);
  11577. try {
  11578. return callback();
  11579. } finally {
  11580. this.prodParam.exit();
  11581. }
  11582. }
  11583. return callback();
  11584. }
  11585. disallowInAnd(callback) {
  11586. const flags = this.prodParam.currentFlags();
  11587. const prodParamToClear = PARAM_IN & flags;
  11588. if (prodParamToClear) {
  11589. this.prodParam.enter(flags & ~PARAM_IN);
  11590. try {
  11591. return callback();
  11592. } finally {
  11593. this.prodParam.exit();
  11594. }
  11595. }
  11596. return callback();
  11597. }
  11598. registerTopicReference() {
  11599. this.state.topicContext.maxTopicIndex = 0;
  11600. }
  11601. topicReferenceIsAllowedInCurrentContext() {
  11602. return this.state.topicContext.maxNumOfResolvableTopics >= 1;
  11603. }
  11604. topicReferenceWasUsedInCurrentContext() {
  11605. return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0;
  11606. }
  11607. parseFSharpPipelineBody(prec) {
  11608. const startPos = this.state.start;
  11609. const startLoc = this.state.startLoc;
  11610. this.state.potentialArrowAt = this.state.start;
  11611. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  11612. this.state.inFSharpPipelineDirectBody = true;
  11613. const ret = this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startPos, startLoc, prec);
  11614. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  11615. return ret;
  11616. }
  11617. parseModuleExpression() {
  11618. this.expectPlugin("moduleBlocks");
  11619. const node = this.startNode();
  11620. this.next();
  11621. this.eat(5);
  11622. const revertScopes = this.initializeScopes(true);
  11623. this.enterInitialScopes();
  11624. const program = this.startNode();
  11625. try {
  11626. node.body = this.parseProgram(program, 8, "module");
  11627. } finally {
  11628. revertScopes();
  11629. }
  11630. this.eat(8);
  11631. return this.finishNode(node, "ModuleExpression");
  11632. }
  11633. parsePropertyNamePrefixOperator(prop) {}
  11634. }
  11635. const loopLabel = {
  11636. kind: "loop"
  11637. },
  11638. switchLabel = {
  11639. kind: "switch"
  11640. };
  11641. const FUNC_NO_FLAGS = 0b000,
  11642. FUNC_STATEMENT = 0b001,
  11643. FUNC_HANGING_STATEMENT = 0b010,
  11644. FUNC_NULLABLE_ID = 0b100;
  11645. const loneSurrogate = /[\uD800-\uDFFF]/u;
  11646. const keywordRelationalOperator = /in(?:stanceof)?/y;
  11647. function babel7CompatTokens(tokens) {
  11648. for (let i = 0; i < tokens.length; i++) {
  11649. const token = tokens[i];
  11650. const {
  11651. type
  11652. } = token;
  11653. if (type === 128) {
  11654. {
  11655. const {
  11656. loc,
  11657. start,
  11658. value,
  11659. end
  11660. } = token;
  11661. const hashEndPos = start + 1;
  11662. const hashEndLoc = new Position(loc.start.line, loc.start.column + 1);
  11663. tokens.splice(i, 1, new Token({
  11664. type: getExportedToken(25),
  11665. value: "#",
  11666. start: start,
  11667. end: hashEndPos,
  11668. startLoc: loc.start,
  11669. endLoc: hashEndLoc
  11670. }), new Token({
  11671. type: getExportedToken(122),
  11672. value: value,
  11673. start: hashEndPos,
  11674. end: end,
  11675. startLoc: hashEndLoc,
  11676. endLoc: loc.end
  11677. }));
  11678. i++;
  11679. continue;
  11680. }
  11681. }
  11682. if (typeof type === "number") {
  11683. token.type = getExportedToken(type);
  11684. }
  11685. }
  11686. return tokens;
  11687. }
  11688. class StatementParser extends ExpressionParser {
  11689. parseTopLevel(file, program) {
  11690. file.program = this.parseProgram(program);
  11691. file.comments = this.state.comments;
  11692. if (this.options.tokens) file.tokens = babel7CompatTokens(this.tokens);
  11693. return this.finishNode(file, "File");
  11694. }
  11695. parseProgram(program, end = 129, sourceType = this.options.sourceType) {
  11696. program.sourceType = sourceType;
  11697. program.interpreter = this.parseInterpreterDirective();
  11698. this.parseBlockBody(program, true, true, end);
  11699. if (this.inModule && !this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) {
  11700. for (const [name] of Array.from(this.scope.undefinedExports)) {
  11701. const pos = this.scope.undefinedExports.get(name);
  11702. this.raise(pos, ErrorMessages.ModuleExportUndefined, name);
  11703. }
  11704. }
  11705. return this.finishNode(program, "Program");
  11706. }
  11707. stmtToDirective(stmt) {
  11708. const directive = stmt;
  11709. directive.type = "Directive";
  11710. directive.value = directive.expression;
  11711. delete directive.expression;
  11712. const directiveLiteral = directive.value;
  11713. const expressionValue = directiveLiteral.value;
  11714. const raw = this.input.slice(directiveLiteral.start, directiveLiteral.end);
  11715. const val = directiveLiteral.value = raw.slice(1, -1);
  11716. this.addExtra(directiveLiteral, "raw", raw);
  11717. this.addExtra(directiveLiteral, "rawValue", val);
  11718. this.addExtra(directiveLiteral, "expressionValue", expressionValue);
  11719. directiveLiteral.type = "DirectiveLiteral";
  11720. return directive;
  11721. }
  11722. parseInterpreterDirective() {
  11723. if (!this.match(26)) {
  11724. return null;
  11725. }
  11726. const node = this.startNode();
  11727. node.value = this.state.value;
  11728. this.next();
  11729. return this.finishNode(node, "InterpreterDirective");
  11730. }
  11731. isLet(context) {
  11732. if (!this.isContextual(93)) {
  11733. return false;
  11734. }
  11735. return this.isLetKeyword(context);
  11736. }
  11737. isLetKeyword(context) {
  11738. const next = this.nextTokenStart();
  11739. const nextCh = this.codePointAtPos(next);
  11740. if (nextCh === 92 || nextCh === 91) {
  11741. return true;
  11742. }
  11743. if (context) return false;
  11744. if (nextCh === 123) return true;
  11745. if (isIdentifierStart(nextCh)) {
  11746. keywordRelationalOperator.lastIndex = next;
  11747. if (keywordRelationalOperator.test(this.input)) {
  11748. const endCh = this.codePointAtPos(keywordRelationalOperator.lastIndex);
  11749. if (!isIdentifierChar(endCh) && endCh !== 92) {
  11750. return false;
  11751. }
  11752. }
  11753. return true;
  11754. }
  11755. return false;
  11756. }
  11757. parseStatement(context, topLevel) {
  11758. if (this.match(24)) {
  11759. this.parseDecorators(true);
  11760. }
  11761. return this.parseStatementContent(context, topLevel);
  11762. }
  11763. parseStatementContent(context, topLevel) {
  11764. let starttype = this.state.type;
  11765. const node = this.startNode();
  11766. let kind;
  11767. if (this.isLet(context)) {
  11768. starttype = 68;
  11769. kind = "let";
  11770. }
  11771. switch (starttype) {
  11772. case 54:
  11773. return this.parseBreakContinueStatement(node, true);
  11774. case 57:
  11775. return this.parseBreakContinueStatement(node, false);
  11776. case 58:
  11777. return this.parseDebuggerStatement(node);
  11778. case 84:
  11779. return this.parseDoStatement(node);
  11780. case 85:
  11781. return this.parseForStatement(node);
  11782. case 62:
  11783. if (this.lookaheadCharCode() === 46) break;
  11784. if (context) {
  11785. if (this.state.strict) {
  11786. this.raise(this.state.start, ErrorMessages.StrictFunction);
  11787. } else if (context !== "if" && context !== "label") {
  11788. this.raise(this.state.start, ErrorMessages.SloppyFunction);
  11789. }
  11790. }
  11791. return this.parseFunctionStatement(node, false, !context);
  11792. case 74:
  11793. if (context) this.unexpected();
  11794. return this.parseClass(node, true);
  11795. case 63:
  11796. return this.parseIfStatement(node);
  11797. case 64:
  11798. return this.parseReturnStatement(node);
  11799. case 65:
  11800. return this.parseSwitchStatement(node);
  11801. case 66:
  11802. return this.parseThrowStatement(node);
  11803. case 67:
  11804. return this.parseTryStatement(node);
  11805. case 69:
  11806. case 68:
  11807. kind = kind || this.state.value;
  11808. if (context && kind !== "var") {
  11809. this.raise(this.state.start, ErrorMessages.UnexpectedLexicalDeclaration);
  11810. }
  11811. return this.parseVarStatement(node, kind);
  11812. case 86:
  11813. return this.parseWhileStatement(node);
  11814. case 70:
  11815. return this.parseWithStatement(node);
  11816. case 5:
  11817. return this.parseBlock();
  11818. case 13:
  11819. return this.parseEmptyStatement(node);
  11820. case 77:
  11821. {
  11822. const nextTokenCharCode = this.lookaheadCharCode();
  11823. if (nextTokenCharCode === 40 || nextTokenCharCode === 46) {
  11824. break;
  11825. }
  11826. }
  11827. case 76:
  11828. {
  11829. if (!this.options.allowImportExportEverywhere && !topLevel) {
  11830. this.raise(this.state.start, ErrorMessages.UnexpectedImportExport);
  11831. }
  11832. this.next();
  11833. let result;
  11834. if (starttype === 77) {
  11835. result = this.parseImport(node);
  11836. if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) {
  11837. this.sawUnambiguousESM = true;
  11838. }
  11839. } else {
  11840. result = this.parseExport(node);
  11841. if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") {
  11842. this.sawUnambiguousESM = true;
  11843. }
  11844. }
  11845. this.assertModuleNodeAllowed(node);
  11846. return result;
  11847. }
  11848. default:
  11849. {
  11850. if (this.isAsyncFunction()) {
  11851. if (context) {
  11852. this.raise(this.state.start, ErrorMessages.AsyncFunctionInSingleStatementContext);
  11853. }
  11854. this.next();
  11855. return this.parseFunctionStatement(node, true, !context);
  11856. }
  11857. }
  11858. }
  11859. const maybeName = this.state.value;
  11860. const expr = this.parseExpression();
  11861. if (tokenIsIdentifier(starttype) && expr.type === "Identifier" && this.eat(14)) {
  11862. return this.parseLabeledStatement(node, maybeName, expr, context);
  11863. } else {
  11864. return this.parseExpressionStatement(node, expr);
  11865. }
  11866. }
  11867. assertModuleNodeAllowed(node) {
  11868. if (!this.options.allowImportExportEverywhere && !this.inModule) {
  11869. this.raise(node.start, SourceTypeModuleErrorMessages.ImportOutsideModule);
  11870. }
  11871. }
  11872. takeDecorators(node) {
  11873. const decorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  11874. if (decorators.length) {
  11875. node.decorators = decorators;
  11876. this.resetStartLocationFromNode(node, decorators[0]);
  11877. this.state.decoratorStack[this.state.decoratorStack.length - 1] = [];
  11878. }
  11879. }
  11880. canHaveLeadingDecorator() {
  11881. return this.match(74);
  11882. }
  11883. parseDecorators(allowExport) {
  11884. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  11885. while (this.match(24)) {
  11886. const decorator = this.parseDecorator();
  11887. currentContextDecorators.push(decorator);
  11888. }
  11889. if (this.match(76)) {
  11890. if (!allowExport) {
  11891. this.unexpected();
  11892. }
  11893. if (this.hasPlugin("decorators") && !this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  11894. this.raise(this.state.start, ErrorMessages.DecoratorExportClass);
  11895. }
  11896. } else if (!this.canHaveLeadingDecorator()) {
  11897. throw this.raise(this.state.start, ErrorMessages.UnexpectedLeadingDecorator);
  11898. }
  11899. }
  11900. parseDecorator() {
  11901. this.expectOnePlugin(["decorators-legacy", "decorators"]);
  11902. const node = this.startNode();
  11903. this.next();
  11904. if (this.hasPlugin("decorators")) {
  11905. this.state.decoratorStack.push([]);
  11906. const startPos = this.state.start;
  11907. const startLoc = this.state.startLoc;
  11908. let expr;
  11909. if (this.eat(10)) {
  11910. expr = this.parseExpression();
  11911. this.expect(11);
  11912. } else {
  11913. expr = this.parseIdentifier(false);
  11914. while (this.eat(16)) {
  11915. const node = this.startNodeAt(startPos, startLoc);
  11916. node.object = expr;
  11917. node.property = this.parseIdentifier(true);
  11918. node.computed = false;
  11919. expr = this.finishNode(node, "MemberExpression");
  11920. }
  11921. }
  11922. node.expression = this.parseMaybeDecoratorArguments(expr);
  11923. this.state.decoratorStack.pop();
  11924. } else {
  11925. node.expression = this.parseExprSubscripts();
  11926. }
  11927. return this.finishNode(node, "Decorator");
  11928. }
  11929. parseMaybeDecoratorArguments(expr) {
  11930. if (this.eat(10)) {
  11931. const node = this.startNodeAtNode(expr);
  11932. node.callee = expr;
  11933. node.arguments = this.parseCallExpressionArguments(11, false);
  11934. this.toReferencedList(node.arguments);
  11935. return this.finishNode(node, "CallExpression");
  11936. }
  11937. return expr;
  11938. }
  11939. parseBreakContinueStatement(node, isBreak) {
  11940. this.next();
  11941. if (this.isLineTerminator()) {
  11942. node.label = null;
  11943. } else {
  11944. node.label = this.parseIdentifier();
  11945. this.semicolon();
  11946. }
  11947. this.verifyBreakContinue(node, isBreak);
  11948. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  11949. }
  11950. verifyBreakContinue(node, isBreak) {
  11951. let i;
  11952. for (i = 0; i < this.state.labels.length; ++i) {
  11953. const lab = this.state.labels[i];
  11954. if (node.label == null || lab.name === node.label.name) {
  11955. if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
  11956. if (node.label && isBreak) break;
  11957. }
  11958. }
  11959. if (i === this.state.labels.length) {
  11960. this.raise(node.start, ErrorMessages.IllegalBreakContinue, isBreak ? "break" : "continue");
  11961. }
  11962. }
  11963. parseDebuggerStatement(node) {
  11964. this.next();
  11965. this.semicolon();
  11966. return this.finishNode(node, "DebuggerStatement");
  11967. }
  11968. parseHeaderExpression() {
  11969. this.expect(10);
  11970. const val = this.parseExpression();
  11971. this.expect(11);
  11972. return val;
  11973. }
  11974. parseDoStatement(node) {
  11975. this.next();
  11976. this.state.labels.push(loopLabel);
  11977. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement("do"));
  11978. this.state.labels.pop();
  11979. this.expect(86);
  11980. node.test = this.parseHeaderExpression();
  11981. this.eat(13);
  11982. return this.finishNode(node, "DoWhileStatement");
  11983. }
  11984. parseForStatement(node) {
  11985. this.next();
  11986. this.state.labels.push(loopLabel);
  11987. let awaitAt = -1;
  11988. if (this.isAwaitAllowed() && this.eatContextual(90)) {
  11989. awaitAt = this.state.lastTokStart;
  11990. }
  11991. this.scope.enter(SCOPE_OTHER);
  11992. this.expect(10);
  11993. if (this.match(13)) {
  11994. if (awaitAt > -1) {
  11995. this.unexpected(awaitAt);
  11996. }
  11997. return this.parseFor(node, null);
  11998. }
  11999. const startsWithLet = this.isContextual(93);
  12000. const isLet = startsWithLet && this.isLetKeyword();
  12001. if (this.match(68) || this.match(69) || isLet) {
  12002. const init = this.startNode();
  12003. const kind = isLet ? "let" : this.state.value;
  12004. this.next();
  12005. this.parseVar(init, true, kind);
  12006. this.finishNode(init, "VariableDeclaration");
  12007. if ((this.match(52) || this.isContextual(95)) && init.declarations.length === 1) {
  12008. return this.parseForIn(node, init, awaitAt);
  12009. }
  12010. if (awaitAt > -1) {
  12011. this.unexpected(awaitAt);
  12012. }
  12013. return this.parseFor(node, init);
  12014. }
  12015. const startsWithAsync = this.isContextual(89);
  12016. const refExpressionErrors = new ExpressionErrors();
  12017. const init = this.parseExpression(true, refExpressionErrors);
  12018. const isForOf = this.isContextual(95);
  12019. if (isForOf) {
  12020. if (startsWithLet) {
  12021. this.raise(init.start, ErrorMessages.ForOfLet);
  12022. } else if (awaitAt === -1 && startsWithAsync && init.type === "Identifier") {
  12023. this.raise(init.start, ErrorMessages.ForOfAsync);
  12024. }
  12025. }
  12026. if (isForOf || this.match(52)) {
  12027. this.toAssignable(init, true);
  12028. const description = isForOf ? "for-of statement" : "for-in statement";
  12029. this.checkLVal(init, description);
  12030. return this.parseForIn(node, init, awaitAt);
  12031. } else {
  12032. this.checkExpressionErrors(refExpressionErrors, true);
  12033. }
  12034. if (awaitAt > -1) {
  12035. this.unexpected(awaitAt);
  12036. }
  12037. return this.parseFor(node, init);
  12038. }
  12039. parseFunctionStatement(node, isAsync, declarationPosition) {
  12040. this.next();
  12041. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), isAsync);
  12042. }
  12043. parseIfStatement(node) {
  12044. this.next();
  12045. node.test = this.parseHeaderExpression();
  12046. node.consequent = this.parseStatement("if");
  12047. node.alternate = this.eat(60) ? this.parseStatement("if") : null;
  12048. return this.finishNode(node, "IfStatement");
  12049. }
  12050. parseReturnStatement(node) {
  12051. if (!this.prodParam.hasReturn && !this.options.allowReturnOutsideFunction) {
  12052. this.raise(this.state.start, ErrorMessages.IllegalReturn);
  12053. }
  12054. this.next();
  12055. if (this.isLineTerminator()) {
  12056. node.argument = null;
  12057. } else {
  12058. node.argument = this.parseExpression();
  12059. this.semicolon();
  12060. }
  12061. return this.finishNode(node, "ReturnStatement");
  12062. }
  12063. parseSwitchStatement(node) {
  12064. this.next();
  12065. node.discriminant = this.parseHeaderExpression();
  12066. const cases = node.cases = [];
  12067. this.expect(5);
  12068. this.state.labels.push(switchLabel);
  12069. this.scope.enter(SCOPE_OTHER);
  12070. let cur;
  12071. for (let sawDefault; !this.match(8);) {
  12072. if (this.match(55) || this.match(59)) {
  12073. const isCase = this.match(55);
  12074. if (cur) this.finishNode(cur, "SwitchCase");
  12075. cases.push(cur = this.startNode());
  12076. cur.consequent = [];
  12077. this.next();
  12078. if (isCase) {
  12079. cur.test = this.parseExpression();
  12080. } else {
  12081. if (sawDefault) {
  12082. this.raise(this.state.lastTokStart, ErrorMessages.MultipleDefaultsInSwitch);
  12083. }
  12084. sawDefault = true;
  12085. cur.test = null;
  12086. }
  12087. this.expect(14);
  12088. } else {
  12089. if (cur) {
  12090. cur.consequent.push(this.parseStatement(null));
  12091. } else {
  12092. this.unexpected();
  12093. }
  12094. }
  12095. }
  12096. this.scope.exit();
  12097. if (cur) this.finishNode(cur, "SwitchCase");
  12098. this.next();
  12099. this.state.labels.pop();
  12100. return this.finishNode(node, "SwitchStatement");
  12101. }
  12102. parseThrowStatement(node) {
  12103. this.next();
  12104. if (this.hasPrecedingLineBreak()) {
  12105. this.raise(this.state.lastTokEnd, ErrorMessages.NewlineAfterThrow);
  12106. }
  12107. node.argument = this.parseExpression();
  12108. this.semicolon();
  12109. return this.finishNode(node, "ThrowStatement");
  12110. }
  12111. parseCatchClauseParam() {
  12112. const param = this.parseBindingAtom();
  12113. const simple = param.type === "Identifier";
  12114. this.scope.enter(simple ? SCOPE_SIMPLE_CATCH : 0);
  12115. this.checkLVal(param, "catch clause", BIND_LEXICAL);
  12116. return param;
  12117. }
  12118. parseTryStatement(node) {
  12119. this.next();
  12120. node.block = this.parseBlock();
  12121. node.handler = null;
  12122. if (this.match(56)) {
  12123. const clause = this.startNode();
  12124. this.next();
  12125. if (this.match(10)) {
  12126. this.expect(10);
  12127. clause.param = this.parseCatchClauseParam();
  12128. this.expect(11);
  12129. } else {
  12130. clause.param = null;
  12131. this.scope.enter(SCOPE_OTHER);
  12132. }
  12133. clause.body = this.withSmartMixTopicForbiddingContext(() => this.parseBlock(false, false));
  12134. this.scope.exit();
  12135. node.handler = this.finishNode(clause, "CatchClause");
  12136. }
  12137. node.finalizer = this.eat(61) ? this.parseBlock() : null;
  12138. if (!node.handler && !node.finalizer) {
  12139. this.raise(node.start, ErrorMessages.NoCatchOrFinally);
  12140. }
  12141. return this.finishNode(node, "TryStatement");
  12142. }
  12143. parseVarStatement(node, kind) {
  12144. this.next();
  12145. this.parseVar(node, false, kind);
  12146. this.semicolon();
  12147. return this.finishNode(node, "VariableDeclaration");
  12148. }
  12149. parseWhileStatement(node) {
  12150. this.next();
  12151. node.test = this.parseHeaderExpression();
  12152. this.state.labels.push(loopLabel);
  12153. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement("while"));
  12154. this.state.labels.pop();
  12155. return this.finishNode(node, "WhileStatement");
  12156. }
  12157. parseWithStatement(node) {
  12158. if (this.state.strict) {
  12159. this.raise(this.state.start, ErrorMessages.StrictWith);
  12160. }
  12161. this.next();
  12162. node.object = this.parseHeaderExpression();
  12163. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement("with"));
  12164. return this.finishNode(node, "WithStatement");
  12165. }
  12166. parseEmptyStatement(node) {
  12167. this.next();
  12168. return this.finishNode(node, "EmptyStatement");
  12169. }
  12170. parseLabeledStatement(node, maybeName, expr, context) {
  12171. for (const label of this.state.labels) {
  12172. if (label.name === maybeName) {
  12173. this.raise(expr.start, ErrorMessages.LabelRedeclaration, maybeName);
  12174. }
  12175. }
  12176. const kind = tokenIsLoop(this.state.type) ? "loop" : this.match(65) ? "switch" : null;
  12177. for (let i = this.state.labels.length - 1; i >= 0; i--) {
  12178. const label = this.state.labels[i];
  12179. if (label.statementStart === node.start) {
  12180. label.statementStart = this.state.start;
  12181. label.kind = kind;
  12182. } else {
  12183. break;
  12184. }
  12185. }
  12186. this.state.labels.push({
  12187. name: maybeName,
  12188. kind: kind,
  12189. statementStart: this.state.start
  12190. });
  12191. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  12192. this.state.labels.pop();
  12193. node.label = expr;
  12194. return this.finishNode(node, "LabeledStatement");
  12195. }
  12196. parseExpressionStatement(node, expr) {
  12197. node.expression = expr;
  12198. this.semicolon();
  12199. return this.finishNode(node, "ExpressionStatement");
  12200. }
  12201. parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) {
  12202. const node = this.startNode();
  12203. if (allowDirectives) {
  12204. this.state.strictErrors.clear();
  12205. }
  12206. this.expect(5);
  12207. if (createNewLexicalScope) {
  12208. this.scope.enter(SCOPE_OTHER);
  12209. }
  12210. this.parseBlockBody(node, allowDirectives, false, 8, afterBlockParse);
  12211. if (createNewLexicalScope) {
  12212. this.scope.exit();
  12213. }
  12214. return this.finishNode(node, "BlockStatement");
  12215. }
  12216. isValidDirective(stmt) {
  12217. return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized;
  12218. }
  12219. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  12220. const body = node.body = [];
  12221. const directives = node.directives = [];
  12222. this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse);
  12223. }
  12224. parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) {
  12225. const oldStrict = this.state.strict;
  12226. let hasStrictModeDirective = false;
  12227. let parsedNonDirective = false;
  12228. while (!this.match(end)) {
  12229. const stmt = this.parseStatement(null, topLevel);
  12230. if (directives && !parsedNonDirective) {
  12231. if (this.isValidDirective(stmt)) {
  12232. const directive = this.stmtToDirective(stmt);
  12233. directives.push(directive);
  12234. if (!hasStrictModeDirective && directive.value.value === "use strict") {
  12235. hasStrictModeDirective = true;
  12236. this.setStrict(true);
  12237. }
  12238. continue;
  12239. }
  12240. parsedNonDirective = true;
  12241. this.state.strictErrors.clear();
  12242. }
  12243. body.push(stmt);
  12244. }
  12245. if (afterBlockParse) {
  12246. afterBlockParse.call(this, hasStrictModeDirective);
  12247. }
  12248. if (!oldStrict) {
  12249. this.setStrict(false);
  12250. }
  12251. this.next();
  12252. }
  12253. parseFor(node, init) {
  12254. node.init = init;
  12255. this.semicolon(false);
  12256. node.test = this.match(13) ? null : this.parseExpression();
  12257. this.semicolon(false);
  12258. node.update = this.match(11) ? null : this.parseExpression();
  12259. this.expect(11);
  12260. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement("for"));
  12261. this.scope.exit();
  12262. this.state.labels.pop();
  12263. return this.finishNode(node, "ForStatement");
  12264. }
  12265. parseForIn(node, init, awaitAt) {
  12266. const isForIn = this.match(52);
  12267. this.next();
  12268. if (isForIn) {
  12269. if (awaitAt > -1) this.unexpected(awaitAt);
  12270. } else {
  12271. node.await = awaitAt > -1;
  12272. }
  12273. if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
  12274. this.raise(init.start, ErrorMessages.ForInOfLoopInitializer, isForIn ? "for-in" : "for-of");
  12275. } else if (init.type === "AssignmentPattern") {
  12276. this.raise(init.start, ErrorMessages.InvalidLhs, "for-loop");
  12277. }
  12278. node.left = init;
  12279. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn();
  12280. this.expect(11);
  12281. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement("for"));
  12282. this.scope.exit();
  12283. this.state.labels.pop();
  12284. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
  12285. }
  12286. parseVar(node, isFor, kind) {
  12287. const declarations = node.declarations = [];
  12288. const isTypescript = this.hasPlugin("typescript");
  12289. node.kind = kind;
  12290. for (;;) {
  12291. const decl = this.startNode();
  12292. this.parseVarId(decl, kind);
  12293. if (this.eat(27)) {
  12294. decl.init = isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn();
  12295. } else {
  12296. if (kind === "const" && !(this.match(52) || this.isContextual(95))) {
  12297. if (!isTypescript) {
  12298. this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Const declarations");
  12299. }
  12300. } else if (decl.id.type !== "Identifier" && !(isFor && (this.match(52) || this.isContextual(95)))) {
  12301. this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Complex binding patterns");
  12302. }
  12303. decl.init = null;
  12304. }
  12305. declarations.push(this.finishNode(decl, "VariableDeclarator"));
  12306. if (!this.eat(12)) break;
  12307. }
  12308. return node;
  12309. }
  12310. parseVarId(decl, kind) {
  12311. decl.id = this.parseBindingAtom();
  12312. this.checkLVal(decl.id, "variable declaration", kind === "var" ? BIND_VAR : BIND_LEXICAL, undefined, kind !== "var");
  12313. }
  12314. parseFunction(node, statement = FUNC_NO_FLAGS, isAsync = false) {
  12315. const isStatement = statement & FUNC_STATEMENT;
  12316. const isHangingStatement = statement & FUNC_HANGING_STATEMENT;
  12317. const requireId = !!isStatement && !(statement & FUNC_NULLABLE_ID);
  12318. this.initFunction(node, isAsync);
  12319. if (this.match(49) && isHangingStatement) {
  12320. this.raise(this.state.start, ErrorMessages.GeneratorInSingleStatementContext);
  12321. }
  12322. node.generator = this.eat(49);
  12323. if (isStatement) {
  12324. node.id = this.parseFunctionId(requireId);
  12325. }
  12326. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  12327. this.state.maybeInArrowParameters = false;
  12328. this.scope.enter(SCOPE_FUNCTION);
  12329. this.prodParam.enter(functionFlags(isAsync, node.generator));
  12330. if (!isStatement) {
  12331. node.id = this.parseFunctionId();
  12332. }
  12333. this.parseFunctionParams(node, false);
  12334. this.withSmartMixTopicForbiddingContext(() => {
  12335. this.parseFunctionBodyAndFinish(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
  12336. });
  12337. this.prodParam.exit();
  12338. this.scope.exit();
  12339. if (isStatement && !isHangingStatement) {
  12340. this.registerFunctionStatementId(node);
  12341. }
  12342. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  12343. return node;
  12344. }
  12345. parseFunctionId(requireId) {
  12346. return requireId || tokenIsIdentifier(this.state.type) ? this.parseIdentifier() : null;
  12347. }
  12348. parseFunctionParams(node, allowModifiers) {
  12349. this.expect(10);
  12350. this.expressionScope.enter(newParameterDeclarationScope());
  12351. node.params = this.parseBindingList(11, 41, false, allowModifiers);
  12352. this.expressionScope.exit();
  12353. }
  12354. registerFunctionStatementId(node) {
  12355. if (!node.id) return;
  12356. 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);
  12357. }
  12358. parseClass(node, isStatement, optionalId) {
  12359. this.next();
  12360. this.takeDecorators(node);
  12361. const oldStrict = this.state.strict;
  12362. this.state.strict = true;
  12363. this.parseClassId(node, isStatement, optionalId);
  12364. this.parseClassSuper(node);
  12365. node.body = this.parseClassBody(!!node.superClass, oldStrict);
  12366. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
  12367. }
  12368. isClassProperty() {
  12369. return this.match(27) || this.match(13) || this.match(8);
  12370. }
  12371. isClassMethod() {
  12372. return this.match(10);
  12373. }
  12374. isNonstaticConstructor(method) {
  12375. return !method.computed && !method.static && (method.key.name === "constructor" || method.key.value === "constructor");
  12376. }
  12377. parseClassBody(hadSuperClass, oldStrict) {
  12378. this.classScope.enter();
  12379. const state = {
  12380. hadConstructor: false,
  12381. hadSuperClass
  12382. };
  12383. let decorators = [];
  12384. const classBody = this.startNode();
  12385. classBody.body = [];
  12386. this.expect(5);
  12387. this.withSmartMixTopicForbiddingContext(() => {
  12388. while (!this.match(8)) {
  12389. if (this.eat(13)) {
  12390. if (decorators.length > 0) {
  12391. throw this.raise(this.state.lastTokEnd, ErrorMessages.DecoratorSemicolon);
  12392. }
  12393. continue;
  12394. }
  12395. if (this.match(24)) {
  12396. decorators.push(this.parseDecorator());
  12397. continue;
  12398. }
  12399. const member = this.startNode();
  12400. if (decorators.length) {
  12401. member.decorators = decorators;
  12402. this.resetStartLocationFromNode(member, decorators[0]);
  12403. decorators = [];
  12404. }
  12405. this.parseClassMember(classBody, member, state);
  12406. if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) {
  12407. this.raise(member.start, ErrorMessages.DecoratorConstructor);
  12408. }
  12409. }
  12410. });
  12411. this.state.strict = oldStrict;
  12412. this.next();
  12413. if (decorators.length) {
  12414. throw this.raise(this.state.start, ErrorMessages.TrailingDecorator);
  12415. }
  12416. this.classScope.exit();
  12417. return this.finishNode(classBody, "ClassBody");
  12418. }
  12419. parseClassMemberFromModifier(classBody, member) {
  12420. const key = this.parseIdentifier(true);
  12421. if (this.isClassMethod()) {
  12422. const method = member;
  12423. method.kind = "method";
  12424. method.computed = false;
  12425. method.key = key;
  12426. method.static = false;
  12427. this.pushClassMethod(classBody, method, false, false, false, false);
  12428. return true;
  12429. } else if (this.isClassProperty()) {
  12430. const prop = member;
  12431. prop.computed = false;
  12432. prop.key = key;
  12433. prop.static = false;
  12434. classBody.body.push(this.parseClassProperty(prop));
  12435. return true;
  12436. }
  12437. this.resetPreviousNodeTrailingComments(key);
  12438. return false;
  12439. }
  12440. parseClassMember(classBody, member, state) {
  12441. const isStatic = this.isContextual(98);
  12442. if (isStatic) {
  12443. if (this.parseClassMemberFromModifier(classBody, member)) {
  12444. return;
  12445. }
  12446. if (this.eat(5)) {
  12447. this.parseClassStaticBlock(classBody, member);
  12448. return;
  12449. }
  12450. }
  12451. this.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  12452. }
  12453. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  12454. const publicMethod = member;
  12455. const privateMethod = member;
  12456. const publicProp = member;
  12457. const privateProp = member;
  12458. const method = publicMethod;
  12459. const publicMember = publicMethod;
  12460. member.static = isStatic;
  12461. this.parsePropertyNamePrefixOperator(member);
  12462. if (this.eat(49)) {
  12463. method.kind = "method";
  12464. const isPrivateName = this.match(128);
  12465. this.parseClassElementName(method);
  12466. if (isPrivateName) {
  12467. this.pushClassPrivateMethod(classBody, privateMethod, true, false);
  12468. return;
  12469. }
  12470. if (this.isNonstaticConstructor(publicMethod)) {
  12471. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsGenerator);
  12472. }
  12473. this.pushClassMethod(classBody, publicMethod, true, false, false, false);
  12474. return;
  12475. }
  12476. const isContextual = tokenIsIdentifier(this.state.type) && !this.state.containsEsc;
  12477. const isPrivate = this.match(128);
  12478. const key = this.parseClassElementName(member);
  12479. const maybeQuestionTokenStart = this.state.start;
  12480. this.parsePostMemberNameModifiers(publicMember);
  12481. if (this.isClassMethod()) {
  12482. method.kind = "method";
  12483. if (isPrivate) {
  12484. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  12485. return;
  12486. }
  12487. const isConstructor = this.isNonstaticConstructor(publicMethod);
  12488. let allowsDirectSuper = false;
  12489. if (isConstructor) {
  12490. publicMethod.kind = "constructor";
  12491. if (state.hadConstructor && !this.hasPlugin("typescript")) {
  12492. this.raise(key.start, ErrorMessages.DuplicateConstructor);
  12493. }
  12494. if (isConstructor && this.hasPlugin("typescript") && member.override) {
  12495. this.raise(key.start, ErrorMessages.OverrideOnConstructor);
  12496. }
  12497. state.hadConstructor = true;
  12498. allowsDirectSuper = state.hadSuperClass;
  12499. }
  12500. this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper);
  12501. } else if (this.isClassProperty()) {
  12502. if (isPrivate) {
  12503. this.pushClassPrivateProperty(classBody, privateProp);
  12504. } else {
  12505. this.pushClassProperty(classBody, publicProp);
  12506. }
  12507. } else if (isContextual && key.name === "async" && !this.isLineTerminator()) {
  12508. this.resetPreviousNodeTrailingComments(key);
  12509. const isGenerator = this.eat(49);
  12510. if (publicMember.optional) {
  12511. this.unexpected(maybeQuestionTokenStart);
  12512. }
  12513. method.kind = "method";
  12514. const isPrivate = this.match(128);
  12515. this.parseClassElementName(method);
  12516. this.parsePostMemberNameModifiers(publicMember);
  12517. if (isPrivate) {
  12518. this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true);
  12519. } else {
  12520. if (this.isNonstaticConstructor(publicMethod)) {
  12521. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAsync);
  12522. }
  12523. this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false);
  12524. }
  12525. } else if (isContextual && (key.name === "get" || key.name === "set") && !(this.match(49) && this.isLineTerminator())) {
  12526. this.resetPreviousNodeTrailingComments(key);
  12527. method.kind = key.name;
  12528. const isPrivate = this.match(128);
  12529. this.parseClassElementName(publicMethod);
  12530. if (isPrivate) {
  12531. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  12532. } else {
  12533. if (this.isNonstaticConstructor(publicMethod)) {
  12534. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAccessor);
  12535. }
  12536. this.pushClassMethod(classBody, publicMethod, false, false, false, false);
  12537. }
  12538. this.checkGetterSetterParams(publicMethod);
  12539. } else if (this.isLineTerminator()) {
  12540. if (isPrivate) {
  12541. this.pushClassPrivateProperty(classBody, privateProp);
  12542. } else {
  12543. this.pushClassProperty(classBody, publicProp);
  12544. }
  12545. } else {
  12546. this.unexpected();
  12547. }
  12548. }
  12549. parseClassElementName(member) {
  12550. const {
  12551. type,
  12552. value,
  12553. start
  12554. } = this.state;
  12555. if ((type === 122 || type === 123) && member.static && value === "prototype") {
  12556. this.raise(start, ErrorMessages.StaticPrototype);
  12557. }
  12558. if (type === 128) {
  12559. if (value === "constructor") {
  12560. this.raise(start, ErrorMessages.ConstructorClassPrivateField);
  12561. }
  12562. const key = this.parsePrivateName();
  12563. member.key = key;
  12564. return key;
  12565. }
  12566. return this.parsePropertyName(member);
  12567. }
  12568. parseClassStaticBlock(classBody, member) {
  12569. var _member$decorators;
  12570. this.scope.enter(SCOPE_CLASS | SCOPE_STATIC_BLOCK | SCOPE_SUPER);
  12571. const oldLabels = this.state.labels;
  12572. this.state.labels = [];
  12573. this.prodParam.enter(PARAM);
  12574. const body = member.body = [];
  12575. this.parseBlockOrModuleBlockBody(body, undefined, false, 8);
  12576. this.prodParam.exit();
  12577. this.scope.exit();
  12578. this.state.labels = oldLabels;
  12579. classBody.body.push(this.finishNode(member, "StaticBlock"));
  12580. if ((_member$decorators = member.decorators) != null && _member$decorators.length) {
  12581. this.raise(member.start, ErrorMessages.DecoratorStaticBlock);
  12582. }
  12583. }
  12584. pushClassProperty(classBody, prop) {
  12585. if (!prop.computed && (prop.key.name === "constructor" || prop.key.value === "constructor")) {
  12586. this.raise(prop.key.start, ErrorMessages.ConstructorClassField);
  12587. }
  12588. classBody.body.push(this.parseClassProperty(prop));
  12589. }
  12590. pushClassPrivateProperty(classBody, prop) {
  12591. const node = this.parseClassPrivateProperty(prop);
  12592. classBody.body.push(node);
  12593. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), CLASS_ELEMENT_OTHER, node.key.start);
  12594. }
  12595. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  12596. classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true));
  12597. }
  12598. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  12599. const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true);
  12600. classBody.body.push(node);
  12601. 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;
  12602. this.declareClassPrivateMethodInScope(node, kind);
  12603. }
  12604. declareClassPrivateMethodInScope(node, kind) {
  12605. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), kind, node.key.start);
  12606. }
  12607. parsePostMemberNameModifiers(methodOrProp) {}
  12608. parseClassPrivateProperty(node) {
  12609. this.parseInitializer(node);
  12610. this.semicolon();
  12611. return this.finishNode(node, "ClassPrivateProperty");
  12612. }
  12613. parseClassProperty(node) {
  12614. this.parseInitializer(node);
  12615. this.semicolon();
  12616. return this.finishNode(node, "ClassProperty");
  12617. }
  12618. parseInitializer(node) {
  12619. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  12620. this.expressionScope.enter(newExpressionScope());
  12621. this.prodParam.enter(PARAM);
  12622. node.value = this.eat(27) ? this.parseMaybeAssignAllowIn() : null;
  12623. this.expressionScope.exit();
  12624. this.prodParam.exit();
  12625. this.scope.exit();
  12626. }
  12627. parseClassId(node, isStatement, optionalId, bindingType = BIND_CLASS) {
  12628. if (tokenIsIdentifier(this.state.type)) {
  12629. node.id = this.parseIdentifier();
  12630. if (isStatement) {
  12631. this.checkLVal(node.id, "class name", bindingType);
  12632. }
  12633. } else {
  12634. if (optionalId || !isStatement) {
  12635. node.id = null;
  12636. } else {
  12637. this.unexpected(null, ErrorMessages.MissingClassName);
  12638. }
  12639. }
  12640. }
  12641. parseClassSuper(node) {
  12642. node.superClass = this.eat(75) ? this.parseExprSubscripts() : null;
  12643. }
  12644. parseExport(node) {
  12645. const hasDefault = this.maybeParseExportDefaultSpecifier(node);
  12646. const parseAfterDefault = !hasDefault || this.eat(12);
  12647. const hasStar = parseAfterDefault && this.eatExportStar(node);
  12648. const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node);
  12649. const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(12));
  12650. const isFromRequired = hasDefault || hasStar;
  12651. if (hasStar && !hasNamespace) {
  12652. if (hasDefault) this.unexpected();
  12653. this.parseExportFrom(node, true);
  12654. return this.finishNode(node, "ExportAllDeclaration");
  12655. }
  12656. const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node);
  12657. if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers || hasNamespace && parseAfterNamespace && !hasSpecifiers) {
  12658. throw this.unexpected(null, 5);
  12659. }
  12660. let hasDeclaration;
  12661. if (isFromRequired || hasSpecifiers) {
  12662. hasDeclaration = false;
  12663. this.parseExportFrom(node, isFromRequired);
  12664. } else {
  12665. hasDeclaration = this.maybeParseExportDeclaration(node);
  12666. }
  12667. if (isFromRequired || hasSpecifiers || hasDeclaration) {
  12668. this.checkExport(node, true, false, !!node.source);
  12669. return this.finishNode(node, "ExportNamedDeclaration");
  12670. }
  12671. if (this.eat(59)) {
  12672. node.declaration = this.parseExportDefaultExpression();
  12673. this.checkExport(node, true, true);
  12674. return this.finishNode(node, "ExportDefaultDeclaration");
  12675. }
  12676. throw this.unexpected(null, 5);
  12677. }
  12678. eatExportStar(node) {
  12679. return this.eat(49);
  12680. }
  12681. maybeParseExportDefaultSpecifier(node) {
  12682. if (this.isExportDefaultSpecifier()) {
  12683. this.expectPlugin("exportDefaultFrom");
  12684. const specifier = this.startNode();
  12685. specifier.exported = this.parseIdentifier(true);
  12686. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  12687. return true;
  12688. }
  12689. return false;
  12690. }
  12691. maybeParseExportNamespaceSpecifier(node) {
  12692. if (this.isContextual(87)) {
  12693. if (!node.specifiers) node.specifiers = [];
  12694. const specifier = this.startNodeAt(this.state.lastTokStart, this.state.lastTokStartLoc);
  12695. this.next();
  12696. specifier.exported = this.parseModuleExportName();
  12697. node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
  12698. return true;
  12699. }
  12700. return false;
  12701. }
  12702. maybeParseExportNamedSpecifiers(node) {
  12703. if (this.match(5)) {
  12704. if (!node.specifiers) node.specifiers = [];
  12705. const isTypeExport = node.exportKind === "type";
  12706. node.specifiers.push(...this.parseExportSpecifiers(isTypeExport));
  12707. node.source = null;
  12708. node.declaration = null;
  12709. if (this.hasPlugin("importAssertions")) {
  12710. node.assertions = [];
  12711. }
  12712. return true;
  12713. }
  12714. return false;
  12715. }
  12716. maybeParseExportDeclaration(node) {
  12717. if (this.shouldParseExportDeclaration()) {
  12718. node.specifiers = [];
  12719. node.source = null;
  12720. if (this.hasPlugin("importAssertions")) {
  12721. node.assertions = [];
  12722. }
  12723. node.declaration = this.parseExportDeclaration(node);
  12724. return true;
  12725. }
  12726. return false;
  12727. }
  12728. isAsyncFunction() {
  12729. if (!this.isContextual(89)) return false;
  12730. const next = this.nextTokenStart();
  12731. return !lineBreak.test(this.input.slice(this.state.pos, next)) && this.isUnparsedContextual(next, "function");
  12732. }
  12733. parseExportDefaultExpression() {
  12734. const expr = this.startNode();
  12735. const isAsync = this.isAsyncFunction();
  12736. if (this.match(62) || isAsync) {
  12737. this.next();
  12738. if (isAsync) {
  12739. this.next();
  12740. }
  12741. return this.parseFunction(expr, FUNC_STATEMENT | FUNC_NULLABLE_ID, isAsync);
  12742. } else if (this.match(74)) {
  12743. return this.parseClass(expr, true, true);
  12744. } else if (this.match(24)) {
  12745. if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  12746. this.raise(this.state.start, ErrorMessages.DecoratorBeforeExport);
  12747. }
  12748. this.parseDecorators(false);
  12749. return this.parseClass(expr, true, true);
  12750. } else if (this.match(69) || this.match(68) || this.isLet()) {
  12751. throw this.raise(this.state.start, ErrorMessages.UnsupportedDefaultExport);
  12752. } else {
  12753. const res = this.parseMaybeAssignAllowIn();
  12754. this.semicolon();
  12755. return res;
  12756. }
  12757. }
  12758. parseExportDeclaration(node) {
  12759. return this.parseStatement(null);
  12760. }
  12761. isExportDefaultSpecifier() {
  12762. const {
  12763. type
  12764. } = this.state;
  12765. if (tokenIsIdentifier(type)) {
  12766. if (type === 89 && !this.state.containsEsc || type === 93) {
  12767. return false;
  12768. }
  12769. if ((type === 120 || type === 119) && !this.state.containsEsc) {
  12770. const {
  12771. type: nextType
  12772. } = this.lookahead();
  12773. if (tokenIsIdentifier(nextType) && nextType !== 91 || nextType === 5) {
  12774. this.expectOnePlugin(["flow", "typescript"]);
  12775. return false;
  12776. }
  12777. }
  12778. } else if (!this.match(59)) {
  12779. return false;
  12780. }
  12781. const next = this.nextTokenStart();
  12782. const hasFrom = this.isUnparsedContextual(next, "from");
  12783. if (this.input.charCodeAt(next) === 44 || tokenIsIdentifier(this.state.type) && hasFrom) {
  12784. return true;
  12785. }
  12786. if (this.match(59) && hasFrom) {
  12787. const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4));
  12788. return nextAfterFrom === 34 || nextAfterFrom === 39;
  12789. }
  12790. return false;
  12791. }
  12792. parseExportFrom(node, expect) {
  12793. if (this.eatContextual(91)) {
  12794. node.source = this.parseImportSource();
  12795. this.checkExport(node);
  12796. const assertions = this.maybeParseImportAssertions();
  12797. if (assertions) {
  12798. node.assertions = assertions;
  12799. }
  12800. } else if (expect) {
  12801. this.unexpected();
  12802. }
  12803. this.semicolon();
  12804. }
  12805. shouldParseExportDeclaration() {
  12806. const {
  12807. type
  12808. } = this.state;
  12809. if (type === 24) {
  12810. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  12811. if (this.hasPlugin("decorators")) {
  12812. if (this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  12813. this.unexpected(this.state.start, ErrorMessages.DecoratorBeforeExport);
  12814. } else {
  12815. return true;
  12816. }
  12817. }
  12818. }
  12819. return type === 68 || type === 69 || type === 62 || type === 74 || this.isLet() || this.isAsyncFunction();
  12820. }
  12821. checkExport(node, checkNames, isDefault, isFrom) {
  12822. if (checkNames) {
  12823. if (isDefault) {
  12824. this.checkDuplicateExports(node, "default");
  12825. if (this.hasPlugin("exportDefaultFrom")) {
  12826. var _declaration$extra;
  12827. const declaration = node.declaration;
  12828. if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 && !((_declaration$extra = declaration.extra) != null && _declaration$extra.parenthesized)) {
  12829. this.raise(declaration.start, ErrorMessages.ExportDefaultFromAsIdentifier);
  12830. }
  12831. }
  12832. } else if (node.specifiers && node.specifiers.length) {
  12833. for (const specifier of node.specifiers) {
  12834. const {
  12835. exported
  12836. } = specifier;
  12837. const exportedName = exported.type === "Identifier" ? exported.name : exported.value;
  12838. this.checkDuplicateExports(specifier, exportedName);
  12839. if (!isFrom && specifier.local) {
  12840. const {
  12841. local
  12842. } = specifier;
  12843. if (local.type !== "Identifier") {
  12844. this.raise(specifier.start, ErrorMessages.ExportBindingIsString, local.value, exportedName);
  12845. } else {
  12846. this.checkReservedWord(local.name, local.start, true, false);
  12847. this.scope.checkLocalExport(local);
  12848. }
  12849. }
  12850. }
  12851. } else if (node.declaration) {
  12852. if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") {
  12853. const id = node.declaration.id;
  12854. if (!id) throw new Error("Assertion failure");
  12855. this.checkDuplicateExports(node, id.name);
  12856. } else if (node.declaration.type === "VariableDeclaration") {
  12857. for (const declaration of node.declaration.declarations) {
  12858. this.checkDeclaration(declaration.id);
  12859. }
  12860. }
  12861. }
  12862. }
  12863. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  12864. if (currentContextDecorators.length) {
  12865. throw this.raise(node.start, ErrorMessages.UnsupportedDecoratorExport);
  12866. }
  12867. }
  12868. checkDeclaration(node) {
  12869. if (node.type === "Identifier") {
  12870. this.checkDuplicateExports(node, node.name);
  12871. } else if (node.type === "ObjectPattern") {
  12872. for (const prop of node.properties) {
  12873. this.checkDeclaration(prop);
  12874. }
  12875. } else if (node.type === "ArrayPattern") {
  12876. for (const elem of node.elements) {
  12877. if (elem) {
  12878. this.checkDeclaration(elem);
  12879. }
  12880. }
  12881. } else if (node.type === "ObjectProperty") {
  12882. this.checkDeclaration(node.value);
  12883. } else if (node.type === "RestElement") {
  12884. this.checkDeclaration(node.argument);
  12885. } else if (node.type === "AssignmentPattern") {
  12886. this.checkDeclaration(node.left);
  12887. }
  12888. }
  12889. checkDuplicateExports(node, name) {
  12890. if (this.exportedIdentifiers.has(name)) {
  12891. this.raise(node.start, name === "default" ? ErrorMessages.DuplicateDefaultExport : ErrorMessages.DuplicateExport, name);
  12892. }
  12893. this.exportedIdentifiers.add(name);
  12894. }
  12895. parseExportSpecifiers(isInTypeExport) {
  12896. const nodes = [];
  12897. let first = true;
  12898. this.expect(5);
  12899. while (!this.eat(8)) {
  12900. if (first) {
  12901. first = false;
  12902. } else {
  12903. this.expect(12);
  12904. if (this.eat(8)) break;
  12905. }
  12906. const isMaybeTypeOnly = this.isContextual(120);
  12907. const isString = this.match(123);
  12908. const node = this.startNode();
  12909. node.local = this.parseModuleExportName();
  12910. nodes.push(this.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly));
  12911. }
  12912. return nodes;
  12913. }
  12914. parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) {
  12915. if (this.eatContextual(87)) {
  12916. node.exported = this.parseModuleExportName();
  12917. } else if (isString) {
  12918. node.exported = cloneStringLiteral(node.local);
  12919. } else if (!node.exported) {
  12920. node.exported = cloneIdentifier(node.local);
  12921. }
  12922. return this.finishNode(node, "ExportSpecifier");
  12923. }
  12924. parseModuleExportName() {
  12925. if (this.match(123)) {
  12926. const result = this.parseStringLiteral(this.state.value);
  12927. const surrogate = result.value.match(loneSurrogate);
  12928. if (surrogate) {
  12929. this.raise(result.start, ErrorMessages.ModuleExportNameHasLoneSurrogate, surrogate[0].charCodeAt(0).toString(16));
  12930. }
  12931. return result;
  12932. }
  12933. return this.parseIdentifier(true);
  12934. }
  12935. parseImport(node) {
  12936. node.specifiers = [];
  12937. if (!this.match(123)) {
  12938. const hasDefault = this.maybeParseDefaultImportSpecifier(node);
  12939. const parseNext = !hasDefault || this.eat(12);
  12940. const hasStar = parseNext && this.maybeParseStarImportSpecifier(node);
  12941. if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node);
  12942. this.expectContextual(91);
  12943. }
  12944. node.source = this.parseImportSource();
  12945. const assertions = this.maybeParseImportAssertions();
  12946. if (assertions) {
  12947. node.assertions = assertions;
  12948. } else {
  12949. const attributes = this.maybeParseModuleAttributes();
  12950. if (attributes) {
  12951. node.attributes = attributes;
  12952. }
  12953. }
  12954. this.semicolon();
  12955. return this.finishNode(node, "ImportDeclaration");
  12956. }
  12957. parseImportSource() {
  12958. if (!this.match(123)) this.unexpected();
  12959. return this.parseExprAtom();
  12960. }
  12961. shouldParseDefaultImport(node) {
  12962. return tokenIsIdentifier(this.state.type);
  12963. }
  12964. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  12965. specifier.local = this.parseIdentifier();
  12966. this.checkLVal(specifier.local, contextDescription, BIND_LEXICAL);
  12967. node.specifiers.push(this.finishNode(specifier, type));
  12968. }
  12969. parseAssertEntries() {
  12970. const attrs = [];
  12971. const attrNames = new Set();
  12972. do {
  12973. if (this.match(8)) {
  12974. break;
  12975. }
  12976. const node = this.startNode();
  12977. const keyName = this.state.value;
  12978. if (attrNames.has(keyName)) {
  12979. this.raise(this.state.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, keyName);
  12980. }
  12981. attrNames.add(keyName);
  12982. if (this.match(123)) {
  12983. node.key = this.parseStringLiteral(keyName);
  12984. } else {
  12985. node.key = this.parseIdentifier(true);
  12986. }
  12987. this.expect(14);
  12988. if (!this.match(123)) {
  12989. throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue);
  12990. }
  12991. node.value = this.parseStringLiteral(this.state.value);
  12992. this.finishNode(node, "ImportAttribute");
  12993. attrs.push(node);
  12994. } while (this.eat(12));
  12995. return attrs;
  12996. }
  12997. maybeParseModuleAttributes() {
  12998. if (this.match(70) && !this.hasPrecedingLineBreak()) {
  12999. this.expectPlugin("moduleAttributes");
  13000. this.next();
  13001. } else {
  13002. if (this.hasPlugin("moduleAttributes")) return [];
  13003. return null;
  13004. }
  13005. const attrs = [];
  13006. const attributes = new Set();
  13007. do {
  13008. const node = this.startNode();
  13009. node.key = this.parseIdentifier(true);
  13010. if (node.key.name !== "type") {
  13011. this.raise(node.key.start, ErrorMessages.ModuleAttributeDifferentFromType, node.key.name);
  13012. }
  13013. if (attributes.has(node.key.name)) {
  13014. this.raise(node.key.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, node.key.name);
  13015. }
  13016. attributes.add(node.key.name);
  13017. this.expect(14);
  13018. if (!this.match(123)) {
  13019. throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue);
  13020. }
  13021. node.value = this.parseStringLiteral(this.state.value);
  13022. this.finishNode(node, "ImportAttribute");
  13023. attrs.push(node);
  13024. } while (this.eat(12));
  13025. return attrs;
  13026. }
  13027. maybeParseImportAssertions() {
  13028. if (this.isContextual(88) && !this.hasPrecedingLineBreak()) {
  13029. this.expectPlugin("importAssertions");
  13030. this.next();
  13031. } else {
  13032. if (this.hasPlugin("importAssertions")) return [];
  13033. return null;
  13034. }
  13035. this.eat(5);
  13036. const attrs = this.parseAssertEntries();
  13037. this.eat(8);
  13038. return attrs;
  13039. }
  13040. maybeParseDefaultImportSpecifier(node) {
  13041. if (this.shouldParseDefaultImport(node)) {
  13042. this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier", "default import specifier");
  13043. return true;
  13044. }
  13045. return false;
  13046. }
  13047. maybeParseStarImportSpecifier(node) {
  13048. if (this.match(49)) {
  13049. const specifier = this.startNode();
  13050. this.next();
  13051. this.expectContextual(87);
  13052. this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier", "import namespace specifier");
  13053. return true;
  13054. }
  13055. return false;
  13056. }
  13057. parseNamedImportSpecifiers(node) {
  13058. let first = true;
  13059. this.expect(5);
  13060. while (!this.eat(8)) {
  13061. if (first) {
  13062. first = false;
  13063. } else {
  13064. if (this.eat(14)) {
  13065. throw this.raise(this.state.start, ErrorMessages.DestructureNamedImport);
  13066. }
  13067. this.expect(12);
  13068. if (this.eat(8)) break;
  13069. }
  13070. const specifier = this.startNode();
  13071. const importedIsString = this.match(123);
  13072. const isMaybeTypeOnly = this.isContextual(120);
  13073. specifier.imported = this.parseModuleExportName();
  13074. const importSpecifier = this.parseImportSpecifier(specifier, importedIsString, node.importKind === "type" || node.importKind === "typeof", isMaybeTypeOnly);
  13075. node.specifiers.push(importSpecifier);
  13076. }
  13077. }
  13078. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly) {
  13079. if (this.eatContextual(87)) {
  13080. specifier.local = this.parseIdentifier();
  13081. } else {
  13082. const {
  13083. imported
  13084. } = specifier;
  13085. if (importedIsString) {
  13086. throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, imported.value);
  13087. }
  13088. this.checkReservedWord(imported.name, specifier.start, true, true);
  13089. if (!specifier.local) {
  13090. specifier.local = cloneIdentifier(imported);
  13091. }
  13092. }
  13093. this.checkLVal(specifier.local, "import specifier", BIND_LEXICAL);
  13094. return this.finishNode(specifier, "ImportSpecifier");
  13095. }
  13096. isThisParam(param) {
  13097. return param.type === "Identifier" && param.name === "this";
  13098. }
  13099. }
  13100. class Parser extends StatementParser {
  13101. constructor(options, input) {
  13102. options = getOptions(options);
  13103. super(options, input);
  13104. this.options = options;
  13105. this.initializeScopes();
  13106. this.plugins = pluginsMap(this.options.plugins);
  13107. this.filename = options.sourceFilename;
  13108. }
  13109. getScopeHandler() {
  13110. return ScopeHandler;
  13111. }
  13112. parse() {
  13113. this.enterInitialScopes();
  13114. const file = this.startNode();
  13115. const program = this.startNode();
  13116. this.nextToken();
  13117. file.errors = null;
  13118. this.parseTopLevel(file, program);
  13119. file.errors = this.state.errors;
  13120. return file;
  13121. }
  13122. }
  13123. function pluginsMap(plugins) {
  13124. const pluginMap = new Map();
  13125. for (const plugin of plugins) {
  13126. const [name, options] = Array.isArray(plugin) ? plugin : [plugin, {}];
  13127. if (!pluginMap.has(name)) pluginMap.set(name, options || {});
  13128. }
  13129. return pluginMap;
  13130. }
  13131. function parse(input, options) {
  13132. var _options;
  13133. if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") {
  13134. options = Object.assign({}, options);
  13135. try {
  13136. options.sourceType = "module";
  13137. const parser = getParser(options, input);
  13138. const ast = parser.parse();
  13139. if (parser.sawUnambiguousESM) {
  13140. return ast;
  13141. }
  13142. if (parser.ambiguousScriptDifferentAst) {
  13143. try {
  13144. options.sourceType = "script";
  13145. return getParser(options, input).parse();
  13146. } catch (_unused) {}
  13147. } else {
  13148. ast.program.sourceType = "script";
  13149. }
  13150. return ast;
  13151. } catch (moduleError) {
  13152. try {
  13153. options.sourceType = "script";
  13154. return getParser(options, input).parse();
  13155. } catch (_unused2) {}
  13156. throw moduleError;
  13157. }
  13158. } else {
  13159. return getParser(options, input).parse();
  13160. }
  13161. }
  13162. function parseExpression(input, options) {
  13163. const parser = getParser(options, input);
  13164. if (parser.options.strictMode) {
  13165. parser.state.strict = true;
  13166. }
  13167. return parser.getExpression();
  13168. }
  13169. function generateExportedTokenTypes(internalTokenTypes) {
  13170. const tokenTypes = {};
  13171. for (const typeName of Object.keys(internalTokenTypes)) {
  13172. tokenTypes[typeName] = getExportedToken(internalTokenTypes[typeName]);
  13173. }
  13174. return tokenTypes;
  13175. }
  13176. const tokTypes = generateExportedTokenTypes(tt);
  13177. function getParser(options, input) {
  13178. let cls = Parser;
  13179. if (options != null && options.plugins) {
  13180. validatePlugins(options.plugins);
  13181. cls = getParserClass(options.plugins);
  13182. }
  13183. return new cls(options, input);
  13184. }
  13185. const parserClassCache = {};
  13186. function getParserClass(pluginsFromOptions) {
  13187. const pluginList = mixinPluginNames.filter(name => hasPlugin(pluginsFromOptions, name));
  13188. const key = pluginList.join("/");
  13189. let cls = parserClassCache[key];
  13190. if (!cls) {
  13191. cls = Parser;
  13192. for (const plugin of pluginList) {
  13193. cls = mixinPlugins[plugin](cls);
  13194. }
  13195. parserClassCache[key] = cls;
  13196. }
  13197. return cls;
  13198. }
  13199. var parse_1 = parse;
  13200. var parseExpression_1 = parseExpression;
  13201. var tokTypes_1 = tokTypes;
  13202. //# sourceMappingURL=index.js.map
  13203. /*#__PURE__*/Object.defineProperty({
  13204. parse: parse_1,
  13205. parseExpression: parseExpression_1,
  13206. tokTypes: tokTypes_1
  13207. }, '__esModule', {value: true});
  13208. const isStaticExp = (p) => p.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && p.isStatic;
  13209. const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
  13210. function isCoreComponent(tag) {
  13211. if (isBuiltInType(tag, 'Teleport')) {
  13212. return TELEPORT;
  13213. }
  13214. else if (isBuiltInType(tag, 'Suspense')) {
  13215. return SUSPENSE;
  13216. }
  13217. else if (isBuiltInType(tag, 'KeepAlive')) {
  13218. return KEEP_ALIVE;
  13219. }
  13220. else if (isBuiltInType(tag, 'BaseTransition')) {
  13221. return BASE_TRANSITION;
  13222. }
  13223. }
  13224. const nonIdentifierRE = /^\d|[^\$\w]/;
  13225. const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
  13226. const validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/;
  13227. const validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/;
  13228. const whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g;
  13229. /**
  13230. * Simple lexer to check if an expression is a member expression. This is
  13231. * lax and only checks validity at the root level (i.e. does not validate exps
  13232. * inside square brackets), but it's ok since these are only used on template
  13233. * expressions and false positives are invalid expressions in the first place.
  13234. */
  13235. const isMemberExpressionBrowser = (path) => {
  13236. // remove whitespaces around . or [ first
  13237. path = path.trim().replace(whitespaceRE, s => s.trim());
  13238. let state = 0 /* MemberExpLexState.inMemberExp */;
  13239. let stateStack = [];
  13240. let currentOpenBracketCount = 0;
  13241. let currentOpenParensCount = 0;
  13242. let currentStringType = null;
  13243. for (let i = 0; i < path.length; i++) {
  13244. const char = path.charAt(i);
  13245. switch (state) {
  13246. case 0 /* MemberExpLexState.inMemberExp */:
  13247. if (char === '[') {
  13248. stateStack.push(state);
  13249. state = 1 /* MemberExpLexState.inBrackets */;
  13250. currentOpenBracketCount++;
  13251. }
  13252. else if (char === '(') {
  13253. stateStack.push(state);
  13254. state = 2 /* MemberExpLexState.inParens */;
  13255. currentOpenParensCount++;
  13256. }
  13257. else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) {
  13258. return false;
  13259. }
  13260. break;
  13261. case 1 /* MemberExpLexState.inBrackets */:
  13262. if (char === `'` || char === `"` || char === '`') {
  13263. stateStack.push(state);
  13264. state = 3 /* MemberExpLexState.inString */;
  13265. currentStringType = char;
  13266. }
  13267. else if (char === `[`) {
  13268. currentOpenBracketCount++;
  13269. }
  13270. else if (char === `]`) {
  13271. if (!--currentOpenBracketCount) {
  13272. state = stateStack.pop();
  13273. }
  13274. }
  13275. break;
  13276. case 2 /* MemberExpLexState.inParens */:
  13277. if (char === `'` || char === `"` || char === '`') {
  13278. stateStack.push(state);
  13279. state = 3 /* MemberExpLexState.inString */;
  13280. currentStringType = char;
  13281. }
  13282. else if (char === `(`) {
  13283. currentOpenParensCount++;
  13284. }
  13285. else if (char === `)`) {
  13286. // if the exp ends as a call then it should not be considered valid
  13287. if (i === path.length - 1) {
  13288. return false;
  13289. }
  13290. if (!--currentOpenParensCount) {
  13291. state = stateStack.pop();
  13292. }
  13293. }
  13294. break;
  13295. case 3 /* MemberExpLexState.inString */:
  13296. if (char === currentStringType) {
  13297. state = stateStack.pop();
  13298. currentStringType = null;
  13299. }
  13300. break;
  13301. }
  13302. }
  13303. return !currentOpenBracketCount && !currentOpenParensCount;
  13304. };
  13305. const isMemberExpressionNode = (path, context) => {
  13306. try {
  13307. let ret = parseExpression_1(path, {
  13308. plugins: context.expressionPlugins
  13309. });
  13310. if (ret.type === 'TSAsExpression' || ret.type === 'TSTypeAssertion') {
  13311. ret = ret.expression;
  13312. }
  13313. return (ret.type === 'MemberExpression' ||
  13314. ret.type === 'OptionalMemberExpression' ||
  13315. ret.type === 'Identifier');
  13316. }
  13317. catch (e) {
  13318. return false;
  13319. }
  13320. };
  13321. const isMemberExpression = isMemberExpressionNode;
  13322. function getInnerRange(loc, offset, length) {
  13323. const source = loc.source.slice(offset, offset + length);
  13324. const newLoc = {
  13325. source,
  13326. start: advancePositionWithClone(loc.start, loc.source, offset),
  13327. end: loc.end
  13328. };
  13329. if (length != null) {
  13330. newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
  13331. }
  13332. return newLoc;
  13333. }
  13334. function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
  13335. return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
  13336. }
  13337. // advance by mutation without cloning (for performance reasons), since this
  13338. // gets called a lot in the parser
  13339. function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
  13340. let linesCount = 0;
  13341. let lastNewLinePos = -1;
  13342. for (let i = 0; i < numberOfCharacters; i++) {
  13343. if (source.charCodeAt(i) === 10 /* newline char code */) {
  13344. linesCount++;
  13345. lastNewLinePos = i;
  13346. }
  13347. }
  13348. pos.offset += numberOfCharacters;
  13349. pos.line += linesCount;
  13350. pos.column =
  13351. lastNewLinePos === -1
  13352. ? pos.column + numberOfCharacters
  13353. : numberOfCharacters - lastNewLinePos;
  13354. return pos;
  13355. }
  13356. function assert$1(condition, msg) {
  13357. /* istanbul ignore if */
  13358. if (!condition) {
  13359. throw new Error(msg || `unexpected compiler condition`);
  13360. }
  13361. }
  13362. function findDir(node, name, allowEmpty = false) {
  13363. for (let i = 0; i < node.props.length; i++) {
  13364. const p = node.props[i];
  13365. if (p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  13366. (allowEmpty || p.exp) &&
  13367. (isString(name) ? p.name === name : name.test(p.name))) {
  13368. return p;
  13369. }
  13370. }
  13371. }
  13372. function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
  13373. for (let i = 0; i < node.props.length; i++) {
  13374. const p = node.props[i];
  13375. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  13376. if (dynamicOnly)
  13377. continue;
  13378. if (p.name === name && (p.value || allowEmpty)) {
  13379. return p;
  13380. }
  13381. }
  13382. else if (p.name === 'bind' &&
  13383. (p.exp || allowEmpty) &&
  13384. isStaticArgOf(p.arg, name)) {
  13385. return p;
  13386. }
  13387. }
  13388. }
  13389. function isStaticArgOf(arg, name) {
  13390. return !!(arg && isStaticExp(arg) && arg.content === name);
  13391. }
  13392. function hasDynamicKeyVBind(node) {
  13393. return node.props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  13394. p.name === 'bind' &&
  13395. (!p.arg || // v-bind="obj"
  13396. p.arg.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
  13397. !p.arg.isStatic) // v-bind:[foo]
  13398. );
  13399. }
  13400. function isText(node) {
  13401. return node.type === 5 /* NodeTypes.INTERPOLATION */ || node.type === 2 /* NodeTypes.TEXT */;
  13402. }
  13403. function isVSlot(p) {
  13404. return p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'slot';
  13405. }
  13406. function isTemplateNode(node) {
  13407. return (node.type === 1 /* NodeTypes.ELEMENT */ && node.tagType === 3 /* ElementTypes.TEMPLATE */);
  13408. }
  13409. function isSlotOutlet(node) {
  13410. return node.type === 1 /* NodeTypes.ELEMENT */ && node.tagType === 2 /* ElementTypes.SLOT */;
  13411. }
  13412. function getVNodeHelper(ssr, isComponent) {
  13413. return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE;
  13414. }
  13415. function getVNodeBlockHelper(ssr, isComponent) {
  13416. return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK;
  13417. }
  13418. const propsHelperSet = new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]);
  13419. function getUnnormalizedProps(props, callPath = []) {
  13420. if (props &&
  13421. !isString(props) &&
  13422. props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  13423. const callee = props.callee;
  13424. if (!isString(callee) && propsHelperSet.has(callee)) {
  13425. return getUnnormalizedProps(props.arguments[0], callPath.concat(props));
  13426. }
  13427. }
  13428. return [props, callPath];
  13429. }
  13430. function injectProp(node, prop, context) {
  13431. let propsWithInjection;
  13432. /**
  13433. * 1. mergeProps(...)
  13434. * 2. toHandlers(...)
  13435. * 3. normalizeProps(...)
  13436. * 4. normalizeProps(guardReactiveProps(...))
  13437. *
  13438. * we need to get the real props before normalization
  13439. */
  13440. let props = node.type === 13 /* NodeTypes.VNODE_CALL */ ? node.props : node.arguments[2];
  13441. let callPath = [];
  13442. let parentCall;
  13443. if (props &&
  13444. !isString(props) &&
  13445. props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  13446. const ret = getUnnormalizedProps(props);
  13447. props = ret[0];
  13448. callPath = ret[1];
  13449. parentCall = callPath[callPath.length - 1];
  13450. }
  13451. if (props == null || isString(props)) {
  13452. propsWithInjection = createObjectExpression([prop]);
  13453. }
  13454. else if (props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  13455. // merged props... add ours
  13456. // only inject key to object literal if it's the first argument so that
  13457. // if doesn't override user provided keys
  13458. const first = props.arguments[0];
  13459. if (!isString(first) && first.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
  13460. // #6631
  13461. if (!hasProp(prop, first)) {
  13462. first.properties.unshift(prop);
  13463. }
  13464. }
  13465. else {
  13466. if (props.callee === TO_HANDLERS) {
  13467. // #2366
  13468. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  13469. createObjectExpression([prop]),
  13470. props
  13471. ]);
  13472. }
  13473. else {
  13474. props.arguments.unshift(createObjectExpression([prop]));
  13475. }
  13476. }
  13477. !propsWithInjection && (propsWithInjection = props);
  13478. }
  13479. else if (props.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
  13480. if (!hasProp(prop, props)) {
  13481. props.properties.unshift(prop);
  13482. }
  13483. propsWithInjection = props;
  13484. }
  13485. else {
  13486. // single v-bind with expression, return a merged replacement
  13487. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  13488. createObjectExpression([prop]),
  13489. props
  13490. ]);
  13491. // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(props))`,
  13492. // it will be rewritten as `normalizeProps(mergeProps({ key: 0 }, props))`,
  13493. // the `guardReactiveProps` will no longer be needed
  13494. if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) {
  13495. parentCall = callPath[callPath.length - 2];
  13496. }
  13497. }
  13498. if (node.type === 13 /* NodeTypes.VNODE_CALL */) {
  13499. if (parentCall) {
  13500. parentCall.arguments[0] = propsWithInjection;
  13501. }
  13502. else {
  13503. node.props = propsWithInjection;
  13504. }
  13505. }
  13506. else {
  13507. if (parentCall) {
  13508. parentCall.arguments[0] = propsWithInjection;
  13509. }
  13510. else {
  13511. node.arguments[2] = propsWithInjection;
  13512. }
  13513. }
  13514. }
  13515. // check existing key to avoid overriding user provided keys
  13516. function hasProp(prop, props) {
  13517. let result = false;
  13518. if (prop.key.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  13519. const propKeyName = prop.key.content;
  13520. result = props.properties.some(p => p.key.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  13521. p.key.content === propKeyName);
  13522. }
  13523. return result;
  13524. }
  13525. function toValidAssetId(name, type) {
  13526. // see issue#4422, we need adding identifier on validAssetId if variable `name` has specific character
  13527. return `_${type}_${name.replace(/[^\w]/g, (searchValue, replaceValue) => {
  13528. return searchValue === '-' ? '_' : name.charCodeAt(replaceValue).toString();
  13529. })}`;
  13530. }
  13531. // Check if a node contains expressions that reference current context scope ids
  13532. function hasScopeRef(node, ids) {
  13533. if (!node || Object.keys(ids).length === 0) {
  13534. return false;
  13535. }
  13536. switch (node.type) {
  13537. case 1 /* NodeTypes.ELEMENT */:
  13538. for (let i = 0; i < node.props.length; i++) {
  13539. const p = node.props[i];
  13540. if (p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  13541. (hasScopeRef(p.arg, ids) || hasScopeRef(p.exp, ids))) {
  13542. return true;
  13543. }
  13544. }
  13545. return node.children.some(c => hasScopeRef(c, ids));
  13546. case 11 /* NodeTypes.FOR */:
  13547. if (hasScopeRef(node.source, ids)) {
  13548. return true;
  13549. }
  13550. return node.children.some(c => hasScopeRef(c, ids));
  13551. case 9 /* NodeTypes.IF */:
  13552. return node.branches.some(b => hasScopeRef(b, ids));
  13553. case 10 /* NodeTypes.IF_BRANCH */:
  13554. if (hasScopeRef(node.condition, ids)) {
  13555. return true;
  13556. }
  13557. return node.children.some(c => hasScopeRef(c, ids));
  13558. case 4 /* NodeTypes.SIMPLE_EXPRESSION */:
  13559. return (!node.isStatic &&
  13560. isSimpleIdentifier(node.content) &&
  13561. !!ids[node.content]);
  13562. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  13563. return node.children.some(c => isObject(c) && hasScopeRef(c, ids));
  13564. case 5 /* NodeTypes.INTERPOLATION */:
  13565. case 12 /* NodeTypes.TEXT_CALL */:
  13566. return hasScopeRef(node.content, ids);
  13567. case 2 /* NodeTypes.TEXT */:
  13568. case 3 /* NodeTypes.COMMENT */:
  13569. return false;
  13570. default:
  13571. return false;
  13572. }
  13573. }
  13574. function getMemoedVNodeCall(node) {
  13575. if (node.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */ && node.callee === WITH_MEMO) {
  13576. return node.arguments[1].returns;
  13577. }
  13578. else {
  13579. return node;
  13580. }
  13581. }
  13582. function makeBlock(node, { helper, removeHelper, inSSR }) {
  13583. if (!node.isBlock) {
  13584. node.isBlock = true;
  13585. removeHelper(getVNodeHelper(inSSR, node.isComponent));
  13586. helper(OPEN_BLOCK);
  13587. helper(getVNodeBlockHelper(inSSR, node.isComponent));
  13588. }
  13589. }
  13590. const deprecationData = {
  13591. ["COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */]: {
  13592. message: `Platform-native elements with "is" prop will no longer be ` +
  13593. `treated as components in Vue 3 unless the "is" value is explicitly ` +
  13594. `prefixed with "vue:".`,
  13595. link: `https://v3-migration.vuejs.org/breaking-changes/custom-elements-interop.html`
  13596. },
  13597. ["COMPILER_V_BIND_SYNC" /* CompilerDeprecationTypes.COMPILER_V_BIND_SYNC */]: {
  13598. message: key => `.sync modifier for v-bind has been removed. Use v-model with ` +
  13599. `argument instead. \`v-bind:${key}.sync\` should be changed to ` +
  13600. `\`v-model:${key}\`.`,
  13601. link: `https://v3-migration.vuejs.org/breaking-changes/v-model.html`
  13602. },
  13603. ["COMPILER_V_BIND_PROP" /* CompilerDeprecationTypes.COMPILER_V_BIND_PROP */]: {
  13604. message: `.prop modifier for v-bind has been removed and no longer necessary. ` +
  13605. `Vue 3 will automatically set a binding as DOM property when appropriate.`
  13606. },
  13607. ["COMPILER_V_BIND_OBJECT_ORDER" /* CompilerDeprecationTypes.COMPILER_V_BIND_OBJECT_ORDER */]: {
  13608. message: `v-bind="obj" usage is now order sensitive and behaves like JavaScript ` +
  13609. `object spread: it will now overwrite an existing non-mergeable attribute ` +
  13610. `that appears before v-bind in the case of conflict. ` +
  13611. `To retain 2.x behavior, move v-bind to make it the first attribute. ` +
  13612. `You can also suppress this warning if the usage is intended.`,
  13613. link: `https://v3-migration.vuejs.org/breaking-changes/v-bind.html`
  13614. },
  13615. ["COMPILER_V_ON_NATIVE" /* CompilerDeprecationTypes.COMPILER_V_ON_NATIVE */]: {
  13616. message: `.native modifier for v-on has been removed as is no longer necessary.`,
  13617. link: `https://v3-migration.vuejs.org/breaking-changes/v-on-native-modifier-removed.html`
  13618. },
  13619. ["COMPILER_V_IF_V_FOR_PRECEDENCE" /* CompilerDeprecationTypes.COMPILER_V_IF_V_FOR_PRECEDENCE */]: {
  13620. message: `v-if / v-for precedence when used on the same element has changed ` +
  13621. `in Vue 3: v-if now takes higher precedence and will no longer have ` +
  13622. `access to v-for scope variables. It is best to avoid the ambiguity ` +
  13623. `with <template> tags or use a computed property that filters v-for ` +
  13624. `data source.`,
  13625. link: `https://v3-migration.vuejs.org/breaking-changes/v-if-v-for.html`
  13626. },
  13627. ["COMPILER_NATIVE_TEMPLATE" /* CompilerDeprecationTypes.COMPILER_NATIVE_TEMPLATE */]: {
  13628. message: `<template> with no special directives will render as a native template ` +
  13629. `element instead of its inner content in Vue 3.`
  13630. },
  13631. ["COMPILER_INLINE_TEMPLATE" /* CompilerDeprecationTypes.COMPILER_INLINE_TEMPLATE */]: {
  13632. message: `"inline-template" has been removed in Vue 3.`,
  13633. link: `https://v3-migration.vuejs.org/breaking-changes/inline-template-attribute.html`
  13634. },
  13635. ["COMPILER_FILTER" /* CompilerDeprecationTypes.COMPILER_FILTERS */]: {
  13636. message: `filters have been removed in Vue 3. ` +
  13637. `The "|" symbol will be treated as native JavaScript bitwise OR operator. ` +
  13638. `Use method calls or computed properties instead.`,
  13639. link: `https://v3-migration.vuejs.org/breaking-changes/filters.html`
  13640. }
  13641. };
  13642. function getCompatValue(key, context) {
  13643. const config = context.options
  13644. ? context.options.compatConfig
  13645. : context.compatConfig;
  13646. const value = config && config[key];
  13647. if (key === 'MODE') {
  13648. return value || 3; // compiler defaults to v3 behavior
  13649. }
  13650. else {
  13651. return value;
  13652. }
  13653. }
  13654. function isCompatEnabled(key, context) {
  13655. const mode = getCompatValue('MODE', context);
  13656. const value = getCompatValue(key, context);
  13657. // in v3 mode, only enable if explicitly set to true
  13658. // otherwise enable for any non-false value
  13659. return mode === 3 ? value === true : value !== false;
  13660. }
  13661. function checkCompatEnabled(key, context, loc, ...args) {
  13662. const enabled = isCompatEnabled(key, context);
  13663. if (enabled) {
  13664. warnDeprecation(key, context, loc, ...args);
  13665. }
  13666. return enabled;
  13667. }
  13668. function warnDeprecation(key, context, loc, ...args) {
  13669. const val = getCompatValue(key, context);
  13670. if (val === 'suppress-warning') {
  13671. return;
  13672. }
  13673. const { message, link } = deprecationData[key];
  13674. const msg = `(deprecation ${key}) ${typeof message === 'function' ? message(...args) : message}${link ? `\n Details: ${link}` : ``}`;
  13675. const err = new SyntaxError(msg);
  13676. err.code = key;
  13677. if (loc)
  13678. err.loc = loc;
  13679. context.onWarn(err);
  13680. }
  13681. // The default decoder only provides escapes for characters reserved as part of
  13682. // the template syntax, and is only used if the custom renderer did not provide
  13683. // a platform-specific decoder.
  13684. const decodeRE = /&(gt|lt|amp|apos|quot);/g;
  13685. const decodeMap = {
  13686. gt: '>',
  13687. lt: '<',
  13688. amp: '&',
  13689. apos: "'",
  13690. quot: '"'
  13691. };
  13692. const defaultParserOptions = {
  13693. delimiters: [`{{`, `}}`],
  13694. getNamespace: () => 0 /* Namespaces.HTML */,
  13695. getTextMode: () => 0 /* TextModes.DATA */,
  13696. isVoidTag: NO,
  13697. isPreTag: NO,
  13698. isCustomElement: NO,
  13699. decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
  13700. onError: defaultOnError,
  13701. onWarn: defaultOnWarn,
  13702. comments: true
  13703. };
  13704. function baseParse(content, options = {}) {
  13705. const context = createParserContext(content, options);
  13706. const start = getCursor(context);
  13707. return createRoot(parseChildren(context, 0 /* TextModes.DATA */, []), getSelection(context, start));
  13708. }
  13709. function createParserContext(content, rawOptions) {
  13710. const options = extend({}, defaultParserOptions);
  13711. let key;
  13712. for (key in rawOptions) {
  13713. // @ts-ignore
  13714. options[key] =
  13715. rawOptions[key] === undefined
  13716. ? defaultParserOptions[key]
  13717. : rawOptions[key];
  13718. }
  13719. return {
  13720. options,
  13721. column: 1,
  13722. line: 1,
  13723. offset: 0,
  13724. originalSource: content,
  13725. source: content,
  13726. inPre: false,
  13727. inVPre: false,
  13728. onWarn: options.onWarn
  13729. };
  13730. }
  13731. function parseChildren(context, mode, ancestors) {
  13732. const parent = last(ancestors);
  13733. const ns = parent ? parent.ns : 0 /* Namespaces.HTML */;
  13734. const nodes = [];
  13735. while (!isEnd(context, mode, ancestors)) {
  13736. const s = context.source;
  13737. let node = undefined;
  13738. if (mode === 0 /* TextModes.DATA */ || mode === 1 /* TextModes.RCDATA */) {
  13739. if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
  13740. // '{{'
  13741. node = parseInterpolation(context, mode);
  13742. }
  13743. else if (mode === 0 /* TextModes.DATA */ && s[0] === '<') {
  13744. // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
  13745. if (s.length === 1) {
  13746. emitError(context, 5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */, 1);
  13747. }
  13748. else if (s[1] === '!') {
  13749. // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
  13750. if (startsWith(s, '<!--')) {
  13751. node = parseComment(context);
  13752. }
  13753. else if (startsWith(s, '<!DOCTYPE')) {
  13754. // Ignore DOCTYPE by a limitation.
  13755. node = parseBogusComment(context);
  13756. }
  13757. else if (startsWith(s, '<![CDATA[')) {
  13758. if (ns !== 0 /* Namespaces.HTML */) {
  13759. node = parseCDATA(context, ancestors);
  13760. }
  13761. else {
  13762. emitError(context, 1 /* ErrorCodes.CDATA_IN_HTML_CONTENT */);
  13763. node = parseBogusComment(context);
  13764. }
  13765. }
  13766. else {
  13767. emitError(context, 11 /* ErrorCodes.INCORRECTLY_OPENED_COMMENT */);
  13768. node = parseBogusComment(context);
  13769. }
  13770. }
  13771. else if (s[1] === '/') {
  13772. // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
  13773. if (s.length === 2) {
  13774. emitError(context, 5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */, 2);
  13775. }
  13776. else if (s[2] === '>') {
  13777. emitError(context, 14 /* ErrorCodes.MISSING_END_TAG_NAME */, 2);
  13778. advanceBy(context, 3);
  13779. continue;
  13780. }
  13781. else if (/[a-z]/i.test(s[2])) {
  13782. emitError(context, 23 /* ErrorCodes.X_INVALID_END_TAG */);
  13783. parseTag(context, 1 /* TagType.End */, parent);
  13784. continue;
  13785. }
  13786. else {
  13787. emitError(context, 12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
  13788. node = parseBogusComment(context);
  13789. }
  13790. }
  13791. else if (/[a-z]/i.test(s[1])) {
  13792. node = parseElement(context, ancestors);
  13793. }
  13794. else if (s[1] === '?') {
  13795. emitError(context, 21 /* ErrorCodes.UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
  13796. node = parseBogusComment(context);
  13797. }
  13798. else {
  13799. emitError(context, 12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
  13800. }
  13801. }
  13802. }
  13803. if (!node) {
  13804. node = parseText(context, mode);
  13805. }
  13806. if (isArray(node)) {
  13807. for (let i = 0; i < node.length; i++) {
  13808. pushNode(nodes, node[i]);
  13809. }
  13810. }
  13811. else {
  13812. pushNode(nodes, node);
  13813. }
  13814. }
  13815. // Whitespace handling strategy like v2
  13816. let removedWhitespace = false;
  13817. if (mode !== 2 /* TextModes.RAWTEXT */ && mode !== 1 /* TextModes.RCDATA */) {
  13818. const shouldCondense = context.options.whitespace !== 'preserve';
  13819. for (let i = 0; i < nodes.length; i++) {
  13820. const node = nodes[i];
  13821. if (node.type === 2 /* NodeTypes.TEXT */) {
  13822. if (!context.inPre) {
  13823. if (!/[^\t\r\n\f ]/.test(node.content)) {
  13824. const prev = nodes[i - 1];
  13825. const next = nodes[i + 1];
  13826. // Remove if:
  13827. // - the whitespace is the first or last node, or:
  13828. // - (condense mode) the whitespace is between twos comments, or:
  13829. // - (condense mode) the whitespace is between comment and element, or:
  13830. // - (condense mode) the whitespace is between two elements AND contains newline
  13831. if (!prev ||
  13832. !next ||
  13833. (shouldCondense &&
  13834. ((prev.type === 3 /* NodeTypes.COMMENT */ &&
  13835. next.type === 3 /* NodeTypes.COMMENT */) ||
  13836. (prev.type === 3 /* NodeTypes.COMMENT */ &&
  13837. next.type === 1 /* NodeTypes.ELEMENT */) ||
  13838. (prev.type === 1 /* NodeTypes.ELEMENT */ &&
  13839. next.type === 3 /* NodeTypes.COMMENT */) ||
  13840. (prev.type === 1 /* NodeTypes.ELEMENT */ &&
  13841. next.type === 1 /* NodeTypes.ELEMENT */ &&
  13842. /[\r\n]/.test(node.content))))) {
  13843. removedWhitespace = true;
  13844. nodes[i] = null;
  13845. }
  13846. else {
  13847. // Otherwise, the whitespace is condensed into a single space
  13848. node.content = ' ';
  13849. }
  13850. }
  13851. else if (shouldCondense) {
  13852. // in condense mode, consecutive whitespaces in text are condensed
  13853. // down to a single space.
  13854. node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
  13855. }
  13856. }
  13857. else {
  13858. // #6410 normalize windows newlines in <pre>:
  13859. // in SSR, browsers normalize server-rendered \r\n into a single \n
  13860. // in the DOM
  13861. node.content = node.content.replace(/\r\n/g, '\n');
  13862. }
  13863. }
  13864. // Remove comment nodes if desired by configuration.
  13865. else if (node.type === 3 /* NodeTypes.COMMENT */ && !context.options.comments) {
  13866. removedWhitespace = true;
  13867. nodes[i] = null;
  13868. }
  13869. }
  13870. if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
  13871. // remove leading newline per html spec
  13872. // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
  13873. const first = nodes[0];
  13874. if (first && first.type === 2 /* NodeTypes.TEXT */) {
  13875. first.content = first.content.replace(/^\r?\n/, '');
  13876. }
  13877. }
  13878. }
  13879. return removedWhitespace ? nodes.filter(Boolean) : nodes;
  13880. }
  13881. function pushNode(nodes, node) {
  13882. if (node.type === 2 /* NodeTypes.TEXT */) {
  13883. const prev = last(nodes);
  13884. // Merge if both this and the previous node are text and those are
  13885. // consecutive. This happens for cases like "a < b".
  13886. if (prev &&
  13887. prev.type === 2 /* NodeTypes.TEXT */ &&
  13888. prev.loc.end.offset === node.loc.start.offset) {
  13889. prev.content += node.content;
  13890. prev.loc.end = node.loc.end;
  13891. prev.loc.source += node.loc.source;
  13892. return;
  13893. }
  13894. }
  13895. nodes.push(node);
  13896. }
  13897. function parseCDATA(context, ancestors) {
  13898. advanceBy(context, 9);
  13899. const nodes = parseChildren(context, 3 /* TextModes.CDATA */, ancestors);
  13900. if (context.source.length === 0) {
  13901. emitError(context, 6 /* ErrorCodes.EOF_IN_CDATA */);
  13902. }
  13903. else {
  13904. advanceBy(context, 3);
  13905. }
  13906. return nodes;
  13907. }
  13908. function parseComment(context) {
  13909. const start = getCursor(context);
  13910. let content;
  13911. // Regular comment.
  13912. const match = /--(\!)?>/.exec(context.source);
  13913. if (!match) {
  13914. content = context.source.slice(4);
  13915. advanceBy(context, context.source.length);
  13916. emitError(context, 7 /* ErrorCodes.EOF_IN_COMMENT */);
  13917. }
  13918. else {
  13919. if (match.index <= 3) {
  13920. emitError(context, 0 /* ErrorCodes.ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
  13921. }
  13922. if (match[1]) {
  13923. emitError(context, 10 /* ErrorCodes.INCORRECTLY_CLOSED_COMMENT */);
  13924. }
  13925. content = context.source.slice(4, match.index);
  13926. // Advancing with reporting nested comments.
  13927. const s = context.source.slice(0, match.index);
  13928. let prevIndex = 1, nestedIndex = 0;
  13929. while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
  13930. advanceBy(context, nestedIndex - prevIndex + 1);
  13931. if (nestedIndex + 4 < s.length) {
  13932. emitError(context, 16 /* ErrorCodes.NESTED_COMMENT */);
  13933. }
  13934. prevIndex = nestedIndex + 1;
  13935. }
  13936. advanceBy(context, match.index + match[0].length - prevIndex + 1);
  13937. }
  13938. return {
  13939. type: 3 /* NodeTypes.COMMENT */,
  13940. content,
  13941. loc: getSelection(context, start)
  13942. };
  13943. }
  13944. function parseBogusComment(context) {
  13945. const start = getCursor(context);
  13946. const contentStart = context.source[1] === '?' ? 1 : 2;
  13947. let content;
  13948. const closeIndex = context.source.indexOf('>');
  13949. if (closeIndex === -1) {
  13950. content = context.source.slice(contentStart);
  13951. advanceBy(context, context.source.length);
  13952. }
  13953. else {
  13954. content = context.source.slice(contentStart, closeIndex);
  13955. advanceBy(context, closeIndex + 1);
  13956. }
  13957. return {
  13958. type: 3 /* NodeTypes.COMMENT */,
  13959. content,
  13960. loc: getSelection(context, start)
  13961. };
  13962. }
  13963. function parseElement(context, ancestors) {
  13964. // Start tag.
  13965. const wasInPre = context.inPre;
  13966. const wasInVPre = context.inVPre;
  13967. const parent = last(ancestors);
  13968. const element = parseTag(context, 0 /* TagType.Start */, parent);
  13969. const isPreBoundary = context.inPre && !wasInPre;
  13970. const isVPreBoundary = context.inVPre && !wasInVPre;
  13971. if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
  13972. // #4030 self-closing <pre> tag
  13973. if (isPreBoundary) {
  13974. context.inPre = false;
  13975. }
  13976. if (isVPreBoundary) {
  13977. context.inVPre = false;
  13978. }
  13979. return element;
  13980. }
  13981. // Children.
  13982. ancestors.push(element);
  13983. const mode = context.options.getTextMode(element, parent);
  13984. const children = parseChildren(context, mode, ancestors);
  13985. ancestors.pop();
  13986. element.children = children;
  13987. // End tag.
  13988. if (startsWithEndTagOpen(context.source, element.tag)) {
  13989. parseTag(context, 1 /* TagType.End */, parent);
  13990. }
  13991. else {
  13992. emitError(context, 24 /* ErrorCodes.X_MISSING_END_TAG */, 0, element.loc.start);
  13993. if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
  13994. const first = children[0];
  13995. if (first && startsWith(first.loc.source, '<!--')) {
  13996. emitError(context, 8 /* ErrorCodes.EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
  13997. }
  13998. }
  13999. }
  14000. element.loc = getSelection(context, element.loc.start);
  14001. if (isPreBoundary) {
  14002. context.inPre = false;
  14003. }
  14004. if (isVPreBoundary) {
  14005. context.inVPre = false;
  14006. }
  14007. return element;
  14008. }
  14009. const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
  14010. function parseTag(context, type, parent) {
  14011. // Tag open.
  14012. const start = getCursor(context);
  14013. const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
  14014. const tag = match[1];
  14015. const ns = context.options.getNamespace(tag, parent);
  14016. advanceBy(context, match[0].length);
  14017. advanceSpaces(context);
  14018. // save current state in case we need to re-parse attributes with v-pre
  14019. const cursor = getCursor(context);
  14020. const currentSource = context.source;
  14021. // check <pre> tag
  14022. if (context.options.isPreTag(tag)) {
  14023. context.inPre = true;
  14024. }
  14025. // Attributes.
  14026. let props = parseAttributes(context, type);
  14027. // check v-pre
  14028. if (type === 0 /* TagType.Start */ &&
  14029. !context.inVPre &&
  14030. props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'pre')) {
  14031. context.inVPre = true;
  14032. // reset context
  14033. extend(context, cursor);
  14034. context.source = currentSource;
  14035. // re-parse attrs and filter out v-pre itself
  14036. props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
  14037. }
  14038. // Tag close.
  14039. let isSelfClosing = false;
  14040. if (context.source.length === 0) {
  14041. emitError(context, 9 /* ErrorCodes.EOF_IN_TAG */);
  14042. }
  14043. else {
  14044. isSelfClosing = startsWith(context.source, '/>');
  14045. if (type === 1 /* TagType.End */ && isSelfClosing) {
  14046. emitError(context, 4 /* ErrorCodes.END_TAG_WITH_TRAILING_SOLIDUS */);
  14047. }
  14048. advanceBy(context, isSelfClosing ? 2 : 1);
  14049. }
  14050. if (type === 1 /* TagType.End */) {
  14051. return;
  14052. }
  14053. let tagType = 0 /* ElementTypes.ELEMENT */;
  14054. if (!context.inVPre) {
  14055. if (tag === 'slot') {
  14056. tagType = 2 /* ElementTypes.SLOT */;
  14057. }
  14058. else if (tag === 'template') {
  14059. if (props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ && isSpecialTemplateDirective(p.name))) {
  14060. tagType = 3 /* ElementTypes.TEMPLATE */;
  14061. }
  14062. }
  14063. else if (isComponent(tag, props, context)) {
  14064. tagType = 1 /* ElementTypes.COMPONENT */;
  14065. }
  14066. }
  14067. return {
  14068. type: 1 /* NodeTypes.ELEMENT */,
  14069. ns,
  14070. tag,
  14071. tagType,
  14072. props,
  14073. isSelfClosing,
  14074. children: [],
  14075. loc: getSelection(context, start),
  14076. codegenNode: undefined // to be created during transform phase
  14077. };
  14078. }
  14079. function isComponent(tag, props, context) {
  14080. const options = context.options;
  14081. if (options.isCustomElement(tag)) {
  14082. return false;
  14083. }
  14084. if (tag === 'component' ||
  14085. /^[A-Z]/.test(tag) ||
  14086. isCoreComponent(tag) ||
  14087. (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
  14088. (options.isNativeTag && !options.isNativeTag(tag))) {
  14089. return true;
  14090. }
  14091. // at this point the tag should be a native tag, but check for potential "is"
  14092. // casting
  14093. for (let i = 0; i < props.length; i++) {
  14094. const p = props[i];
  14095. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  14096. if (p.name === 'is' && p.value) {
  14097. if (p.value.content.startsWith('vue:')) {
  14098. return true;
  14099. }
  14100. }
  14101. }
  14102. else {
  14103. // directive
  14104. // v-is (TODO Deprecate)
  14105. if (p.name === 'is') {
  14106. return true;
  14107. }
  14108. else if (
  14109. // :is on plain element - only treat as component in compat mode
  14110. p.name === 'bind' &&
  14111. isStaticArgOf(p.arg, 'is') &&
  14112. false &&
  14113. checkCompatEnabled("COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */, context, p.loc)) {
  14114. return true;
  14115. }
  14116. }
  14117. }
  14118. }
  14119. function parseAttributes(context, type) {
  14120. const props = [];
  14121. const attributeNames = new Set();
  14122. while (context.source.length > 0 &&
  14123. !startsWith(context.source, '>') &&
  14124. !startsWith(context.source, '/>')) {
  14125. if (startsWith(context.source, '/')) {
  14126. emitError(context, 22 /* ErrorCodes.UNEXPECTED_SOLIDUS_IN_TAG */);
  14127. advanceBy(context, 1);
  14128. advanceSpaces(context);
  14129. continue;
  14130. }
  14131. if (type === 1 /* TagType.End */) {
  14132. emitError(context, 3 /* ErrorCodes.END_TAG_WITH_ATTRIBUTES */);
  14133. }
  14134. const attr = parseAttribute(context, attributeNames);
  14135. // Trim whitespace between class
  14136. // https://github.com/vuejs/core/issues/4251
  14137. if (attr.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  14138. attr.value &&
  14139. attr.name === 'class') {
  14140. attr.value.content = attr.value.content.replace(/\s+/g, ' ').trim();
  14141. }
  14142. if (type === 0 /* TagType.Start */) {
  14143. props.push(attr);
  14144. }
  14145. if (/^[^\t\r\n\f />]/.test(context.source)) {
  14146. emitError(context, 15 /* ErrorCodes.MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
  14147. }
  14148. advanceSpaces(context);
  14149. }
  14150. return props;
  14151. }
  14152. function parseAttribute(context, nameSet) {
  14153. // Name.
  14154. const start = getCursor(context);
  14155. const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
  14156. const name = match[0];
  14157. if (nameSet.has(name)) {
  14158. emitError(context, 2 /* ErrorCodes.DUPLICATE_ATTRIBUTE */);
  14159. }
  14160. nameSet.add(name);
  14161. if (name[0] === '=') {
  14162. emitError(context, 19 /* ErrorCodes.UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
  14163. }
  14164. {
  14165. const pattern = /["'<]/g;
  14166. let m;
  14167. while ((m = pattern.exec(name))) {
  14168. emitError(context, 17 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
  14169. }
  14170. }
  14171. advanceBy(context, name.length);
  14172. // Value
  14173. let value = undefined;
  14174. if (/^[\t\r\n\f ]*=/.test(context.source)) {
  14175. advanceSpaces(context);
  14176. advanceBy(context, 1);
  14177. advanceSpaces(context);
  14178. value = parseAttributeValue(context);
  14179. if (!value) {
  14180. emitError(context, 13 /* ErrorCodes.MISSING_ATTRIBUTE_VALUE */);
  14181. }
  14182. }
  14183. const loc = getSelection(context, start);
  14184. if (!context.inVPre && /^(v-[A-Za-z0-9-]|:|\.|@|#)/.test(name)) {
  14185. const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^\.|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
  14186. let isPropShorthand = startsWith(name, '.');
  14187. let dirName = match[1] ||
  14188. (isPropShorthand || startsWith(name, ':')
  14189. ? 'bind'
  14190. : startsWith(name, '@')
  14191. ? 'on'
  14192. : 'slot');
  14193. let arg;
  14194. if (match[2]) {
  14195. const isSlot = dirName === 'slot';
  14196. const startOffset = name.lastIndexOf(match[2]);
  14197. const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
  14198. let content = match[2];
  14199. let isStatic = true;
  14200. if (content.startsWith('[')) {
  14201. isStatic = false;
  14202. if (!content.endsWith(']')) {
  14203. emitError(context, 27 /* ErrorCodes.X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
  14204. content = content.slice(1);
  14205. }
  14206. else {
  14207. content = content.slice(1, content.length - 1);
  14208. }
  14209. }
  14210. else if (isSlot) {
  14211. // #1241 special case for v-slot: vuetify relies extensively on slot
  14212. // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
  14213. // supports such usage so we are keeping it consistent with 2.x.
  14214. content += match[3] || '';
  14215. }
  14216. arg = {
  14217. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  14218. content,
  14219. isStatic,
  14220. constType: isStatic
  14221. ? 3 /* ConstantTypes.CAN_STRINGIFY */
  14222. : 0 /* ConstantTypes.NOT_CONSTANT */,
  14223. loc
  14224. };
  14225. }
  14226. if (value && value.isQuoted) {
  14227. const valueLoc = value.loc;
  14228. valueLoc.start.offset++;
  14229. valueLoc.start.column++;
  14230. valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
  14231. valueLoc.source = valueLoc.source.slice(1, -1);
  14232. }
  14233. const modifiers = match[3] ? match[3].slice(1).split('.') : [];
  14234. if (isPropShorthand)
  14235. modifiers.push('prop');
  14236. return {
  14237. type: 7 /* NodeTypes.DIRECTIVE */,
  14238. name: dirName,
  14239. exp: value && {
  14240. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  14241. content: value.content,
  14242. isStatic: false,
  14243. // Treat as non-constant by default. This can be potentially set to
  14244. // other values by `transformExpression` to make it eligible for hoisting.
  14245. constType: 0 /* ConstantTypes.NOT_CONSTANT */,
  14246. loc: value.loc
  14247. },
  14248. arg,
  14249. modifiers,
  14250. loc
  14251. };
  14252. }
  14253. // missing directive name or illegal directive name
  14254. if (!context.inVPre && startsWith(name, 'v-')) {
  14255. emitError(context, 26 /* ErrorCodes.X_MISSING_DIRECTIVE_NAME */);
  14256. }
  14257. return {
  14258. type: 6 /* NodeTypes.ATTRIBUTE */,
  14259. name,
  14260. value: value && {
  14261. type: 2 /* NodeTypes.TEXT */,
  14262. content: value.content,
  14263. loc: value.loc
  14264. },
  14265. loc
  14266. };
  14267. }
  14268. function parseAttributeValue(context) {
  14269. const start = getCursor(context);
  14270. let content;
  14271. const quote = context.source[0];
  14272. const isQuoted = quote === `"` || quote === `'`;
  14273. if (isQuoted) {
  14274. // Quoted value.
  14275. advanceBy(context, 1);
  14276. const endIndex = context.source.indexOf(quote);
  14277. if (endIndex === -1) {
  14278. content = parseTextData(context, context.source.length, 4 /* TextModes.ATTRIBUTE_VALUE */);
  14279. }
  14280. else {
  14281. content = parseTextData(context, endIndex, 4 /* TextModes.ATTRIBUTE_VALUE */);
  14282. advanceBy(context, 1);
  14283. }
  14284. }
  14285. else {
  14286. // Unquoted
  14287. const match = /^[^\t\r\n\f >]+/.exec(context.source);
  14288. if (!match) {
  14289. return undefined;
  14290. }
  14291. const unexpectedChars = /["'<=`]/g;
  14292. let m;
  14293. while ((m = unexpectedChars.exec(match[0]))) {
  14294. emitError(context, 18 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
  14295. }
  14296. content = parseTextData(context, match[0].length, 4 /* TextModes.ATTRIBUTE_VALUE */);
  14297. }
  14298. return { content, isQuoted, loc: getSelection(context, start) };
  14299. }
  14300. function parseInterpolation(context, mode) {
  14301. const [open, close] = context.options.delimiters;
  14302. const closeIndex = context.source.indexOf(close, open.length);
  14303. if (closeIndex === -1) {
  14304. emitError(context, 25 /* ErrorCodes.X_MISSING_INTERPOLATION_END */);
  14305. return undefined;
  14306. }
  14307. const start = getCursor(context);
  14308. advanceBy(context, open.length);
  14309. const innerStart = getCursor(context);
  14310. const innerEnd = getCursor(context);
  14311. const rawContentLength = closeIndex - open.length;
  14312. const rawContent = context.source.slice(0, rawContentLength);
  14313. const preTrimContent = parseTextData(context, rawContentLength, mode);
  14314. const content = preTrimContent.trim();
  14315. const startOffset = preTrimContent.indexOf(content);
  14316. if (startOffset > 0) {
  14317. advancePositionWithMutation(innerStart, rawContent, startOffset);
  14318. }
  14319. const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
  14320. advancePositionWithMutation(innerEnd, rawContent, endOffset);
  14321. advanceBy(context, close.length);
  14322. return {
  14323. type: 5 /* NodeTypes.INTERPOLATION */,
  14324. content: {
  14325. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  14326. isStatic: false,
  14327. // Set `isConstant` to false by default and will decide in transformExpression
  14328. constType: 0 /* ConstantTypes.NOT_CONSTANT */,
  14329. content,
  14330. loc: getSelection(context, innerStart, innerEnd)
  14331. },
  14332. loc: getSelection(context, start)
  14333. };
  14334. }
  14335. function parseText(context, mode) {
  14336. const endTokens = mode === 3 /* TextModes.CDATA */ ? [']]>'] : ['<', context.options.delimiters[0]];
  14337. let endIndex = context.source.length;
  14338. for (let i = 0; i < endTokens.length; i++) {
  14339. const index = context.source.indexOf(endTokens[i], 1);
  14340. if (index !== -1 && endIndex > index) {
  14341. endIndex = index;
  14342. }
  14343. }
  14344. const start = getCursor(context);
  14345. const content = parseTextData(context, endIndex, mode);
  14346. return {
  14347. type: 2 /* NodeTypes.TEXT */,
  14348. content,
  14349. loc: getSelection(context, start)
  14350. };
  14351. }
  14352. /**
  14353. * Get text data with a given length from the current location.
  14354. * This translates HTML entities in the text data.
  14355. */
  14356. function parseTextData(context, length, mode) {
  14357. const rawText = context.source.slice(0, length);
  14358. advanceBy(context, length);
  14359. if (mode === 2 /* TextModes.RAWTEXT */ ||
  14360. mode === 3 /* TextModes.CDATA */ ||
  14361. !rawText.includes('&')) {
  14362. return rawText;
  14363. }
  14364. else {
  14365. // DATA or RCDATA containing "&"". Entity decoding required.
  14366. return context.options.decodeEntities(rawText, mode === 4 /* TextModes.ATTRIBUTE_VALUE */);
  14367. }
  14368. }
  14369. function getCursor(context) {
  14370. const { column, line, offset } = context;
  14371. return { column, line, offset };
  14372. }
  14373. function getSelection(context, start, end) {
  14374. end = end || getCursor(context);
  14375. return {
  14376. start,
  14377. end,
  14378. source: context.originalSource.slice(start.offset, end.offset)
  14379. };
  14380. }
  14381. function last(xs) {
  14382. return xs[xs.length - 1];
  14383. }
  14384. function startsWith(source, searchString) {
  14385. return source.startsWith(searchString);
  14386. }
  14387. function advanceBy(context, numberOfCharacters) {
  14388. const { source } = context;
  14389. advancePositionWithMutation(context, source, numberOfCharacters);
  14390. context.source = source.slice(numberOfCharacters);
  14391. }
  14392. function advanceSpaces(context) {
  14393. const match = /^[\t\r\n\f ]+/.exec(context.source);
  14394. if (match) {
  14395. advanceBy(context, match[0].length);
  14396. }
  14397. }
  14398. function getNewPosition(context, start, numberOfCharacters) {
  14399. return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
  14400. }
  14401. function emitError(context, code, offset, loc = getCursor(context)) {
  14402. if (offset) {
  14403. loc.offset += offset;
  14404. loc.column += offset;
  14405. }
  14406. context.options.onError(createCompilerError(code, {
  14407. start: loc,
  14408. end: loc,
  14409. source: ''
  14410. }));
  14411. }
  14412. function isEnd(context, mode, ancestors) {
  14413. const s = context.source;
  14414. switch (mode) {
  14415. case 0 /* TextModes.DATA */:
  14416. if (startsWith(s, '</')) {
  14417. // TODO: probably bad performance
  14418. for (let i = ancestors.length - 1; i >= 0; --i) {
  14419. if (startsWithEndTagOpen(s, ancestors[i].tag)) {
  14420. return true;
  14421. }
  14422. }
  14423. }
  14424. break;
  14425. case 1 /* TextModes.RCDATA */:
  14426. case 2 /* TextModes.RAWTEXT */: {
  14427. const parent = last(ancestors);
  14428. if (parent && startsWithEndTagOpen(s, parent.tag)) {
  14429. return true;
  14430. }
  14431. break;
  14432. }
  14433. case 3 /* TextModes.CDATA */:
  14434. if (startsWith(s, ']]>')) {
  14435. return true;
  14436. }
  14437. break;
  14438. }
  14439. return !s;
  14440. }
  14441. function startsWithEndTagOpen(source, tag) {
  14442. return (startsWith(source, '</') &&
  14443. source.slice(2, 2 + tag.length).toLowerCase() === tag.toLowerCase() &&
  14444. /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
  14445. }
  14446. function hoistStatic(root, context) {
  14447. walk(root, context,
  14448. // Root node is unfortunately non-hoistable due to potential parent
  14449. // fallthrough attributes.
  14450. isSingleElementRoot(root, root.children[0]));
  14451. }
  14452. function isSingleElementRoot(root, child) {
  14453. const { children } = root;
  14454. return (children.length === 1 &&
  14455. child.type === 1 /* NodeTypes.ELEMENT */ &&
  14456. !isSlotOutlet(child));
  14457. }
  14458. function walk(node, context, doNotHoistNode = false) {
  14459. const { children } = node;
  14460. const originalCount = children.length;
  14461. let hoistedCount = 0;
  14462. for (let i = 0; i < children.length; i++) {
  14463. const child = children[i];
  14464. // only plain elements & text calls are eligible for hoisting.
  14465. if (child.type === 1 /* NodeTypes.ELEMENT */ &&
  14466. child.tagType === 0 /* ElementTypes.ELEMENT */) {
  14467. const constantType = doNotHoistNode
  14468. ? 0 /* ConstantTypes.NOT_CONSTANT */
  14469. : getConstantType(child, context);
  14470. if (constantType > 0 /* ConstantTypes.NOT_CONSTANT */) {
  14471. if (constantType >= 2 /* ConstantTypes.CAN_HOIST */) {
  14472. child.codegenNode.patchFlag =
  14473. -1 /* PatchFlags.HOISTED */ + (` /* HOISTED */` );
  14474. child.codegenNode = context.hoist(child.codegenNode);
  14475. hoistedCount++;
  14476. continue;
  14477. }
  14478. }
  14479. else {
  14480. // node may contain dynamic children, but its props may be eligible for
  14481. // hoisting.
  14482. const codegenNode = child.codegenNode;
  14483. if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  14484. const flag = getPatchFlag(codegenNode);
  14485. if ((!flag ||
  14486. flag === 512 /* PatchFlags.NEED_PATCH */ ||
  14487. flag === 1 /* PatchFlags.TEXT */) &&
  14488. getGeneratedPropsConstantType(child, context) >=
  14489. 2 /* ConstantTypes.CAN_HOIST */) {
  14490. const props = getNodeProps(child);
  14491. if (props) {
  14492. codegenNode.props = context.hoist(props);
  14493. }
  14494. }
  14495. if (codegenNode.dynamicProps) {
  14496. codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps);
  14497. }
  14498. }
  14499. }
  14500. }
  14501. // walk further
  14502. if (child.type === 1 /* NodeTypes.ELEMENT */) {
  14503. const isComponent = child.tagType === 1 /* ElementTypes.COMPONENT */;
  14504. if (isComponent) {
  14505. context.scopes.vSlot++;
  14506. }
  14507. walk(child, context);
  14508. if (isComponent) {
  14509. context.scopes.vSlot--;
  14510. }
  14511. }
  14512. else if (child.type === 11 /* NodeTypes.FOR */) {
  14513. // Do not hoist v-for single child because it has to be a block
  14514. walk(child, context, child.children.length === 1);
  14515. }
  14516. else if (child.type === 9 /* NodeTypes.IF */) {
  14517. for (let i = 0; i < child.branches.length; i++) {
  14518. // Do not hoist v-if single child because it has to be a block
  14519. walk(child.branches[i], context, child.branches[i].children.length === 1);
  14520. }
  14521. }
  14522. }
  14523. if (hoistedCount && context.transformHoist) {
  14524. context.transformHoist(children, context, node);
  14525. }
  14526. // all children were hoisted - the entire children array is hoistable.
  14527. if (hoistedCount &&
  14528. hoistedCount === originalCount &&
  14529. node.type === 1 /* NodeTypes.ELEMENT */ &&
  14530. node.tagType === 0 /* ElementTypes.ELEMENT */ &&
  14531. node.codegenNode &&
  14532. node.codegenNode.type === 13 /* NodeTypes.VNODE_CALL */ &&
  14533. isArray(node.codegenNode.children)) {
  14534. node.codegenNode.children = context.hoist(createArrayExpression(node.codegenNode.children));
  14535. }
  14536. }
  14537. function getConstantType(node, context) {
  14538. const { constantCache } = context;
  14539. switch (node.type) {
  14540. case 1 /* NodeTypes.ELEMENT */:
  14541. if (node.tagType !== 0 /* ElementTypes.ELEMENT */) {
  14542. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14543. }
  14544. const cached = constantCache.get(node);
  14545. if (cached !== undefined) {
  14546. return cached;
  14547. }
  14548. const codegenNode = node.codegenNode;
  14549. if (codegenNode.type !== 13 /* NodeTypes.VNODE_CALL */) {
  14550. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14551. }
  14552. if (codegenNode.isBlock &&
  14553. node.tag !== 'svg' &&
  14554. node.tag !== 'foreignObject') {
  14555. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14556. }
  14557. const flag = getPatchFlag(codegenNode);
  14558. if (!flag) {
  14559. let returnType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  14560. // Element itself has no patch flag. However we still need to check:
  14561. // 1. Even for a node with no patch flag, it is possible for it to contain
  14562. // non-hoistable expressions that refers to scope variables, e.g. compiler
  14563. // injected keys or cached event handlers. Therefore we need to always
  14564. // check the codegenNode's props to be sure.
  14565. const generatedPropsType = getGeneratedPropsConstantType(node, context);
  14566. if (generatedPropsType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  14567. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  14568. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14569. }
  14570. if (generatedPropsType < returnType) {
  14571. returnType = generatedPropsType;
  14572. }
  14573. // 2. its children.
  14574. for (let i = 0; i < node.children.length; i++) {
  14575. const childType = getConstantType(node.children[i], context);
  14576. if (childType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  14577. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  14578. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14579. }
  14580. if (childType < returnType) {
  14581. returnType = childType;
  14582. }
  14583. }
  14584. // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
  14585. // type, check if any of the props can cause the type to be lowered
  14586. // we can skip can_patch because it's guaranteed by the absence of a
  14587. // patchFlag.
  14588. if (returnType > 1 /* ConstantTypes.CAN_SKIP_PATCH */) {
  14589. for (let i = 0; i < node.props.length; i++) {
  14590. const p = node.props[i];
  14591. if (p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'bind' && p.exp) {
  14592. const expType = getConstantType(p.exp, context);
  14593. if (expType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  14594. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  14595. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14596. }
  14597. if (expType < returnType) {
  14598. returnType = expType;
  14599. }
  14600. }
  14601. }
  14602. }
  14603. // only svg/foreignObject could be block here, however if they are
  14604. // static then they don't need to be blocks since there will be no
  14605. // nested updates.
  14606. if (codegenNode.isBlock) {
  14607. // except set custom directives.
  14608. for (let i = 0; i < node.props.length; i++) {
  14609. const p = node.props[i];
  14610. if (p.type === 7 /* NodeTypes.DIRECTIVE */) {
  14611. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  14612. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14613. }
  14614. }
  14615. context.removeHelper(OPEN_BLOCK);
  14616. context.removeHelper(getVNodeBlockHelper(context.inSSR, codegenNode.isComponent));
  14617. codegenNode.isBlock = false;
  14618. context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent));
  14619. }
  14620. constantCache.set(node, returnType);
  14621. return returnType;
  14622. }
  14623. else {
  14624. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  14625. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14626. }
  14627. case 2 /* NodeTypes.TEXT */:
  14628. case 3 /* NodeTypes.COMMENT */:
  14629. return 3 /* ConstantTypes.CAN_STRINGIFY */;
  14630. case 9 /* NodeTypes.IF */:
  14631. case 11 /* NodeTypes.FOR */:
  14632. case 10 /* NodeTypes.IF_BRANCH */:
  14633. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14634. case 5 /* NodeTypes.INTERPOLATION */:
  14635. case 12 /* NodeTypes.TEXT_CALL */:
  14636. return getConstantType(node.content, context);
  14637. case 4 /* NodeTypes.SIMPLE_EXPRESSION */:
  14638. return node.constType;
  14639. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  14640. let returnType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  14641. for (let i = 0; i < node.children.length; i++) {
  14642. const child = node.children[i];
  14643. if (isString(child) || isSymbol(child)) {
  14644. continue;
  14645. }
  14646. const childType = getConstantType(child, context);
  14647. if (childType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  14648. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14649. }
  14650. else if (childType < returnType) {
  14651. returnType = childType;
  14652. }
  14653. }
  14654. return returnType;
  14655. default:
  14656. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14657. }
  14658. }
  14659. const allowHoistedHelperSet = new Set([
  14660. NORMALIZE_CLASS,
  14661. NORMALIZE_STYLE,
  14662. NORMALIZE_PROPS,
  14663. GUARD_REACTIVE_PROPS
  14664. ]);
  14665. function getConstantTypeOfHelperCall(value, context) {
  14666. if (value.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */ &&
  14667. !isString(value.callee) &&
  14668. allowHoistedHelperSet.has(value.callee)) {
  14669. const arg = value.arguments[0];
  14670. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  14671. return getConstantType(arg, context);
  14672. }
  14673. else if (arg.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  14674. // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(exp))`
  14675. return getConstantTypeOfHelperCall(arg, context);
  14676. }
  14677. }
  14678. return 0 /* ConstantTypes.NOT_CONSTANT */;
  14679. }
  14680. function getGeneratedPropsConstantType(node, context) {
  14681. let returnType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  14682. const props = getNodeProps(node);
  14683. if (props && props.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
  14684. const { properties } = props;
  14685. for (let i = 0; i < properties.length; i++) {
  14686. const { key, value } = properties[i];
  14687. const keyType = getConstantType(key, context);
  14688. if (keyType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  14689. return keyType;
  14690. }
  14691. if (keyType < returnType) {
  14692. returnType = keyType;
  14693. }
  14694. let valueType;
  14695. if (value.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  14696. valueType = getConstantType(value, context);
  14697. }
  14698. else if (value.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  14699. // some helper calls can be hoisted,
  14700. // such as the `normalizeProps` generated by the compiler for pre-normalize class,
  14701. // in this case we need to respect the ConstantType of the helper's arguments
  14702. valueType = getConstantTypeOfHelperCall(value, context);
  14703. }
  14704. else {
  14705. valueType = 0 /* ConstantTypes.NOT_CONSTANT */;
  14706. }
  14707. if (valueType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  14708. return valueType;
  14709. }
  14710. if (valueType < returnType) {
  14711. returnType = valueType;
  14712. }
  14713. }
  14714. }
  14715. return returnType;
  14716. }
  14717. function getNodeProps(node) {
  14718. const codegenNode = node.codegenNode;
  14719. if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  14720. return codegenNode.props;
  14721. }
  14722. }
  14723. function getPatchFlag(node) {
  14724. const flag = node.patchFlag;
  14725. return flag ? parseInt(flag, 10) : undefined;
  14726. }
  14727. 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 }) {
  14728. const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
  14729. const context = {
  14730. // options
  14731. selfName: nameMatch && capitalize(camelize(nameMatch[1])),
  14732. prefixIdentifiers,
  14733. hoistStatic,
  14734. cacheHandlers,
  14735. nodeTransforms,
  14736. directiveTransforms,
  14737. transformHoist,
  14738. isBuiltInComponent,
  14739. isCustomElement,
  14740. expressionPlugins,
  14741. scopeId,
  14742. slotted,
  14743. ssr,
  14744. inSSR,
  14745. ssrCssVars,
  14746. bindingMetadata,
  14747. inline,
  14748. isTS,
  14749. onError,
  14750. onWarn,
  14751. compatConfig,
  14752. // state
  14753. root,
  14754. helpers: new Map(),
  14755. components: new Set(),
  14756. directives: new Set(),
  14757. hoists: [],
  14758. imports: [],
  14759. constantCache: new Map(),
  14760. temps: 0,
  14761. cached: 0,
  14762. identifiers: Object.create(null),
  14763. scopes: {
  14764. vFor: 0,
  14765. vSlot: 0,
  14766. vPre: 0,
  14767. vOnce: 0
  14768. },
  14769. parent: null,
  14770. currentNode: root,
  14771. childIndex: 0,
  14772. inVOnce: false,
  14773. // methods
  14774. helper(name) {
  14775. const count = context.helpers.get(name) || 0;
  14776. context.helpers.set(name, count + 1);
  14777. return name;
  14778. },
  14779. removeHelper(name) {
  14780. const count = context.helpers.get(name);
  14781. if (count) {
  14782. const currentCount = count - 1;
  14783. if (!currentCount) {
  14784. context.helpers.delete(name);
  14785. }
  14786. else {
  14787. context.helpers.set(name, currentCount);
  14788. }
  14789. }
  14790. },
  14791. helperString(name) {
  14792. return `_${helperNameMap[context.helper(name)]}`;
  14793. },
  14794. replaceNode(node) {
  14795. /* istanbul ignore if */
  14796. {
  14797. if (!context.currentNode) {
  14798. throw new Error(`Node being replaced is already removed.`);
  14799. }
  14800. if (!context.parent) {
  14801. throw new Error(`Cannot replace root node.`);
  14802. }
  14803. }
  14804. context.parent.children[context.childIndex] = context.currentNode = node;
  14805. },
  14806. removeNode(node) {
  14807. if (!context.parent) {
  14808. throw new Error(`Cannot remove root node.`);
  14809. }
  14810. const list = context.parent.children;
  14811. const removalIndex = node
  14812. ? list.indexOf(node)
  14813. : context.currentNode
  14814. ? context.childIndex
  14815. : -1;
  14816. /* istanbul ignore if */
  14817. if (removalIndex < 0) {
  14818. throw new Error(`node being removed is not a child of current parent`);
  14819. }
  14820. if (!node || node === context.currentNode) {
  14821. // current node removed
  14822. context.currentNode = null;
  14823. context.onNodeRemoved();
  14824. }
  14825. else {
  14826. // sibling node removed
  14827. if (context.childIndex > removalIndex) {
  14828. context.childIndex--;
  14829. context.onNodeRemoved();
  14830. }
  14831. }
  14832. context.parent.children.splice(removalIndex, 1);
  14833. },
  14834. onNodeRemoved: () => { },
  14835. addIdentifiers(exp) {
  14836. // identifier tracking only happens in non-browser builds.
  14837. {
  14838. if (isString(exp)) {
  14839. addId(exp);
  14840. }
  14841. else if (exp.identifiers) {
  14842. exp.identifiers.forEach(addId);
  14843. }
  14844. else if (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  14845. addId(exp.content);
  14846. }
  14847. }
  14848. },
  14849. removeIdentifiers(exp) {
  14850. {
  14851. if (isString(exp)) {
  14852. removeId(exp);
  14853. }
  14854. else if (exp.identifiers) {
  14855. exp.identifiers.forEach(removeId);
  14856. }
  14857. else if (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  14858. removeId(exp.content);
  14859. }
  14860. }
  14861. },
  14862. hoist(exp) {
  14863. if (isString(exp))
  14864. exp = createSimpleExpression(exp);
  14865. context.hoists.push(exp);
  14866. const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* ConstantTypes.CAN_HOIST */);
  14867. identifier.hoisted = exp;
  14868. return identifier;
  14869. },
  14870. cache(exp, isVNode = false) {
  14871. return createCacheExpression(context.cached++, exp, isVNode);
  14872. }
  14873. };
  14874. function addId(id) {
  14875. const { identifiers } = context;
  14876. if (identifiers[id] === undefined) {
  14877. identifiers[id] = 0;
  14878. }
  14879. identifiers[id]++;
  14880. }
  14881. function removeId(id) {
  14882. context.identifiers[id]--;
  14883. }
  14884. return context;
  14885. }
  14886. function transform(root, options) {
  14887. const context = createTransformContext(root, options);
  14888. traverseNode(root, context);
  14889. if (options.hoistStatic) {
  14890. hoistStatic(root, context);
  14891. }
  14892. if (!options.ssr) {
  14893. createRootCodegen(root, context);
  14894. }
  14895. // finalize meta information
  14896. root.helpers = [...context.helpers.keys()];
  14897. root.components = [...context.components];
  14898. root.directives = [...context.directives];
  14899. root.imports = context.imports;
  14900. root.hoists = context.hoists;
  14901. root.temps = context.temps;
  14902. root.cached = context.cached;
  14903. }
  14904. function createRootCodegen(root, context) {
  14905. const { helper } = context;
  14906. const { children } = root;
  14907. if (children.length === 1) {
  14908. const child = children[0];
  14909. // if the single child is an element, turn it into a block.
  14910. if (isSingleElementRoot(root, child) && child.codegenNode) {
  14911. // single element root is never hoisted so codegenNode will never be
  14912. // SimpleExpressionNode
  14913. const codegenNode = child.codegenNode;
  14914. if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  14915. makeBlock(codegenNode, context);
  14916. }
  14917. root.codegenNode = codegenNode;
  14918. }
  14919. else {
  14920. // - single <slot/>, IfNode, ForNode: already blocks.
  14921. // - single text node: always patched.
  14922. // root codegen falls through via genNode()
  14923. root.codegenNode = child;
  14924. }
  14925. }
  14926. else if (children.length > 1) {
  14927. // root has multiple nodes - return a fragment block.
  14928. let patchFlag = 64 /* PatchFlags.STABLE_FRAGMENT */;
  14929. let patchFlagText = PatchFlagNames[64 /* PatchFlags.STABLE_FRAGMENT */];
  14930. // check if the fragment actually contains a single valid child with
  14931. // the rest being comments
  14932. if (children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */).length === 1) {
  14933. patchFlag |= 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */;
  14934. patchFlagText += `, ${PatchFlagNames[2048 /* PatchFlags.DEV_ROOT_FRAGMENT */]}`;
  14935. }
  14936. root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, undefined, false /* isComponent */);
  14937. }
  14938. else ;
  14939. }
  14940. function traverseChildren(parent, context) {
  14941. let i = 0;
  14942. const nodeRemoved = () => {
  14943. i--;
  14944. };
  14945. for (; i < parent.children.length; i++) {
  14946. const child = parent.children[i];
  14947. if (isString(child))
  14948. continue;
  14949. context.parent = parent;
  14950. context.childIndex = i;
  14951. context.onNodeRemoved = nodeRemoved;
  14952. traverseNode(child, context);
  14953. }
  14954. }
  14955. function traverseNode(node, context) {
  14956. context.currentNode = node;
  14957. // apply transform plugins
  14958. const { nodeTransforms } = context;
  14959. const exitFns = [];
  14960. for (let i = 0; i < nodeTransforms.length; i++) {
  14961. const onExit = nodeTransforms[i](node, context);
  14962. if (onExit) {
  14963. if (isArray(onExit)) {
  14964. exitFns.push(...onExit);
  14965. }
  14966. else {
  14967. exitFns.push(onExit);
  14968. }
  14969. }
  14970. if (!context.currentNode) {
  14971. // node was removed
  14972. return;
  14973. }
  14974. else {
  14975. // node may have been replaced
  14976. node = context.currentNode;
  14977. }
  14978. }
  14979. switch (node.type) {
  14980. case 3 /* NodeTypes.COMMENT */:
  14981. if (!context.ssr) {
  14982. // inject import for the Comment symbol, which is needed for creating
  14983. // comment nodes with `createVNode`
  14984. context.helper(CREATE_COMMENT);
  14985. }
  14986. break;
  14987. case 5 /* NodeTypes.INTERPOLATION */:
  14988. // no need to traverse, but we need to inject toString helper
  14989. if (!context.ssr) {
  14990. context.helper(TO_DISPLAY_STRING);
  14991. }
  14992. break;
  14993. // for container types, further traverse downwards
  14994. case 9 /* NodeTypes.IF */:
  14995. for (let i = 0; i < node.branches.length; i++) {
  14996. traverseNode(node.branches[i], context);
  14997. }
  14998. break;
  14999. case 10 /* NodeTypes.IF_BRANCH */:
  15000. case 11 /* NodeTypes.FOR */:
  15001. case 1 /* NodeTypes.ELEMENT */:
  15002. case 0 /* NodeTypes.ROOT */:
  15003. traverseChildren(node, context);
  15004. break;
  15005. }
  15006. // exit transforms
  15007. context.currentNode = node;
  15008. let i = exitFns.length;
  15009. while (i--) {
  15010. exitFns[i]();
  15011. }
  15012. }
  15013. function createStructuralDirectiveTransform(name, fn) {
  15014. const matches = isString(name)
  15015. ? (n) => n === name
  15016. : (n) => name.test(n);
  15017. return (node, context) => {
  15018. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  15019. const { props } = node;
  15020. // structural directive transforms are not concerned with slots
  15021. // as they are handled separately in vSlot.ts
  15022. if (node.tagType === 3 /* ElementTypes.TEMPLATE */ && props.some(isVSlot)) {
  15023. return;
  15024. }
  15025. const exitFns = [];
  15026. for (let i = 0; i < props.length; i++) {
  15027. const prop = props[i];
  15028. if (prop.type === 7 /* NodeTypes.DIRECTIVE */ && matches(prop.name)) {
  15029. // structural directives are removed to avoid infinite recursion
  15030. // also we remove them *before* applying so that it can further
  15031. // traverse itself in case it moves the node around
  15032. props.splice(i, 1);
  15033. i--;
  15034. const onExit = fn(node, prop, context);
  15035. if (onExit)
  15036. exitFns.push(onExit);
  15037. }
  15038. }
  15039. return exitFns;
  15040. }
  15041. };
  15042. }
  15043. /* -*- Mode: js; js-indent-level: 2; -*- */
  15044. /*
  15045. * Copyright 2011 Mozilla Foundation and contributors
  15046. * Licensed under the New BSD license. See LICENSE or:
  15047. * http://opensource.org/licenses/BSD-3-Clause
  15048. */
  15049. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  15050. /**
  15051. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  15052. */
  15053. var encode = function (number) {
  15054. if (0 <= number && number < intToCharMap.length) {
  15055. return intToCharMap[number];
  15056. }
  15057. throw new TypeError("Must be between 0 and 63: " + number);
  15058. };
  15059. /**
  15060. * Decode a single base 64 character code digit to an integer. Returns -1 on
  15061. * failure.
  15062. */
  15063. var decode = function (charCode) {
  15064. var bigA = 65; // 'A'
  15065. var bigZ = 90; // 'Z'
  15066. var littleA = 97; // 'a'
  15067. var littleZ = 122; // 'z'
  15068. var zero = 48; // '0'
  15069. var nine = 57; // '9'
  15070. var plus = 43; // '+'
  15071. var slash = 47; // '/'
  15072. var littleOffset = 26;
  15073. var numberOffset = 52;
  15074. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  15075. if (bigA <= charCode && charCode <= bigZ) {
  15076. return (charCode - bigA);
  15077. }
  15078. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  15079. if (littleA <= charCode && charCode <= littleZ) {
  15080. return (charCode - littleA + littleOffset);
  15081. }
  15082. // 52 - 61: 0123456789
  15083. if (zero <= charCode && charCode <= nine) {
  15084. return (charCode - zero + numberOffset);
  15085. }
  15086. // 62: +
  15087. if (charCode == plus) {
  15088. return 62;
  15089. }
  15090. // 63: /
  15091. if (charCode == slash) {
  15092. return 63;
  15093. }
  15094. // Invalid base64 digit.
  15095. return -1;
  15096. };
  15097. var base64 = {
  15098. encode: encode,
  15099. decode: decode
  15100. };
  15101. /* -*- Mode: js; js-indent-level: 2; -*- */
  15102. /*
  15103. * Copyright 2011 Mozilla Foundation and contributors
  15104. * Licensed under the New BSD license. See LICENSE or:
  15105. * http://opensource.org/licenses/BSD-3-Clause
  15106. *
  15107. * Based on the Base 64 VLQ implementation in Closure Compiler:
  15108. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  15109. *
  15110. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  15111. * Redistribution and use in source and binary forms, with or without
  15112. * modification, are permitted provided that the following conditions are
  15113. * met:
  15114. *
  15115. * * Redistributions of source code must retain the above copyright
  15116. * notice, this list of conditions and the following disclaimer.
  15117. * * Redistributions in binary form must reproduce the above
  15118. * copyright notice, this list of conditions and the following
  15119. * disclaimer in the documentation and/or other materials provided
  15120. * with the distribution.
  15121. * * Neither the name of Google Inc. nor the names of its
  15122. * contributors may be used to endorse or promote products derived
  15123. * from this software without specific prior written permission.
  15124. *
  15125. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  15126. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  15127. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  15128. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  15129. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  15130. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  15131. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  15132. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  15133. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  15134. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  15135. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  15136. */
  15137. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  15138. // length quantities we use in the source map spec, the first bit is the sign,
  15139. // the next four bits are the actual value, and the 6th bit is the
  15140. // continuation bit. The continuation bit tells us whether there are more
  15141. // digits in this value following this digit.
  15142. //
  15143. // Continuation
  15144. // | Sign
  15145. // | |
  15146. // V V
  15147. // 101011
  15148. var VLQ_BASE_SHIFT = 5;
  15149. // binary: 100000
  15150. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  15151. // binary: 011111
  15152. var VLQ_BASE_MASK = VLQ_BASE - 1;
  15153. // binary: 100000
  15154. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  15155. /**
  15156. * Converts from a two-complement value to a value where the sign bit is
  15157. * placed in the least significant bit. For example, as decimals:
  15158. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  15159. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  15160. */
  15161. function toVLQSigned(aValue) {
  15162. return aValue < 0
  15163. ? ((-aValue) << 1) + 1
  15164. : (aValue << 1) + 0;
  15165. }
  15166. /**
  15167. * Converts to a two-complement value from a value where the sign bit is
  15168. * placed in the least significant bit. For example, as decimals:
  15169. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  15170. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  15171. */
  15172. function fromVLQSigned(aValue) {
  15173. var isNegative = (aValue & 1) === 1;
  15174. var shifted = aValue >> 1;
  15175. return isNegative
  15176. ? -shifted
  15177. : shifted;
  15178. }
  15179. /**
  15180. * Returns the base 64 VLQ encoded value.
  15181. */
  15182. var encode$1 = function base64VLQ_encode(aValue) {
  15183. var encoded = "";
  15184. var digit;
  15185. var vlq = toVLQSigned(aValue);
  15186. do {
  15187. digit = vlq & VLQ_BASE_MASK;
  15188. vlq >>>= VLQ_BASE_SHIFT;
  15189. if (vlq > 0) {
  15190. // There are still more digits in this value, so we must make sure the
  15191. // continuation bit is marked.
  15192. digit |= VLQ_CONTINUATION_BIT;
  15193. }
  15194. encoded += base64.encode(digit);
  15195. } while (vlq > 0);
  15196. return encoded;
  15197. };
  15198. /**
  15199. * Decodes the next base 64 VLQ value from the given string and returns the
  15200. * value and the rest of the string via the out parameter.
  15201. */
  15202. var decode$1 = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  15203. var strLen = aStr.length;
  15204. var result = 0;
  15205. var shift = 0;
  15206. var continuation, digit;
  15207. do {
  15208. if (aIndex >= strLen) {
  15209. throw new Error("Expected more digits in base 64 VLQ value.");
  15210. }
  15211. digit = base64.decode(aStr.charCodeAt(aIndex++));
  15212. if (digit === -1) {
  15213. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  15214. }
  15215. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  15216. digit &= VLQ_BASE_MASK;
  15217. result = result + (digit << shift);
  15218. shift += VLQ_BASE_SHIFT;
  15219. } while (continuation);
  15220. aOutParam.value = fromVLQSigned(result);
  15221. aOutParam.rest = aIndex;
  15222. };
  15223. var base64Vlq = {
  15224. encode: encode$1,
  15225. decode: decode$1
  15226. };
  15227. function getDefaultExportFromCjs (x) {
  15228. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  15229. }
  15230. function getAugmentedNamespace(n) {
  15231. if (n.__esModule) return n;
  15232. var a = Object.defineProperty({}, '__esModule', {value: true});
  15233. Object.keys(n).forEach(function (k) {
  15234. var d = Object.getOwnPropertyDescriptor(n, k);
  15235. Object.defineProperty(a, k, d.get ? d : {
  15236. enumerable: true,
  15237. get: function () {
  15238. return n[k];
  15239. }
  15240. });
  15241. });
  15242. return a;
  15243. }
  15244. function createCommonjsModule(fn) {
  15245. var module = { exports: {} };
  15246. return fn(module, module.exports), module.exports;
  15247. }
  15248. /* -*- Mode: js; js-indent-level: 2; -*- */
  15249. var util = createCommonjsModule(function (module, exports) {
  15250. /*
  15251. * Copyright 2011 Mozilla Foundation and contributors
  15252. * Licensed under the New BSD license. See LICENSE or:
  15253. * http://opensource.org/licenses/BSD-3-Clause
  15254. */
  15255. /**
  15256. * This is a helper function for getting values from parameter/options
  15257. * objects.
  15258. *
  15259. * @param args The object we are extracting values from
  15260. * @param name The name of the property we are getting.
  15261. * @param defaultValue An optional value to return if the property is missing
  15262. * from the object. If this is not specified and the property is missing, an
  15263. * error will be thrown.
  15264. */
  15265. function getArg(aArgs, aName, aDefaultValue) {
  15266. if (aName in aArgs) {
  15267. return aArgs[aName];
  15268. } else if (arguments.length === 3) {
  15269. return aDefaultValue;
  15270. } else {
  15271. throw new Error('"' + aName + '" is a required argument.');
  15272. }
  15273. }
  15274. exports.getArg = getArg;
  15275. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  15276. var dataUrlRegexp = /^data:.+\,.+$/;
  15277. function urlParse(aUrl) {
  15278. var match = aUrl.match(urlRegexp);
  15279. if (!match) {
  15280. return null;
  15281. }
  15282. return {
  15283. scheme: match[1],
  15284. auth: match[2],
  15285. host: match[3],
  15286. port: match[4],
  15287. path: match[5]
  15288. };
  15289. }
  15290. exports.urlParse = urlParse;
  15291. function urlGenerate(aParsedUrl) {
  15292. var url = '';
  15293. if (aParsedUrl.scheme) {
  15294. url += aParsedUrl.scheme + ':';
  15295. }
  15296. url += '//';
  15297. if (aParsedUrl.auth) {
  15298. url += aParsedUrl.auth + '@';
  15299. }
  15300. if (aParsedUrl.host) {
  15301. url += aParsedUrl.host;
  15302. }
  15303. if (aParsedUrl.port) {
  15304. url += ":" + aParsedUrl.port;
  15305. }
  15306. if (aParsedUrl.path) {
  15307. url += aParsedUrl.path;
  15308. }
  15309. return url;
  15310. }
  15311. exports.urlGenerate = urlGenerate;
  15312. /**
  15313. * Normalizes a path, or the path portion of a URL:
  15314. *
  15315. * - Replaces consecutive slashes with one slash.
  15316. * - Removes unnecessary '.' parts.
  15317. * - Removes unnecessary '<dir>/..' parts.
  15318. *
  15319. * Based on code in the Node.js 'path' core module.
  15320. *
  15321. * @param aPath The path or url to normalize.
  15322. */
  15323. function normalize(aPath) {
  15324. var path = aPath;
  15325. var url = urlParse(aPath);
  15326. if (url) {
  15327. if (!url.path) {
  15328. return aPath;
  15329. }
  15330. path = url.path;
  15331. }
  15332. var isAbsolute = exports.isAbsolute(path);
  15333. var parts = path.split(/\/+/);
  15334. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  15335. part = parts[i];
  15336. if (part === '.') {
  15337. parts.splice(i, 1);
  15338. } else if (part === '..') {
  15339. up++;
  15340. } else if (up > 0) {
  15341. if (part === '') {
  15342. // The first part is blank if the path is absolute. Trying to go
  15343. // above the root is a no-op. Therefore we can remove all '..' parts
  15344. // directly after the root.
  15345. parts.splice(i + 1, up);
  15346. up = 0;
  15347. } else {
  15348. parts.splice(i, 2);
  15349. up--;
  15350. }
  15351. }
  15352. }
  15353. path = parts.join('/');
  15354. if (path === '') {
  15355. path = isAbsolute ? '/' : '.';
  15356. }
  15357. if (url) {
  15358. url.path = path;
  15359. return urlGenerate(url);
  15360. }
  15361. return path;
  15362. }
  15363. exports.normalize = normalize;
  15364. /**
  15365. * Joins two paths/URLs.
  15366. *
  15367. * @param aRoot The root path or URL.
  15368. * @param aPath The path or URL to be joined with the root.
  15369. *
  15370. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  15371. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  15372. * first.
  15373. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  15374. * is updated with the result and aRoot is returned. Otherwise the result
  15375. * is returned.
  15376. * - If aPath is absolute, the result is aPath.
  15377. * - Otherwise the two paths are joined with a slash.
  15378. * - Joining for example 'http://' and 'www.example.com' is also supported.
  15379. */
  15380. function join(aRoot, aPath) {
  15381. if (aRoot === "") {
  15382. aRoot = ".";
  15383. }
  15384. if (aPath === "") {
  15385. aPath = ".";
  15386. }
  15387. var aPathUrl = urlParse(aPath);
  15388. var aRootUrl = urlParse(aRoot);
  15389. if (aRootUrl) {
  15390. aRoot = aRootUrl.path || '/';
  15391. }
  15392. // `join(foo, '//www.example.org')`
  15393. if (aPathUrl && !aPathUrl.scheme) {
  15394. if (aRootUrl) {
  15395. aPathUrl.scheme = aRootUrl.scheme;
  15396. }
  15397. return urlGenerate(aPathUrl);
  15398. }
  15399. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  15400. return aPath;
  15401. }
  15402. // `join('http://', 'www.example.com')`
  15403. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  15404. aRootUrl.host = aPath;
  15405. return urlGenerate(aRootUrl);
  15406. }
  15407. var joined = aPath.charAt(0) === '/'
  15408. ? aPath
  15409. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  15410. if (aRootUrl) {
  15411. aRootUrl.path = joined;
  15412. return urlGenerate(aRootUrl);
  15413. }
  15414. return joined;
  15415. }
  15416. exports.join = join;
  15417. exports.isAbsolute = function (aPath) {
  15418. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  15419. };
  15420. /**
  15421. * Make a path relative to a URL or another path.
  15422. *
  15423. * @param aRoot The root path or URL.
  15424. * @param aPath The path or URL to be made relative to aRoot.
  15425. */
  15426. function relative(aRoot, aPath) {
  15427. if (aRoot === "") {
  15428. aRoot = ".";
  15429. }
  15430. aRoot = aRoot.replace(/\/$/, '');
  15431. // It is possible for the path to be above the root. In this case, simply
  15432. // checking whether the root is a prefix of the path won't work. Instead, we
  15433. // need to remove components from the root one by one, until either we find
  15434. // a prefix that fits, or we run out of components to remove.
  15435. var level = 0;
  15436. while (aPath.indexOf(aRoot + '/') !== 0) {
  15437. var index = aRoot.lastIndexOf("/");
  15438. if (index < 0) {
  15439. return aPath;
  15440. }
  15441. // If the only part of the root that is left is the scheme (i.e. http://,
  15442. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  15443. // have exhausted all components, so the path is not relative to the root.
  15444. aRoot = aRoot.slice(0, index);
  15445. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  15446. return aPath;
  15447. }
  15448. ++level;
  15449. }
  15450. // Make sure we add a "../" for each component we removed from the root.
  15451. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  15452. }
  15453. exports.relative = relative;
  15454. var supportsNullProto = (function () {
  15455. var obj = Object.create(null);
  15456. return !('__proto__' in obj);
  15457. }());
  15458. function identity (s) {
  15459. return s;
  15460. }
  15461. /**
  15462. * Because behavior goes wacky when you set `__proto__` on objects, we
  15463. * have to prefix all the strings in our set with an arbitrary character.
  15464. *
  15465. * See https://github.com/mozilla/source-map/pull/31 and
  15466. * https://github.com/mozilla/source-map/issues/30
  15467. *
  15468. * @param String aStr
  15469. */
  15470. function toSetString(aStr) {
  15471. if (isProtoString(aStr)) {
  15472. return '$' + aStr;
  15473. }
  15474. return aStr;
  15475. }
  15476. exports.toSetString = supportsNullProto ? identity : toSetString;
  15477. function fromSetString(aStr) {
  15478. if (isProtoString(aStr)) {
  15479. return aStr.slice(1);
  15480. }
  15481. return aStr;
  15482. }
  15483. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  15484. function isProtoString(s) {
  15485. if (!s) {
  15486. return false;
  15487. }
  15488. var length = s.length;
  15489. if (length < 9 /* "__proto__".length */) {
  15490. return false;
  15491. }
  15492. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  15493. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  15494. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  15495. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  15496. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  15497. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  15498. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  15499. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  15500. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  15501. return false;
  15502. }
  15503. for (var i = length - 10; i >= 0; i--) {
  15504. if (s.charCodeAt(i) !== 36 /* '$' */) {
  15505. return false;
  15506. }
  15507. }
  15508. return true;
  15509. }
  15510. /**
  15511. * Comparator between two mappings where the original positions are compared.
  15512. *
  15513. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  15514. * mappings with the same original source/line/column, but different generated
  15515. * line and column the same. Useful when searching for a mapping with a
  15516. * stubbed out mapping.
  15517. */
  15518. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  15519. var cmp = strcmp(mappingA.source, mappingB.source);
  15520. if (cmp !== 0) {
  15521. return cmp;
  15522. }
  15523. cmp = mappingA.originalLine - mappingB.originalLine;
  15524. if (cmp !== 0) {
  15525. return cmp;
  15526. }
  15527. cmp = mappingA.originalColumn - mappingB.originalColumn;
  15528. if (cmp !== 0 || onlyCompareOriginal) {
  15529. return cmp;
  15530. }
  15531. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  15532. if (cmp !== 0) {
  15533. return cmp;
  15534. }
  15535. cmp = mappingA.generatedLine - mappingB.generatedLine;
  15536. if (cmp !== 0) {
  15537. return cmp;
  15538. }
  15539. return strcmp(mappingA.name, mappingB.name);
  15540. }
  15541. exports.compareByOriginalPositions = compareByOriginalPositions;
  15542. /**
  15543. * Comparator between two mappings with deflated source and name indices where
  15544. * the generated positions are compared.
  15545. *
  15546. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  15547. * mappings with the same generated line and column, but different
  15548. * source/name/original line and column the same. Useful when searching for a
  15549. * mapping with a stubbed out mapping.
  15550. */
  15551. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  15552. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  15553. if (cmp !== 0) {
  15554. return cmp;
  15555. }
  15556. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  15557. if (cmp !== 0 || onlyCompareGenerated) {
  15558. return cmp;
  15559. }
  15560. cmp = strcmp(mappingA.source, mappingB.source);
  15561. if (cmp !== 0) {
  15562. return cmp;
  15563. }
  15564. cmp = mappingA.originalLine - mappingB.originalLine;
  15565. if (cmp !== 0) {
  15566. return cmp;
  15567. }
  15568. cmp = mappingA.originalColumn - mappingB.originalColumn;
  15569. if (cmp !== 0) {
  15570. return cmp;
  15571. }
  15572. return strcmp(mappingA.name, mappingB.name);
  15573. }
  15574. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  15575. function strcmp(aStr1, aStr2) {
  15576. if (aStr1 === aStr2) {
  15577. return 0;
  15578. }
  15579. if (aStr1 === null) {
  15580. return 1; // aStr2 !== null
  15581. }
  15582. if (aStr2 === null) {
  15583. return -1; // aStr1 !== null
  15584. }
  15585. if (aStr1 > aStr2) {
  15586. return 1;
  15587. }
  15588. return -1;
  15589. }
  15590. /**
  15591. * Comparator between two mappings with inflated source and name strings where
  15592. * the generated positions are compared.
  15593. */
  15594. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  15595. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  15596. if (cmp !== 0) {
  15597. return cmp;
  15598. }
  15599. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  15600. if (cmp !== 0) {
  15601. return cmp;
  15602. }
  15603. cmp = strcmp(mappingA.source, mappingB.source);
  15604. if (cmp !== 0) {
  15605. return cmp;
  15606. }
  15607. cmp = mappingA.originalLine - mappingB.originalLine;
  15608. if (cmp !== 0) {
  15609. return cmp;
  15610. }
  15611. cmp = mappingA.originalColumn - mappingB.originalColumn;
  15612. if (cmp !== 0) {
  15613. return cmp;
  15614. }
  15615. return strcmp(mappingA.name, mappingB.name);
  15616. }
  15617. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  15618. /**
  15619. * Strip any JSON XSSI avoidance prefix from the string (as documented
  15620. * in the source maps specification), and then parse the string as
  15621. * JSON.
  15622. */
  15623. function parseSourceMapInput(str) {
  15624. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  15625. }
  15626. exports.parseSourceMapInput = parseSourceMapInput;
  15627. /**
  15628. * Compute the URL of a source given the the source root, the source's
  15629. * URL, and the source map's URL.
  15630. */
  15631. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  15632. sourceURL = sourceURL || '';
  15633. if (sourceRoot) {
  15634. // This follows what Chrome does.
  15635. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  15636. sourceRoot += '/';
  15637. }
  15638. // The spec says:
  15639. // Line 4: An optional source root, useful for relocating source
  15640. // files on a server or removing repeated values in the
  15641. // “sources” entry. This value is prepended to the individual
  15642. // entries in the “source” field.
  15643. sourceURL = sourceRoot + sourceURL;
  15644. }
  15645. // Historically, SourceMapConsumer did not take the sourceMapURL as
  15646. // a parameter. This mode is still somewhat supported, which is why
  15647. // this code block is conditional. However, it's preferable to pass
  15648. // the source map URL to SourceMapConsumer, so that this function
  15649. // can implement the source URL resolution algorithm as outlined in
  15650. // the spec. This block is basically the equivalent of:
  15651. // new URL(sourceURL, sourceMapURL).toString()
  15652. // ... except it avoids using URL, which wasn't available in the
  15653. // older releases of node still supported by this library.
  15654. //
  15655. // The spec says:
  15656. // If the sources are not absolute URLs after prepending of the
  15657. // “sourceRoot”, the sources are resolved relative to the
  15658. // SourceMap (like resolving script src in a html document).
  15659. if (sourceMapURL) {
  15660. var parsed = urlParse(sourceMapURL);
  15661. if (!parsed) {
  15662. throw new Error("sourceMapURL could not be parsed");
  15663. }
  15664. if (parsed.path) {
  15665. // Strip the last path component, but keep the "/".
  15666. var index = parsed.path.lastIndexOf('/');
  15667. if (index >= 0) {
  15668. parsed.path = parsed.path.substring(0, index + 1);
  15669. }
  15670. }
  15671. sourceURL = join(urlGenerate(parsed), sourceURL);
  15672. }
  15673. return normalize(sourceURL);
  15674. }
  15675. exports.computeSourceURL = computeSourceURL;
  15676. });
  15677. /* -*- Mode: js; js-indent-level: 2; -*- */
  15678. /*
  15679. * Copyright 2011 Mozilla Foundation and contributors
  15680. * Licensed under the New BSD license. See LICENSE or:
  15681. * http://opensource.org/licenses/BSD-3-Clause
  15682. */
  15683. var has = Object.prototype.hasOwnProperty;
  15684. var hasNativeMap = typeof Map !== "undefined";
  15685. /**
  15686. * A data structure which is a combination of an array and a set. Adding a new
  15687. * member is O(1), testing for membership is O(1), and finding the index of an
  15688. * element is O(1). Removing elements from the set is not supported. Only
  15689. * strings are supported for membership.
  15690. */
  15691. function ArraySet() {
  15692. this._array = [];
  15693. this._set = hasNativeMap ? new Map() : Object.create(null);
  15694. }
  15695. /**
  15696. * Static method for creating ArraySet instances from an existing array.
  15697. */
  15698. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  15699. var set = new ArraySet();
  15700. for (var i = 0, len = aArray.length; i < len; i++) {
  15701. set.add(aArray[i], aAllowDuplicates);
  15702. }
  15703. return set;
  15704. };
  15705. /**
  15706. * Return how many unique items are in this ArraySet. If duplicates have been
  15707. * added, than those do not count towards the size.
  15708. *
  15709. * @returns Number
  15710. */
  15711. ArraySet.prototype.size = function ArraySet_size() {
  15712. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  15713. };
  15714. /**
  15715. * Add the given string to this set.
  15716. *
  15717. * @param String aStr
  15718. */
  15719. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  15720. var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
  15721. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  15722. var idx = this._array.length;
  15723. if (!isDuplicate || aAllowDuplicates) {
  15724. this._array.push(aStr);
  15725. }
  15726. if (!isDuplicate) {
  15727. if (hasNativeMap) {
  15728. this._set.set(aStr, idx);
  15729. } else {
  15730. this._set[sStr] = idx;
  15731. }
  15732. }
  15733. };
  15734. /**
  15735. * Is the given string a member of this set?
  15736. *
  15737. * @param String aStr
  15738. */
  15739. ArraySet.prototype.has = function ArraySet_has(aStr) {
  15740. if (hasNativeMap) {
  15741. return this._set.has(aStr);
  15742. } else {
  15743. var sStr = util.toSetString(aStr);
  15744. return has.call(this._set, sStr);
  15745. }
  15746. };
  15747. /**
  15748. * What is the index of the given string in the array?
  15749. *
  15750. * @param String aStr
  15751. */
  15752. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  15753. if (hasNativeMap) {
  15754. var idx = this._set.get(aStr);
  15755. if (idx >= 0) {
  15756. return idx;
  15757. }
  15758. } else {
  15759. var sStr = util.toSetString(aStr);
  15760. if (has.call(this._set, sStr)) {
  15761. return this._set[sStr];
  15762. }
  15763. }
  15764. throw new Error('"' + aStr + '" is not in the set.');
  15765. };
  15766. /**
  15767. * What is the element at the given index?
  15768. *
  15769. * @param Number aIdx
  15770. */
  15771. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  15772. if (aIdx >= 0 && aIdx < this._array.length) {
  15773. return this._array[aIdx];
  15774. }
  15775. throw new Error('No element indexed by ' + aIdx);
  15776. };
  15777. /**
  15778. * Returns the array representation of this set (which has the proper indices
  15779. * indicated by indexOf). Note that this is a copy of the internal array used
  15780. * for storing the members so that no one can mess with internal state.
  15781. */
  15782. ArraySet.prototype.toArray = function ArraySet_toArray() {
  15783. return this._array.slice();
  15784. };
  15785. var ArraySet_1 = ArraySet;
  15786. var arraySet = {
  15787. ArraySet: ArraySet_1
  15788. };
  15789. /* -*- Mode: js; js-indent-level: 2; -*- */
  15790. /*
  15791. * Copyright 2014 Mozilla Foundation and contributors
  15792. * Licensed under the New BSD license. See LICENSE or:
  15793. * http://opensource.org/licenses/BSD-3-Clause
  15794. */
  15795. /**
  15796. * Determine whether mappingB is after mappingA with respect to generated
  15797. * position.
  15798. */
  15799. function generatedPositionAfter(mappingA, mappingB) {
  15800. // Optimized for most common case
  15801. var lineA = mappingA.generatedLine;
  15802. var lineB = mappingB.generatedLine;
  15803. var columnA = mappingA.generatedColumn;
  15804. var columnB = mappingB.generatedColumn;
  15805. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  15806. util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  15807. }
  15808. /**
  15809. * A data structure to provide a sorted view of accumulated mappings in a
  15810. * performance conscious manner. It trades a neglibable overhead in general
  15811. * case for a large speedup in case of mappings being added in order.
  15812. */
  15813. function MappingList() {
  15814. this._array = [];
  15815. this._sorted = true;
  15816. // Serves as infimum
  15817. this._last = {generatedLine: -1, generatedColumn: 0};
  15818. }
  15819. /**
  15820. * Iterate through internal items. This method takes the same arguments that
  15821. * `Array.prototype.forEach` takes.
  15822. *
  15823. * NOTE: The order of the mappings is NOT guaranteed.
  15824. */
  15825. MappingList.prototype.unsortedForEach =
  15826. function MappingList_forEach(aCallback, aThisArg) {
  15827. this._array.forEach(aCallback, aThisArg);
  15828. };
  15829. /**
  15830. * Add the given source mapping.
  15831. *
  15832. * @param Object aMapping
  15833. */
  15834. MappingList.prototype.add = function MappingList_add(aMapping) {
  15835. if (generatedPositionAfter(this._last, aMapping)) {
  15836. this._last = aMapping;
  15837. this._array.push(aMapping);
  15838. } else {
  15839. this._sorted = false;
  15840. this._array.push(aMapping);
  15841. }
  15842. };
  15843. /**
  15844. * Returns the flat, sorted array of mappings. The mappings are sorted by
  15845. * generated position.
  15846. *
  15847. * WARNING: This method returns internal data without copying, for
  15848. * performance. The return value must NOT be mutated, and should be treated as
  15849. * an immutable borrow. If you want to take ownership, you must make your own
  15850. * copy.
  15851. */
  15852. MappingList.prototype.toArray = function MappingList_toArray() {
  15853. if (!this._sorted) {
  15854. this._array.sort(util.compareByGeneratedPositionsInflated);
  15855. this._sorted = true;
  15856. }
  15857. return this._array;
  15858. };
  15859. var MappingList_1 = MappingList;
  15860. var mappingList = {
  15861. MappingList: MappingList_1
  15862. };
  15863. /* -*- Mode: js; js-indent-level: 2; -*- */
  15864. /*
  15865. * Copyright 2011 Mozilla Foundation and contributors
  15866. * Licensed under the New BSD license. See LICENSE or:
  15867. * http://opensource.org/licenses/BSD-3-Clause
  15868. */
  15869. var ArraySet$1 = arraySet.ArraySet;
  15870. var MappingList$1 = mappingList.MappingList;
  15871. /**
  15872. * An instance of the SourceMapGenerator represents a source map which is
  15873. * being built incrementally. You may pass an object with the following
  15874. * properties:
  15875. *
  15876. * - file: The filename of the generated source.
  15877. * - sourceRoot: A root for all relative URLs in this source map.
  15878. */
  15879. function SourceMapGenerator(aArgs) {
  15880. if (!aArgs) {
  15881. aArgs = {};
  15882. }
  15883. this._file = util.getArg(aArgs, 'file', null);
  15884. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  15885. this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  15886. this._sources = new ArraySet$1();
  15887. this._names = new ArraySet$1();
  15888. this._mappings = new MappingList$1();
  15889. this._sourcesContents = null;
  15890. }
  15891. SourceMapGenerator.prototype._version = 3;
  15892. /**
  15893. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  15894. *
  15895. * @param aSourceMapConsumer The SourceMap.
  15896. */
  15897. SourceMapGenerator.fromSourceMap =
  15898. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  15899. var sourceRoot = aSourceMapConsumer.sourceRoot;
  15900. var generator = new SourceMapGenerator({
  15901. file: aSourceMapConsumer.file,
  15902. sourceRoot: sourceRoot
  15903. });
  15904. aSourceMapConsumer.eachMapping(function (mapping) {
  15905. var newMapping = {
  15906. generated: {
  15907. line: mapping.generatedLine,
  15908. column: mapping.generatedColumn
  15909. }
  15910. };
  15911. if (mapping.source != null) {
  15912. newMapping.source = mapping.source;
  15913. if (sourceRoot != null) {
  15914. newMapping.source = util.relative(sourceRoot, newMapping.source);
  15915. }
  15916. newMapping.original = {
  15917. line: mapping.originalLine,
  15918. column: mapping.originalColumn
  15919. };
  15920. if (mapping.name != null) {
  15921. newMapping.name = mapping.name;
  15922. }
  15923. }
  15924. generator.addMapping(newMapping);
  15925. });
  15926. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  15927. var sourceRelative = sourceFile;
  15928. if (sourceRoot !== null) {
  15929. sourceRelative = util.relative(sourceRoot, sourceFile);
  15930. }
  15931. if (!generator._sources.has(sourceRelative)) {
  15932. generator._sources.add(sourceRelative);
  15933. }
  15934. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  15935. if (content != null) {
  15936. generator.setSourceContent(sourceFile, content);
  15937. }
  15938. });
  15939. return generator;
  15940. };
  15941. /**
  15942. * Add a single mapping from original source line and column to the generated
  15943. * source's line and column for this source map being created. The mapping
  15944. * object should have the following properties:
  15945. *
  15946. * - generated: An object with the generated line and column positions.
  15947. * - original: An object with the original line and column positions.
  15948. * - source: The original source file (relative to the sourceRoot).
  15949. * - name: An optional original token name for this mapping.
  15950. */
  15951. SourceMapGenerator.prototype.addMapping =
  15952. function SourceMapGenerator_addMapping(aArgs) {
  15953. var generated = util.getArg(aArgs, 'generated');
  15954. var original = util.getArg(aArgs, 'original', null);
  15955. var source = util.getArg(aArgs, 'source', null);
  15956. var name = util.getArg(aArgs, 'name', null);
  15957. if (!this._skipValidation) {
  15958. this._validateMapping(generated, original, source, name);
  15959. }
  15960. if (source != null) {
  15961. source = String(source);
  15962. if (!this._sources.has(source)) {
  15963. this._sources.add(source);
  15964. }
  15965. }
  15966. if (name != null) {
  15967. name = String(name);
  15968. if (!this._names.has(name)) {
  15969. this._names.add(name);
  15970. }
  15971. }
  15972. this._mappings.add({
  15973. generatedLine: generated.line,
  15974. generatedColumn: generated.column,
  15975. originalLine: original != null && original.line,
  15976. originalColumn: original != null && original.column,
  15977. source: source,
  15978. name: name
  15979. });
  15980. };
  15981. /**
  15982. * Set the source content for a source file.
  15983. */
  15984. SourceMapGenerator.prototype.setSourceContent =
  15985. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  15986. var source = aSourceFile;
  15987. if (this._sourceRoot != null) {
  15988. source = util.relative(this._sourceRoot, source);
  15989. }
  15990. if (aSourceContent != null) {
  15991. // Add the source content to the _sourcesContents map.
  15992. // Create a new _sourcesContents map if the property is null.
  15993. if (!this._sourcesContents) {
  15994. this._sourcesContents = Object.create(null);
  15995. }
  15996. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  15997. } else if (this._sourcesContents) {
  15998. // Remove the source file from the _sourcesContents map.
  15999. // If the _sourcesContents map is empty, set the property to null.
  16000. delete this._sourcesContents[util.toSetString(source)];
  16001. if (Object.keys(this._sourcesContents).length === 0) {
  16002. this._sourcesContents = null;
  16003. }
  16004. }
  16005. };
  16006. /**
  16007. * Applies the mappings of a sub-source-map for a specific source file to the
  16008. * source map being generated. Each mapping to the supplied source file is
  16009. * rewritten using the supplied source map. Note: The resolution for the
  16010. * resulting mappings is the minimium of this map and the supplied map.
  16011. *
  16012. * @param aSourceMapConsumer The source map to be applied.
  16013. * @param aSourceFile Optional. The filename of the source file.
  16014. * If omitted, SourceMapConsumer's file property will be used.
  16015. * @param aSourceMapPath Optional. The dirname of the path to the source map
  16016. * to be applied. If relative, it is relative to the SourceMapConsumer.
  16017. * This parameter is needed when the two source maps aren't in the same
  16018. * directory, and the source map to be applied contains relative source
  16019. * paths. If so, those relative source paths need to be rewritten
  16020. * relative to the SourceMapGenerator.
  16021. */
  16022. SourceMapGenerator.prototype.applySourceMap =
  16023. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  16024. var sourceFile = aSourceFile;
  16025. // If aSourceFile is omitted, we will use the file property of the SourceMap
  16026. if (aSourceFile == null) {
  16027. if (aSourceMapConsumer.file == null) {
  16028. throw new Error(
  16029. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  16030. 'or the source map\'s "file" property. Both were omitted.'
  16031. );
  16032. }
  16033. sourceFile = aSourceMapConsumer.file;
  16034. }
  16035. var sourceRoot = this._sourceRoot;
  16036. // Make "sourceFile" relative if an absolute Url is passed.
  16037. if (sourceRoot != null) {
  16038. sourceFile = util.relative(sourceRoot, sourceFile);
  16039. }
  16040. // Applying the SourceMap can add and remove items from the sources and
  16041. // the names array.
  16042. var newSources = new ArraySet$1();
  16043. var newNames = new ArraySet$1();
  16044. // Find mappings for the "sourceFile"
  16045. this._mappings.unsortedForEach(function (mapping) {
  16046. if (mapping.source === sourceFile && mapping.originalLine != null) {
  16047. // Check if it can be mapped by the source map, then update the mapping.
  16048. var original = aSourceMapConsumer.originalPositionFor({
  16049. line: mapping.originalLine,
  16050. column: mapping.originalColumn
  16051. });
  16052. if (original.source != null) {
  16053. // Copy mapping
  16054. mapping.source = original.source;
  16055. if (aSourceMapPath != null) {
  16056. mapping.source = util.join(aSourceMapPath, mapping.source);
  16057. }
  16058. if (sourceRoot != null) {
  16059. mapping.source = util.relative(sourceRoot, mapping.source);
  16060. }
  16061. mapping.originalLine = original.line;
  16062. mapping.originalColumn = original.column;
  16063. if (original.name != null) {
  16064. mapping.name = original.name;
  16065. }
  16066. }
  16067. }
  16068. var source = mapping.source;
  16069. if (source != null && !newSources.has(source)) {
  16070. newSources.add(source);
  16071. }
  16072. var name = mapping.name;
  16073. if (name != null && !newNames.has(name)) {
  16074. newNames.add(name);
  16075. }
  16076. }, this);
  16077. this._sources = newSources;
  16078. this._names = newNames;
  16079. // Copy sourcesContents of applied map.
  16080. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  16081. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  16082. if (content != null) {
  16083. if (aSourceMapPath != null) {
  16084. sourceFile = util.join(aSourceMapPath, sourceFile);
  16085. }
  16086. if (sourceRoot != null) {
  16087. sourceFile = util.relative(sourceRoot, sourceFile);
  16088. }
  16089. this.setSourceContent(sourceFile, content);
  16090. }
  16091. }, this);
  16092. };
  16093. /**
  16094. * A mapping can have one of the three levels of data:
  16095. *
  16096. * 1. Just the generated position.
  16097. * 2. The Generated position, original position, and original source.
  16098. * 3. Generated and original position, original source, as well as a name
  16099. * token.
  16100. *
  16101. * To maintain consistency, we validate that any new mapping being added falls
  16102. * in to one of these categories.
  16103. */
  16104. SourceMapGenerator.prototype._validateMapping =
  16105. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  16106. aName) {
  16107. // When aOriginal is truthy but has empty values for .line and .column,
  16108. // it is most likely a programmer error. In this case we throw a very
  16109. // specific error message to try to guide them the right way.
  16110. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  16111. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  16112. throw new Error(
  16113. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  16114. 'the original mapping entirely and only map the generated position. If so, pass ' +
  16115. 'null for the original mapping instead of an object with empty or null values.'
  16116. );
  16117. }
  16118. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  16119. && aGenerated.line > 0 && aGenerated.column >= 0
  16120. && !aOriginal && !aSource && !aName) {
  16121. // Case 1.
  16122. return;
  16123. }
  16124. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  16125. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  16126. && aGenerated.line > 0 && aGenerated.column >= 0
  16127. && aOriginal.line > 0 && aOriginal.column >= 0
  16128. && aSource) {
  16129. // Cases 2 and 3.
  16130. return;
  16131. }
  16132. else {
  16133. throw new Error('Invalid mapping: ' + JSON.stringify({
  16134. generated: aGenerated,
  16135. source: aSource,
  16136. original: aOriginal,
  16137. name: aName
  16138. }));
  16139. }
  16140. };
  16141. /**
  16142. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  16143. * specified by the source map format.
  16144. */
  16145. SourceMapGenerator.prototype._serializeMappings =
  16146. function SourceMapGenerator_serializeMappings() {
  16147. var previousGeneratedColumn = 0;
  16148. var previousGeneratedLine = 1;
  16149. var previousOriginalColumn = 0;
  16150. var previousOriginalLine = 0;
  16151. var previousName = 0;
  16152. var previousSource = 0;
  16153. var result = '';
  16154. var next;
  16155. var mapping;
  16156. var nameIdx;
  16157. var sourceIdx;
  16158. var mappings = this._mappings.toArray();
  16159. for (var i = 0, len = mappings.length; i < len; i++) {
  16160. mapping = mappings[i];
  16161. next = '';
  16162. if (mapping.generatedLine !== previousGeneratedLine) {
  16163. previousGeneratedColumn = 0;
  16164. while (mapping.generatedLine !== previousGeneratedLine) {
  16165. next += ';';
  16166. previousGeneratedLine++;
  16167. }
  16168. }
  16169. else {
  16170. if (i > 0) {
  16171. if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  16172. continue;
  16173. }
  16174. next += ',';
  16175. }
  16176. }
  16177. next += base64Vlq.encode(mapping.generatedColumn
  16178. - previousGeneratedColumn);
  16179. previousGeneratedColumn = mapping.generatedColumn;
  16180. if (mapping.source != null) {
  16181. sourceIdx = this._sources.indexOf(mapping.source);
  16182. next += base64Vlq.encode(sourceIdx - previousSource);
  16183. previousSource = sourceIdx;
  16184. // lines are stored 0-based in SourceMap spec version 3
  16185. next += base64Vlq.encode(mapping.originalLine - 1
  16186. - previousOriginalLine);
  16187. previousOriginalLine = mapping.originalLine - 1;
  16188. next += base64Vlq.encode(mapping.originalColumn
  16189. - previousOriginalColumn);
  16190. previousOriginalColumn = mapping.originalColumn;
  16191. if (mapping.name != null) {
  16192. nameIdx = this._names.indexOf(mapping.name);
  16193. next += base64Vlq.encode(nameIdx - previousName);
  16194. previousName = nameIdx;
  16195. }
  16196. }
  16197. result += next;
  16198. }
  16199. return result;
  16200. };
  16201. SourceMapGenerator.prototype._generateSourcesContent =
  16202. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  16203. return aSources.map(function (source) {
  16204. if (!this._sourcesContents) {
  16205. return null;
  16206. }
  16207. if (aSourceRoot != null) {
  16208. source = util.relative(aSourceRoot, source);
  16209. }
  16210. var key = util.toSetString(source);
  16211. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  16212. ? this._sourcesContents[key]
  16213. : null;
  16214. }, this);
  16215. };
  16216. /**
  16217. * Externalize the source map.
  16218. */
  16219. SourceMapGenerator.prototype.toJSON =
  16220. function SourceMapGenerator_toJSON() {
  16221. var map = {
  16222. version: this._version,
  16223. sources: this._sources.toArray(),
  16224. names: this._names.toArray(),
  16225. mappings: this._serializeMappings()
  16226. };
  16227. if (this._file != null) {
  16228. map.file = this._file;
  16229. }
  16230. if (this._sourceRoot != null) {
  16231. map.sourceRoot = this._sourceRoot;
  16232. }
  16233. if (this._sourcesContents) {
  16234. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  16235. }
  16236. return map;
  16237. };
  16238. /**
  16239. * Render the source map being generated to a string.
  16240. */
  16241. SourceMapGenerator.prototype.toString =
  16242. function SourceMapGenerator_toString() {
  16243. return JSON.stringify(this.toJSON());
  16244. };
  16245. var SourceMapGenerator_1 = SourceMapGenerator;
  16246. var sourceMapGenerator = {
  16247. SourceMapGenerator: SourceMapGenerator_1
  16248. };
  16249. /* -*- Mode: js; js-indent-level: 2; -*- */
  16250. var binarySearch = createCommonjsModule(function (module, exports) {
  16251. /*
  16252. * Copyright 2011 Mozilla Foundation and contributors
  16253. * Licensed under the New BSD license. See LICENSE or:
  16254. * http://opensource.org/licenses/BSD-3-Clause
  16255. */
  16256. exports.GREATEST_LOWER_BOUND = 1;
  16257. exports.LEAST_UPPER_BOUND = 2;
  16258. /**
  16259. * Recursive implementation of binary search.
  16260. *
  16261. * @param aLow Indices here and lower do not contain the needle.
  16262. * @param aHigh Indices here and higher do not contain the needle.
  16263. * @param aNeedle The element being searched for.
  16264. * @param aHaystack The non-empty array being searched.
  16265. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  16266. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  16267. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  16268. * closest element that is smaller than or greater than the one we are
  16269. * searching for, respectively, if the exact element cannot be found.
  16270. */
  16271. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  16272. // This function terminates when one of the following is true:
  16273. //
  16274. // 1. We find the exact element we are looking for.
  16275. //
  16276. // 2. We did not find the exact element, but we can return the index of
  16277. // the next-closest element.
  16278. //
  16279. // 3. We did not find the exact element, and there is no next-closest
  16280. // element than the one we are searching for, so we return -1.
  16281. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  16282. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  16283. if (cmp === 0) {
  16284. // Found the element we are looking for.
  16285. return mid;
  16286. }
  16287. else if (cmp > 0) {
  16288. // Our needle is greater than aHaystack[mid].
  16289. if (aHigh - mid > 1) {
  16290. // The element is in the upper half.
  16291. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  16292. }
  16293. // The exact needle element was not found in this haystack. Determine if
  16294. // we are in termination case (3) or (2) and return the appropriate thing.
  16295. if (aBias == exports.LEAST_UPPER_BOUND) {
  16296. return aHigh < aHaystack.length ? aHigh : -1;
  16297. } else {
  16298. return mid;
  16299. }
  16300. }
  16301. else {
  16302. // Our needle is less than aHaystack[mid].
  16303. if (mid - aLow > 1) {
  16304. // The element is in the lower half.
  16305. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  16306. }
  16307. // we are in termination case (3) or (2) and return the appropriate thing.
  16308. if (aBias == exports.LEAST_UPPER_BOUND) {
  16309. return mid;
  16310. } else {
  16311. return aLow < 0 ? -1 : aLow;
  16312. }
  16313. }
  16314. }
  16315. /**
  16316. * This is an implementation of binary search which will always try and return
  16317. * the index of the closest element if there is no exact hit. This is because
  16318. * mappings between original and generated line/col pairs are single points,
  16319. * and there is an implicit region between each of them, so a miss just means
  16320. * that you aren't on the very start of a region.
  16321. *
  16322. * @param aNeedle The element you are looking for.
  16323. * @param aHaystack The array that is being searched.
  16324. * @param aCompare A function which takes the needle and an element in the
  16325. * array and returns -1, 0, or 1 depending on whether the needle is less
  16326. * than, equal to, or greater than the element, respectively.
  16327. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  16328. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  16329. * closest element that is smaller than or greater than the one we are
  16330. * searching for, respectively, if the exact element cannot be found.
  16331. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  16332. */
  16333. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  16334. if (aHaystack.length === 0) {
  16335. return -1;
  16336. }
  16337. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  16338. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  16339. if (index < 0) {
  16340. return -1;
  16341. }
  16342. // We have found either the exact element, or the next-closest element than
  16343. // the one we are searching for. However, there may be more than one such
  16344. // element. Make sure we always return the smallest of these.
  16345. while (index - 1 >= 0) {
  16346. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  16347. break;
  16348. }
  16349. --index;
  16350. }
  16351. return index;
  16352. };
  16353. });
  16354. /* -*- Mode: js; js-indent-level: 2; -*- */
  16355. /*
  16356. * Copyright 2011 Mozilla Foundation and contributors
  16357. * Licensed under the New BSD license. See LICENSE or:
  16358. * http://opensource.org/licenses/BSD-3-Clause
  16359. */
  16360. // It turns out that some (most?) JavaScript engines don't self-host
  16361. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  16362. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  16363. // custom comparator function, calling back and forth between the VM's C++ and
  16364. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  16365. // worse generated code for the comparator function than would be optimal. In
  16366. // fact, when sorting with a comparator, these costs outweigh the benefits of
  16367. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  16368. // a ~3500ms mean speed-up in `bench/bench.html`.
  16369. /**
  16370. * Swap the elements indexed by `x` and `y` in the array `ary`.
  16371. *
  16372. * @param {Array} ary
  16373. * The array.
  16374. * @param {Number} x
  16375. * The index of the first item.
  16376. * @param {Number} y
  16377. * The index of the second item.
  16378. */
  16379. function swap(ary, x, y) {
  16380. var temp = ary[x];
  16381. ary[x] = ary[y];
  16382. ary[y] = temp;
  16383. }
  16384. /**
  16385. * Returns a random integer within the range `low .. high` inclusive.
  16386. *
  16387. * @param {Number} low
  16388. * The lower bound on the range.
  16389. * @param {Number} high
  16390. * The upper bound on the range.
  16391. */
  16392. function randomIntInRange(low, high) {
  16393. return Math.round(low + (Math.random() * (high - low)));
  16394. }
  16395. /**
  16396. * The Quick Sort algorithm.
  16397. *
  16398. * @param {Array} ary
  16399. * An array to sort.
  16400. * @param {function} comparator
  16401. * Function to use to compare two items.
  16402. * @param {Number} p
  16403. * Start index of the array
  16404. * @param {Number} r
  16405. * End index of the array
  16406. */
  16407. function doQuickSort(ary, comparator, p, r) {
  16408. // If our lower bound is less than our upper bound, we (1) partition the
  16409. // array into two pieces and (2) recurse on each half. If it is not, this is
  16410. // the empty array and our base case.
  16411. if (p < r) {
  16412. // (1) Partitioning.
  16413. //
  16414. // The partitioning chooses a pivot between `p` and `r` and moves all
  16415. // elements that are less than or equal to the pivot to the before it, and
  16416. // all the elements that are greater than it after it. The effect is that
  16417. // once partition is done, the pivot is in the exact place it will be when
  16418. // the array is put in sorted order, and it will not need to be moved
  16419. // again. This runs in O(n) time.
  16420. // Always choose a random pivot so that an input array which is reverse
  16421. // sorted does not cause O(n^2) running time.
  16422. var pivotIndex = randomIntInRange(p, r);
  16423. var i = p - 1;
  16424. swap(ary, pivotIndex, r);
  16425. var pivot = ary[r];
  16426. // Immediately after `j` is incremented in this loop, the following hold
  16427. // true:
  16428. //
  16429. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  16430. //
  16431. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  16432. for (var j = p; j < r; j++) {
  16433. if (comparator(ary[j], pivot) <= 0) {
  16434. i += 1;
  16435. swap(ary, i, j);
  16436. }
  16437. }
  16438. swap(ary, i + 1, j);
  16439. var q = i + 1;
  16440. // (2) Recurse on each half.
  16441. doQuickSort(ary, comparator, p, q - 1);
  16442. doQuickSort(ary, comparator, q + 1, r);
  16443. }
  16444. }
  16445. /**
  16446. * Sort the given array in-place with the given comparator function.
  16447. *
  16448. * @param {Array} ary
  16449. * An array to sort.
  16450. * @param {function} comparator
  16451. * Function to use to compare two items.
  16452. */
  16453. var quickSort_1 = function (ary, comparator) {
  16454. doQuickSort(ary, comparator, 0, ary.length - 1);
  16455. };
  16456. var quickSort = {
  16457. quickSort: quickSort_1
  16458. };
  16459. /* -*- Mode: js; js-indent-level: 2; -*- */
  16460. /*
  16461. * Copyright 2011 Mozilla Foundation and contributors
  16462. * Licensed under the New BSD license. See LICENSE or:
  16463. * http://opensource.org/licenses/BSD-3-Clause
  16464. */
  16465. var ArraySet$2 = arraySet.ArraySet;
  16466. var quickSort$1 = quickSort.quickSort;
  16467. function SourceMapConsumer(aSourceMap, aSourceMapURL) {
  16468. var sourceMap = aSourceMap;
  16469. if (typeof aSourceMap === 'string') {
  16470. sourceMap = util.parseSourceMapInput(aSourceMap);
  16471. }
  16472. return sourceMap.sections != null
  16473. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  16474. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  16475. }
  16476. SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  16477. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  16478. };
  16479. /**
  16480. * The version of the source mapping spec that we are consuming.
  16481. */
  16482. SourceMapConsumer.prototype._version = 3;
  16483. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  16484. // parsed mapping coordinates from the source map's "mappings" attribute. They
  16485. // are lazily instantiated, accessed via the `_generatedMappings` and
  16486. // `_originalMappings` getters respectively, and we only parse the mappings
  16487. // and create these arrays once queried for a source location. We jump through
  16488. // these hoops because there can be many thousands of mappings, and parsing
  16489. // them is expensive, so we only want to do it if we must.
  16490. //
  16491. // Each object in the arrays is of the form:
  16492. //
  16493. // {
  16494. // generatedLine: The line number in the generated code,
  16495. // generatedColumn: The column number in the generated code,
  16496. // source: The path to the original source file that generated this
  16497. // chunk of code,
  16498. // originalLine: The line number in the original source that
  16499. // corresponds to this chunk of generated code,
  16500. // originalColumn: The column number in the original source that
  16501. // corresponds to this chunk of generated code,
  16502. // name: The name of the original symbol which generated this chunk of
  16503. // code.
  16504. // }
  16505. //
  16506. // All properties except for `generatedLine` and `generatedColumn` can be
  16507. // `null`.
  16508. //
  16509. // `_generatedMappings` is ordered by the generated positions.
  16510. //
  16511. // `_originalMappings` is ordered by the original positions.
  16512. SourceMapConsumer.prototype.__generatedMappings = null;
  16513. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  16514. configurable: true,
  16515. enumerable: true,
  16516. get: function () {
  16517. if (!this.__generatedMappings) {
  16518. this._parseMappings(this._mappings, this.sourceRoot);
  16519. }
  16520. return this.__generatedMappings;
  16521. }
  16522. });
  16523. SourceMapConsumer.prototype.__originalMappings = null;
  16524. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  16525. configurable: true,
  16526. enumerable: true,
  16527. get: function () {
  16528. if (!this.__originalMappings) {
  16529. this._parseMappings(this._mappings, this.sourceRoot);
  16530. }
  16531. return this.__originalMappings;
  16532. }
  16533. });
  16534. SourceMapConsumer.prototype._charIsMappingSeparator =
  16535. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  16536. var c = aStr.charAt(index);
  16537. return c === ";" || c === ",";
  16538. };
  16539. /**
  16540. * Parse the mappings in a string in to a data structure which we can easily
  16541. * query (the ordered arrays in the `this.__generatedMappings` and
  16542. * `this.__originalMappings` properties).
  16543. */
  16544. SourceMapConsumer.prototype._parseMappings =
  16545. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  16546. throw new Error("Subclasses must implement _parseMappings");
  16547. };
  16548. SourceMapConsumer.GENERATED_ORDER = 1;
  16549. SourceMapConsumer.ORIGINAL_ORDER = 2;
  16550. SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
  16551. SourceMapConsumer.LEAST_UPPER_BOUND = 2;
  16552. /**
  16553. * Iterate over each mapping between an original source/line/column and a
  16554. * generated line/column in this source map.
  16555. *
  16556. * @param Function aCallback
  16557. * The function that is called with each mapping.
  16558. * @param Object aContext
  16559. * Optional. If specified, this object will be the value of `this` every
  16560. * time that `aCallback` is called.
  16561. * @param aOrder
  16562. * Either `SourceMapConsumer.GENERATED_ORDER` or
  16563. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  16564. * iterate over the mappings sorted by the generated file's line/column
  16565. * order or the original's source/line/column order, respectively. Defaults to
  16566. * `SourceMapConsumer.GENERATED_ORDER`.
  16567. */
  16568. SourceMapConsumer.prototype.eachMapping =
  16569. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  16570. var context = aContext || null;
  16571. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  16572. var mappings;
  16573. switch (order) {
  16574. case SourceMapConsumer.GENERATED_ORDER:
  16575. mappings = this._generatedMappings;
  16576. break;
  16577. case SourceMapConsumer.ORIGINAL_ORDER:
  16578. mappings = this._originalMappings;
  16579. break;
  16580. default:
  16581. throw new Error("Unknown order of iteration.");
  16582. }
  16583. var sourceRoot = this.sourceRoot;
  16584. mappings.map(function (mapping) {
  16585. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  16586. source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);
  16587. return {
  16588. source: source,
  16589. generatedLine: mapping.generatedLine,
  16590. generatedColumn: mapping.generatedColumn,
  16591. originalLine: mapping.originalLine,
  16592. originalColumn: mapping.originalColumn,
  16593. name: mapping.name === null ? null : this._names.at(mapping.name)
  16594. };
  16595. }, this).forEach(aCallback, context);
  16596. };
  16597. /**
  16598. * Returns all generated line and column information for the original source,
  16599. * line, and column provided. If no column is provided, returns all mappings
  16600. * corresponding to a either the line we are searching for or the next
  16601. * closest line that has any mappings. Otherwise, returns all mappings
  16602. * corresponding to the given line and either the column we are searching for
  16603. * or the next closest column that has any offsets.
  16604. *
  16605. * The only argument is an object with the following properties:
  16606. *
  16607. * - source: The filename of the original source.
  16608. * - line: The line number in the original source. The line number is 1-based.
  16609. * - column: Optional. the column number in the original source.
  16610. * The column number is 0-based.
  16611. *
  16612. * and an array of objects is returned, each with the following properties:
  16613. *
  16614. * - line: The line number in the generated source, or null. The
  16615. * line number is 1-based.
  16616. * - column: The column number in the generated source, or null.
  16617. * The column number is 0-based.
  16618. */
  16619. SourceMapConsumer.prototype.allGeneratedPositionsFor =
  16620. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  16621. var line = util.getArg(aArgs, 'line');
  16622. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  16623. // returns the index of the closest mapping less than the needle. By
  16624. // setting needle.originalColumn to 0, we thus find the last mapping for
  16625. // the given line, provided such a mapping exists.
  16626. var needle = {
  16627. source: util.getArg(aArgs, 'source'),
  16628. originalLine: line,
  16629. originalColumn: util.getArg(aArgs, 'column', 0)
  16630. };
  16631. needle.source = this._findSourceIndex(needle.source);
  16632. if (needle.source < 0) {
  16633. return [];
  16634. }
  16635. var mappings = [];
  16636. var index = this._findMapping(needle,
  16637. this._originalMappings,
  16638. "originalLine",
  16639. "originalColumn",
  16640. util.compareByOriginalPositions,
  16641. binarySearch.LEAST_UPPER_BOUND);
  16642. if (index >= 0) {
  16643. var mapping = this._originalMappings[index];
  16644. if (aArgs.column === undefined) {
  16645. var originalLine = mapping.originalLine;
  16646. // Iterate until either we run out of mappings, or we run into
  16647. // a mapping for a different line than the one we found. Since
  16648. // mappings are sorted, this is guaranteed to find all mappings for
  16649. // the line we found.
  16650. while (mapping && mapping.originalLine === originalLine) {
  16651. mappings.push({
  16652. line: util.getArg(mapping, 'generatedLine', null),
  16653. column: util.getArg(mapping, 'generatedColumn', null),
  16654. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  16655. });
  16656. mapping = this._originalMappings[++index];
  16657. }
  16658. } else {
  16659. var originalColumn = mapping.originalColumn;
  16660. // Iterate until either we run out of mappings, or we run into
  16661. // a mapping for a different line than the one we were searching for.
  16662. // Since mappings are sorted, this is guaranteed to find all mappings for
  16663. // the line we are searching for.
  16664. while (mapping &&
  16665. mapping.originalLine === line &&
  16666. mapping.originalColumn == originalColumn) {
  16667. mappings.push({
  16668. line: util.getArg(mapping, 'generatedLine', null),
  16669. column: util.getArg(mapping, 'generatedColumn', null),
  16670. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  16671. });
  16672. mapping = this._originalMappings[++index];
  16673. }
  16674. }
  16675. }
  16676. return mappings;
  16677. };
  16678. var SourceMapConsumer_1 = SourceMapConsumer;
  16679. /**
  16680. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  16681. * query for information about the original file positions by giving it a file
  16682. * position in the generated source.
  16683. *
  16684. * The first parameter is the raw source map (either as a JSON string, or
  16685. * already parsed to an object). According to the spec, source maps have the
  16686. * following attributes:
  16687. *
  16688. * - version: Which version of the source map spec this map is following.
  16689. * - sources: An array of URLs to the original source files.
  16690. * - names: An array of identifiers which can be referrenced by individual mappings.
  16691. * - sourceRoot: Optional. The URL root from which all sources are relative.
  16692. * - sourcesContent: Optional. An array of contents of the original source files.
  16693. * - mappings: A string of base64 VLQs which contain the actual mappings.
  16694. * - file: Optional. The generated file this source map is associated with.
  16695. *
  16696. * Here is an example source map, taken from the source map spec[0]:
  16697. *
  16698. * {
  16699. * version : 3,
  16700. * file: "out.js",
  16701. * sourceRoot : "",
  16702. * sources: ["foo.js", "bar.js"],
  16703. * names: ["src", "maps", "are", "fun"],
  16704. * mappings: "AA,AB;;ABCDE;"
  16705. * }
  16706. *
  16707. * The second parameter, if given, is a string whose value is the URL
  16708. * at which the source map was found. This URL is used to compute the
  16709. * sources array.
  16710. *
  16711. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  16712. */
  16713. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  16714. var sourceMap = aSourceMap;
  16715. if (typeof aSourceMap === 'string') {
  16716. sourceMap = util.parseSourceMapInput(aSourceMap);
  16717. }
  16718. var version = util.getArg(sourceMap, 'version');
  16719. var sources = util.getArg(sourceMap, 'sources');
  16720. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  16721. // requires the array) to play nice here.
  16722. var names = util.getArg(sourceMap, 'names', []);
  16723. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  16724. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  16725. var mappings = util.getArg(sourceMap, 'mappings');
  16726. var file = util.getArg(sourceMap, 'file', null);
  16727. // Once again, Sass deviates from the spec and supplies the version as a
  16728. // string rather than a number, so we use loose equality checking here.
  16729. if (version != this._version) {
  16730. throw new Error('Unsupported version: ' + version);
  16731. }
  16732. if (sourceRoot) {
  16733. sourceRoot = util.normalize(sourceRoot);
  16734. }
  16735. sources = sources
  16736. .map(String)
  16737. // Some source maps produce relative source paths like "./foo.js" instead of
  16738. // "foo.js". Normalize these first so that future comparisons will succeed.
  16739. // See bugzil.la/1090768.
  16740. .map(util.normalize)
  16741. // Always ensure that absolute sources are internally stored relative to
  16742. // the source root, if the source root is absolute. Not doing this would
  16743. // be particularly problematic when the source root is a prefix of the
  16744. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  16745. .map(function (source) {
  16746. return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
  16747. ? util.relative(sourceRoot, source)
  16748. : source;
  16749. });
  16750. // Pass `true` below to allow duplicate names and sources. While source maps
  16751. // are intended to be compressed and deduplicated, the TypeScript compiler
  16752. // sometimes generates source maps with duplicates in them. See Github issue
  16753. // #72 and bugzil.la/889492.
  16754. this._names = ArraySet$2.fromArray(names.map(String), true);
  16755. this._sources = ArraySet$2.fromArray(sources, true);
  16756. this._absoluteSources = this._sources.toArray().map(function (s) {
  16757. return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
  16758. });
  16759. this.sourceRoot = sourceRoot;
  16760. this.sourcesContent = sourcesContent;
  16761. this._mappings = mappings;
  16762. this._sourceMapURL = aSourceMapURL;
  16763. this.file = file;
  16764. }
  16765. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  16766. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
  16767. /**
  16768. * Utility function to find the index of a source. Returns -1 if not
  16769. * found.
  16770. */
  16771. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  16772. var relativeSource = aSource;
  16773. if (this.sourceRoot != null) {
  16774. relativeSource = util.relative(this.sourceRoot, relativeSource);
  16775. }
  16776. if (this._sources.has(relativeSource)) {
  16777. return this._sources.indexOf(relativeSource);
  16778. }
  16779. // Maybe aSource is an absolute URL as returned by |sources|. In
  16780. // this case we can't simply undo the transform.
  16781. var i;
  16782. for (i = 0; i < this._absoluteSources.length; ++i) {
  16783. if (this._absoluteSources[i] == aSource) {
  16784. return i;
  16785. }
  16786. }
  16787. return -1;
  16788. };
  16789. /**
  16790. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  16791. *
  16792. * @param SourceMapGenerator aSourceMap
  16793. * The source map that will be consumed.
  16794. * @param String aSourceMapURL
  16795. * The URL at which the source map can be found (optional)
  16796. * @returns BasicSourceMapConsumer
  16797. */
  16798. BasicSourceMapConsumer.fromSourceMap =
  16799. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  16800. var smc = Object.create(BasicSourceMapConsumer.prototype);
  16801. var names = smc._names = ArraySet$2.fromArray(aSourceMap._names.toArray(), true);
  16802. var sources = smc._sources = ArraySet$2.fromArray(aSourceMap._sources.toArray(), true);
  16803. smc.sourceRoot = aSourceMap._sourceRoot;
  16804. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  16805. smc.sourceRoot);
  16806. smc.file = aSourceMap._file;
  16807. smc._sourceMapURL = aSourceMapURL;
  16808. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  16809. return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  16810. });
  16811. // Because we are modifying the entries (by converting string sources and
  16812. // names to indices into the sources and names ArraySets), we have to make
  16813. // a copy of the entry or else bad things happen. Shared mutable state
  16814. // strikes again! See github issue #191.
  16815. var generatedMappings = aSourceMap._mappings.toArray().slice();
  16816. var destGeneratedMappings = smc.__generatedMappings = [];
  16817. var destOriginalMappings = smc.__originalMappings = [];
  16818. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  16819. var srcMapping = generatedMappings[i];
  16820. var destMapping = new Mapping;
  16821. destMapping.generatedLine = srcMapping.generatedLine;
  16822. destMapping.generatedColumn = srcMapping.generatedColumn;
  16823. if (srcMapping.source) {
  16824. destMapping.source = sources.indexOf(srcMapping.source);
  16825. destMapping.originalLine = srcMapping.originalLine;
  16826. destMapping.originalColumn = srcMapping.originalColumn;
  16827. if (srcMapping.name) {
  16828. destMapping.name = names.indexOf(srcMapping.name);
  16829. }
  16830. destOriginalMappings.push(destMapping);
  16831. }
  16832. destGeneratedMappings.push(destMapping);
  16833. }
  16834. quickSort$1(smc.__originalMappings, util.compareByOriginalPositions);
  16835. return smc;
  16836. };
  16837. /**
  16838. * The version of the source mapping spec that we are consuming.
  16839. */
  16840. BasicSourceMapConsumer.prototype._version = 3;
  16841. /**
  16842. * The list of original sources.
  16843. */
  16844. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  16845. get: function () {
  16846. return this._absoluteSources.slice();
  16847. }
  16848. });
  16849. /**
  16850. * Provide the JIT with a nice shape / hidden class.
  16851. */
  16852. function Mapping() {
  16853. this.generatedLine = 0;
  16854. this.generatedColumn = 0;
  16855. this.source = null;
  16856. this.originalLine = null;
  16857. this.originalColumn = null;
  16858. this.name = null;
  16859. }
  16860. /**
  16861. * Parse the mappings in a string in to a data structure which we can easily
  16862. * query (the ordered arrays in the `this.__generatedMappings` and
  16863. * `this.__originalMappings` properties).
  16864. */
  16865. BasicSourceMapConsumer.prototype._parseMappings =
  16866. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  16867. var generatedLine = 1;
  16868. var previousGeneratedColumn = 0;
  16869. var previousOriginalLine = 0;
  16870. var previousOriginalColumn = 0;
  16871. var previousSource = 0;
  16872. var previousName = 0;
  16873. var length = aStr.length;
  16874. var index = 0;
  16875. var cachedSegments = {};
  16876. var temp = {};
  16877. var originalMappings = [];
  16878. var generatedMappings = [];
  16879. var mapping, str, segment, end, value;
  16880. while (index < length) {
  16881. if (aStr.charAt(index) === ';') {
  16882. generatedLine++;
  16883. index++;
  16884. previousGeneratedColumn = 0;
  16885. }
  16886. else if (aStr.charAt(index) === ',') {
  16887. index++;
  16888. }
  16889. else {
  16890. mapping = new Mapping();
  16891. mapping.generatedLine = generatedLine;
  16892. // Because each offset is encoded relative to the previous one,
  16893. // many segments often have the same encoding. We can exploit this
  16894. // fact by caching the parsed variable length fields of each segment,
  16895. // allowing us to avoid a second parse if we encounter the same
  16896. // segment again.
  16897. for (end = index; end < length; end++) {
  16898. if (this._charIsMappingSeparator(aStr, end)) {
  16899. break;
  16900. }
  16901. }
  16902. str = aStr.slice(index, end);
  16903. segment = cachedSegments[str];
  16904. if (segment) {
  16905. index += str.length;
  16906. } else {
  16907. segment = [];
  16908. while (index < end) {
  16909. base64Vlq.decode(aStr, index, temp);
  16910. value = temp.value;
  16911. index = temp.rest;
  16912. segment.push(value);
  16913. }
  16914. if (segment.length === 2) {
  16915. throw new Error('Found a source, but no line and column');
  16916. }
  16917. if (segment.length === 3) {
  16918. throw new Error('Found a source and line, but no column');
  16919. }
  16920. cachedSegments[str] = segment;
  16921. }
  16922. // Generated column.
  16923. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  16924. previousGeneratedColumn = mapping.generatedColumn;
  16925. if (segment.length > 1) {
  16926. // Original source.
  16927. mapping.source = previousSource + segment[1];
  16928. previousSource += segment[1];
  16929. // Original line.
  16930. mapping.originalLine = previousOriginalLine + segment[2];
  16931. previousOriginalLine = mapping.originalLine;
  16932. // Lines are stored 0-based
  16933. mapping.originalLine += 1;
  16934. // Original column.
  16935. mapping.originalColumn = previousOriginalColumn + segment[3];
  16936. previousOriginalColumn = mapping.originalColumn;
  16937. if (segment.length > 4) {
  16938. // Original name.
  16939. mapping.name = previousName + segment[4];
  16940. previousName += segment[4];
  16941. }
  16942. }
  16943. generatedMappings.push(mapping);
  16944. if (typeof mapping.originalLine === 'number') {
  16945. originalMappings.push(mapping);
  16946. }
  16947. }
  16948. }
  16949. quickSort$1(generatedMappings, util.compareByGeneratedPositionsDeflated);
  16950. this.__generatedMappings = generatedMappings;
  16951. quickSort$1(originalMappings, util.compareByOriginalPositions);
  16952. this.__originalMappings = originalMappings;
  16953. };
  16954. /**
  16955. * Find the mapping that best matches the hypothetical "needle" mapping that
  16956. * we are searching for in the given "haystack" of mappings.
  16957. */
  16958. BasicSourceMapConsumer.prototype._findMapping =
  16959. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  16960. aColumnName, aComparator, aBias) {
  16961. // To return the position we are searching for, we must first find the
  16962. // mapping for the given position and then return the opposite position it
  16963. // points to. Because the mappings are sorted, we can use binary search to
  16964. // find the best mapping.
  16965. if (aNeedle[aLineName] <= 0) {
  16966. throw new TypeError('Line must be greater than or equal to 1, got '
  16967. + aNeedle[aLineName]);
  16968. }
  16969. if (aNeedle[aColumnName] < 0) {
  16970. throw new TypeError('Column must be greater than or equal to 0, got '
  16971. + aNeedle[aColumnName]);
  16972. }
  16973. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  16974. };
  16975. /**
  16976. * Compute the last column for each generated mapping. The last column is
  16977. * inclusive.
  16978. */
  16979. BasicSourceMapConsumer.prototype.computeColumnSpans =
  16980. function SourceMapConsumer_computeColumnSpans() {
  16981. for (var index = 0; index < this._generatedMappings.length; ++index) {
  16982. var mapping = this._generatedMappings[index];
  16983. // Mappings do not contain a field for the last generated columnt. We
  16984. // can come up with an optimistic estimate, however, by assuming that
  16985. // mappings are contiguous (i.e. given two consecutive mappings, the
  16986. // first mapping ends where the second one starts).
  16987. if (index + 1 < this._generatedMappings.length) {
  16988. var nextMapping = this._generatedMappings[index + 1];
  16989. if (mapping.generatedLine === nextMapping.generatedLine) {
  16990. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  16991. continue;
  16992. }
  16993. }
  16994. // The last mapping for each line spans the entire line.
  16995. mapping.lastGeneratedColumn = Infinity;
  16996. }
  16997. };
  16998. /**
  16999. * Returns the original source, line, and column information for the generated
  17000. * source's line and column positions provided. The only argument is an object
  17001. * with the following properties:
  17002. *
  17003. * - line: The line number in the generated source. The line number
  17004. * is 1-based.
  17005. * - column: The column number in the generated source. The column
  17006. * number is 0-based.
  17007. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  17008. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  17009. * closest element that is smaller than or greater than the one we are
  17010. * searching for, respectively, if the exact element cannot be found.
  17011. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  17012. *
  17013. * and an object is returned with the following properties:
  17014. *
  17015. * - source: The original source file, or null.
  17016. * - line: The line number in the original source, or null. The
  17017. * line number is 1-based.
  17018. * - column: The column number in the original source, or null. The
  17019. * column number is 0-based.
  17020. * - name: The original identifier, or null.
  17021. */
  17022. BasicSourceMapConsumer.prototype.originalPositionFor =
  17023. function SourceMapConsumer_originalPositionFor(aArgs) {
  17024. var needle = {
  17025. generatedLine: util.getArg(aArgs, 'line'),
  17026. generatedColumn: util.getArg(aArgs, 'column')
  17027. };
  17028. var index = this._findMapping(
  17029. needle,
  17030. this._generatedMappings,
  17031. "generatedLine",
  17032. "generatedColumn",
  17033. util.compareByGeneratedPositionsDeflated,
  17034. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  17035. );
  17036. if (index >= 0) {
  17037. var mapping = this._generatedMappings[index];
  17038. if (mapping.generatedLine === needle.generatedLine) {
  17039. var source = util.getArg(mapping, 'source', null);
  17040. if (source !== null) {
  17041. source = this._sources.at(source);
  17042. source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  17043. }
  17044. var name = util.getArg(mapping, 'name', null);
  17045. if (name !== null) {
  17046. name = this._names.at(name);
  17047. }
  17048. return {
  17049. source: source,
  17050. line: util.getArg(mapping, 'originalLine', null),
  17051. column: util.getArg(mapping, 'originalColumn', null),
  17052. name: name
  17053. };
  17054. }
  17055. }
  17056. return {
  17057. source: null,
  17058. line: null,
  17059. column: null,
  17060. name: null
  17061. };
  17062. };
  17063. /**
  17064. * Return true if we have the source content for every source in the source
  17065. * map, false otherwise.
  17066. */
  17067. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  17068. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  17069. if (!this.sourcesContent) {
  17070. return false;
  17071. }
  17072. return this.sourcesContent.length >= this._sources.size() &&
  17073. !this.sourcesContent.some(function (sc) { return sc == null; });
  17074. };
  17075. /**
  17076. * Returns the original source content. The only argument is the url of the
  17077. * original source file. Returns null if no original source content is
  17078. * available.
  17079. */
  17080. BasicSourceMapConsumer.prototype.sourceContentFor =
  17081. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  17082. if (!this.sourcesContent) {
  17083. return null;
  17084. }
  17085. var index = this._findSourceIndex(aSource);
  17086. if (index >= 0) {
  17087. return this.sourcesContent[index];
  17088. }
  17089. var relativeSource = aSource;
  17090. if (this.sourceRoot != null) {
  17091. relativeSource = util.relative(this.sourceRoot, relativeSource);
  17092. }
  17093. var url;
  17094. if (this.sourceRoot != null
  17095. && (url = util.urlParse(this.sourceRoot))) {
  17096. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  17097. // many users. We can help them out when they expect file:// URIs to
  17098. // behave like it would if they were running a local HTTP server. See
  17099. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  17100. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  17101. if (url.scheme == "file"
  17102. && this._sources.has(fileUriAbsPath)) {
  17103. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  17104. }
  17105. if ((!url.path || url.path == "/")
  17106. && this._sources.has("/" + relativeSource)) {
  17107. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  17108. }
  17109. }
  17110. // This function is used recursively from
  17111. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  17112. // don't want to throw if we can't find the source - we just want to
  17113. // return null, so we provide a flag to exit gracefully.
  17114. if (nullOnMissing) {
  17115. return null;
  17116. }
  17117. else {
  17118. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  17119. }
  17120. };
  17121. /**
  17122. * Returns the generated line and column information for the original source,
  17123. * line, and column positions provided. The only argument is an object with
  17124. * the following properties:
  17125. *
  17126. * - source: The filename of the original source.
  17127. * - line: The line number in the original source. The line number
  17128. * is 1-based.
  17129. * - column: The column number in the original source. The column
  17130. * number is 0-based.
  17131. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  17132. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  17133. * closest element that is smaller than or greater than the one we are
  17134. * searching for, respectively, if the exact element cannot be found.
  17135. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  17136. *
  17137. * and an object is returned with the following properties:
  17138. *
  17139. * - line: The line number in the generated source, or null. The
  17140. * line number is 1-based.
  17141. * - column: The column number in the generated source, or null.
  17142. * The column number is 0-based.
  17143. */
  17144. BasicSourceMapConsumer.prototype.generatedPositionFor =
  17145. function SourceMapConsumer_generatedPositionFor(aArgs) {
  17146. var source = util.getArg(aArgs, 'source');
  17147. source = this._findSourceIndex(source);
  17148. if (source < 0) {
  17149. return {
  17150. line: null,
  17151. column: null,
  17152. lastColumn: null
  17153. };
  17154. }
  17155. var needle = {
  17156. source: source,
  17157. originalLine: util.getArg(aArgs, 'line'),
  17158. originalColumn: util.getArg(aArgs, 'column')
  17159. };
  17160. var index = this._findMapping(
  17161. needle,
  17162. this._originalMappings,
  17163. "originalLine",
  17164. "originalColumn",
  17165. util.compareByOriginalPositions,
  17166. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  17167. );
  17168. if (index >= 0) {
  17169. var mapping = this._originalMappings[index];
  17170. if (mapping.source === needle.source) {
  17171. return {
  17172. line: util.getArg(mapping, 'generatedLine', null),
  17173. column: util.getArg(mapping, 'generatedColumn', null),
  17174. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  17175. };
  17176. }
  17177. }
  17178. return {
  17179. line: null,
  17180. column: null,
  17181. lastColumn: null
  17182. };
  17183. };
  17184. var BasicSourceMapConsumer_1 = BasicSourceMapConsumer;
  17185. /**
  17186. * An IndexedSourceMapConsumer instance represents a parsed source map which
  17187. * we can query for information. It differs from BasicSourceMapConsumer in
  17188. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  17189. * input.
  17190. *
  17191. * The first parameter is a raw source map (either as a JSON string, or already
  17192. * parsed to an object). According to the spec for indexed source maps, they
  17193. * have the following attributes:
  17194. *
  17195. * - version: Which version of the source map spec this map is following.
  17196. * - file: Optional. The generated file this source map is associated with.
  17197. * - sections: A list of section definitions.
  17198. *
  17199. * Each value under the "sections" field has two fields:
  17200. * - offset: The offset into the original specified at which this section
  17201. * begins to apply, defined as an object with a "line" and "column"
  17202. * field.
  17203. * - map: A source map definition. This source map could also be indexed,
  17204. * but doesn't have to be.
  17205. *
  17206. * Instead of the "map" field, it's also possible to have a "url" field
  17207. * specifying a URL to retrieve a source map from, but that's currently
  17208. * unsupported.
  17209. *
  17210. * Here's an example source map, taken from the source map spec[0], but
  17211. * modified to omit a section which uses the "url" field.
  17212. *
  17213. * {
  17214. * version : 3,
  17215. * file: "app.js",
  17216. * sections: [{
  17217. * offset: {line:100, column:10},
  17218. * map: {
  17219. * version : 3,
  17220. * file: "section.js",
  17221. * sources: ["foo.js", "bar.js"],
  17222. * names: ["src", "maps", "are", "fun"],
  17223. * mappings: "AAAA,E;;ABCDE;"
  17224. * }
  17225. * }],
  17226. * }
  17227. *
  17228. * The second parameter, if given, is a string whose value is the URL
  17229. * at which the source map was found. This URL is used to compute the
  17230. * sources array.
  17231. *
  17232. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  17233. */
  17234. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  17235. var sourceMap = aSourceMap;
  17236. if (typeof aSourceMap === 'string') {
  17237. sourceMap = util.parseSourceMapInput(aSourceMap);
  17238. }
  17239. var version = util.getArg(sourceMap, 'version');
  17240. var sections = util.getArg(sourceMap, 'sections');
  17241. if (version != this._version) {
  17242. throw new Error('Unsupported version: ' + version);
  17243. }
  17244. this._sources = new ArraySet$2();
  17245. this._names = new ArraySet$2();
  17246. var lastOffset = {
  17247. line: -1,
  17248. column: 0
  17249. };
  17250. this._sections = sections.map(function (s) {
  17251. if (s.url) {
  17252. // The url field will require support for asynchronicity.
  17253. // See https://github.com/mozilla/source-map/issues/16
  17254. throw new Error('Support for url field in sections not implemented.');
  17255. }
  17256. var offset = util.getArg(s, 'offset');
  17257. var offsetLine = util.getArg(offset, 'line');
  17258. var offsetColumn = util.getArg(offset, 'column');
  17259. if (offsetLine < lastOffset.line ||
  17260. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  17261. throw new Error('Section offsets must be ordered and non-overlapping.');
  17262. }
  17263. lastOffset = offset;
  17264. return {
  17265. generatedOffset: {
  17266. // The offset fields are 0-based, but we use 1-based indices when
  17267. // encoding/decoding from VLQ.
  17268. generatedLine: offsetLine + 1,
  17269. generatedColumn: offsetColumn + 1
  17270. },
  17271. consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
  17272. }
  17273. });
  17274. }
  17275. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  17276. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
  17277. /**
  17278. * The version of the source mapping spec that we are consuming.
  17279. */
  17280. IndexedSourceMapConsumer.prototype._version = 3;
  17281. /**
  17282. * The list of original sources.
  17283. */
  17284. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  17285. get: function () {
  17286. var sources = [];
  17287. for (var i = 0; i < this._sections.length; i++) {
  17288. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  17289. sources.push(this._sections[i].consumer.sources[j]);
  17290. }
  17291. }
  17292. return sources;
  17293. }
  17294. });
  17295. /**
  17296. * Returns the original source, line, and column information for the generated
  17297. * source's line and column positions provided. The only argument is an object
  17298. * with the following properties:
  17299. *
  17300. * - line: The line number in the generated source. The line number
  17301. * is 1-based.
  17302. * - column: The column number in the generated source. The column
  17303. * number is 0-based.
  17304. *
  17305. * and an object is returned with the following properties:
  17306. *
  17307. * - source: The original source file, or null.
  17308. * - line: The line number in the original source, or null. The
  17309. * line number is 1-based.
  17310. * - column: The column number in the original source, or null. The
  17311. * column number is 0-based.
  17312. * - name: The original identifier, or null.
  17313. */
  17314. IndexedSourceMapConsumer.prototype.originalPositionFor =
  17315. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  17316. var needle = {
  17317. generatedLine: util.getArg(aArgs, 'line'),
  17318. generatedColumn: util.getArg(aArgs, 'column')
  17319. };
  17320. // Find the section containing the generated position we're trying to map
  17321. // to an original position.
  17322. var sectionIndex = binarySearch.search(needle, this._sections,
  17323. function(needle, section) {
  17324. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  17325. if (cmp) {
  17326. return cmp;
  17327. }
  17328. return (needle.generatedColumn -
  17329. section.generatedOffset.generatedColumn);
  17330. });
  17331. var section = this._sections[sectionIndex];
  17332. if (!section) {
  17333. return {
  17334. source: null,
  17335. line: null,
  17336. column: null,
  17337. name: null
  17338. };
  17339. }
  17340. return section.consumer.originalPositionFor({
  17341. line: needle.generatedLine -
  17342. (section.generatedOffset.generatedLine - 1),
  17343. column: needle.generatedColumn -
  17344. (section.generatedOffset.generatedLine === needle.generatedLine
  17345. ? section.generatedOffset.generatedColumn - 1
  17346. : 0),
  17347. bias: aArgs.bias
  17348. });
  17349. };
  17350. /**
  17351. * Return true if we have the source content for every source in the source
  17352. * map, false otherwise.
  17353. */
  17354. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  17355. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  17356. return this._sections.every(function (s) {
  17357. return s.consumer.hasContentsOfAllSources();
  17358. });
  17359. };
  17360. /**
  17361. * Returns the original source content. The only argument is the url of the
  17362. * original source file. Returns null if no original source content is
  17363. * available.
  17364. */
  17365. IndexedSourceMapConsumer.prototype.sourceContentFor =
  17366. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  17367. for (var i = 0; i < this._sections.length; i++) {
  17368. var section = this._sections[i];
  17369. var content = section.consumer.sourceContentFor(aSource, true);
  17370. if (content) {
  17371. return content;
  17372. }
  17373. }
  17374. if (nullOnMissing) {
  17375. return null;
  17376. }
  17377. else {
  17378. throw new Error('"' + aSource + '" is not in the SourceMap.');
  17379. }
  17380. };
  17381. /**
  17382. * Returns the generated line and column information for the original source,
  17383. * line, and column positions provided. The only argument is an object with
  17384. * the following properties:
  17385. *
  17386. * - source: The filename of the original source.
  17387. * - line: The line number in the original source. The line number
  17388. * is 1-based.
  17389. * - column: The column number in the original source. The column
  17390. * number is 0-based.
  17391. *
  17392. * and an object is returned with the following properties:
  17393. *
  17394. * - line: The line number in the generated source, or null. The
  17395. * line number is 1-based.
  17396. * - column: The column number in the generated source, or null.
  17397. * The column number is 0-based.
  17398. */
  17399. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  17400. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  17401. for (var i = 0; i < this._sections.length; i++) {
  17402. var section = this._sections[i];
  17403. // Only consider this section if the requested source is in the list of
  17404. // sources of the consumer.
  17405. if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
  17406. continue;
  17407. }
  17408. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  17409. if (generatedPosition) {
  17410. var ret = {
  17411. line: generatedPosition.line +
  17412. (section.generatedOffset.generatedLine - 1),
  17413. column: generatedPosition.column +
  17414. (section.generatedOffset.generatedLine === generatedPosition.line
  17415. ? section.generatedOffset.generatedColumn - 1
  17416. : 0)
  17417. };
  17418. return ret;
  17419. }
  17420. }
  17421. return {
  17422. line: null,
  17423. column: null
  17424. };
  17425. };
  17426. /**
  17427. * Parse the mappings in a string in to a data structure which we can easily
  17428. * query (the ordered arrays in the `this.__generatedMappings` and
  17429. * `this.__originalMappings` properties).
  17430. */
  17431. IndexedSourceMapConsumer.prototype._parseMappings =
  17432. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  17433. this.__generatedMappings = [];
  17434. this.__originalMappings = [];
  17435. for (var i = 0; i < this._sections.length; i++) {
  17436. var section = this._sections[i];
  17437. var sectionMappings = section.consumer._generatedMappings;
  17438. for (var j = 0; j < sectionMappings.length; j++) {
  17439. var mapping = sectionMappings[j];
  17440. var source = section.consumer._sources.at(mapping.source);
  17441. source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  17442. this._sources.add(source);
  17443. source = this._sources.indexOf(source);
  17444. var name = null;
  17445. if (mapping.name) {
  17446. name = section.consumer._names.at(mapping.name);
  17447. this._names.add(name);
  17448. name = this._names.indexOf(name);
  17449. }
  17450. // The mappings coming from the consumer for the section have
  17451. // generated positions relative to the start of the section, so we
  17452. // need to offset them to be relative to the start of the concatenated
  17453. // generated file.
  17454. var adjustedMapping = {
  17455. source: source,
  17456. generatedLine: mapping.generatedLine +
  17457. (section.generatedOffset.generatedLine - 1),
  17458. generatedColumn: mapping.generatedColumn +
  17459. (section.generatedOffset.generatedLine === mapping.generatedLine
  17460. ? section.generatedOffset.generatedColumn - 1
  17461. : 0),
  17462. originalLine: mapping.originalLine,
  17463. originalColumn: mapping.originalColumn,
  17464. name: name
  17465. };
  17466. this.__generatedMappings.push(adjustedMapping);
  17467. if (typeof adjustedMapping.originalLine === 'number') {
  17468. this.__originalMappings.push(adjustedMapping);
  17469. }
  17470. }
  17471. }
  17472. quickSort$1(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
  17473. quickSort$1(this.__originalMappings, util.compareByOriginalPositions);
  17474. };
  17475. var IndexedSourceMapConsumer_1 = IndexedSourceMapConsumer;
  17476. var sourceMapConsumer = {
  17477. SourceMapConsumer: SourceMapConsumer_1,
  17478. BasicSourceMapConsumer: BasicSourceMapConsumer_1,
  17479. IndexedSourceMapConsumer: IndexedSourceMapConsumer_1
  17480. };
  17481. /* -*- Mode: js; js-indent-level: 2; -*- */
  17482. /*
  17483. * Copyright 2011 Mozilla Foundation and contributors
  17484. * Licensed under the New BSD license. See LICENSE or:
  17485. * http://opensource.org/licenses/BSD-3-Clause
  17486. */
  17487. var SourceMapGenerator$1 = sourceMapGenerator.SourceMapGenerator;
  17488. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  17489. // operating systems these days (capturing the result).
  17490. var REGEX_NEWLINE = /(\r?\n)/;
  17491. // Newline character code for charCodeAt() comparisons
  17492. var NEWLINE_CODE = 10;
  17493. // Private symbol for identifying `SourceNode`s when multiple versions of
  17494. // the source-map library are loaded. This MUST NOT CHANGE across
  17495. // versions!
  17496. var isSourceNode = "$$$isSourceNode$$$";
  17497. /**
  17498. * SourceNodes provide a way to abstract over interpolating/concatenating
  17499. * snippets of generated JavaScript source code while maintaining the line and
  17500. * column information associated with the original source code.
  17501. *
  17502. * @param aLine The original line number.
  17503. * @param aColumn The original column number.
  17504. * @param aSource The original source's filename.
  17505. * @param aChunks Optional. An array of strings which are snippets of
  17506. * generated JS, or other SourceNodes.
  17507. * @param aName The original identifier.
  17508. */
  17509. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  17510. this.children = [];
  17511. this.sourceContents = {};
  17512. this.line = aLine == null ? null : aLine;
  17513. this.column = aColumn == null ? null : aColumn;
  17514. this.source = aSource == null ? null : aSource;
  17515. this.name = aName == null ? null : aName;
  17516. this[isSourceNode] = true;
  17517. if (aChunks != null) this.add(aChunks);
  17518. }
  17519. /**
  17520. * Creates a SourceNode from generated code and a SourceMapConsumer.
  17521. *
  17522. * @param aGeneratedCode The generated code
  17523. * @param aSourceMapConsumer The SourceMap for the generated code
  17524. * @param aRelativePath Optional. The path that relative sources in the
  17525. * SourceMapConsumer should be relative to.
  17526. */
  17527. SourceNode.fromStringWithSourceMap =
  17528. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  17529. // The SourceNode we want to fill with the generated code
  17530. // and the SourceMap
  17531. var node = new SourceNode();
  17532. // All even indices of this array are one line of the generated code,
  17533. // while all odd indices are the newlines between two adjacent lines
  17534. // (since `REGEX_NEWLINE` captures its match).
  17535. // Processed fragments are accessed by calling `shiftNextLine`.
  17536. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  17537. var remainingLinesIndex = 0;
  17538. var shiftNextLine = function() {
  17539. var lineContents = getNextLine();
  17540. // The last line of a file might not have a newline.
  17541. var newLine = getNextLine() || "";
  17542. return lineContents + newLine;
  17543. function getNextLine() {
  17544. return remainingLinesIndex < remainingLines.length ?
  17545. remainingLines[remainingLinesIndex++] : undefined;
  17546. }
  17547. };
  17548. // We need to remember the position of "remainingLines"
  17549. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  17550. // The generate SourceNodes we need a code range.
  17551. // To extract it current and last mapping is used.
  17552. // Here we store the last mapping.
  17553. var lastMapping = null;
  17554. aSourceMapConsumer.eachMapping(function (mapping) {
  17555. if (lastMapping !== null) {
  17556. // We add the code from "lastMapping" to "mapping":
  17557. // First check if there is a new line in between.
  17558. if (lastGeneratedLine < mapping.generatedLine) {
  17559. // Associate first line with "lastMapping"
  17560. addMappingWithCode(lastMapping, shiftNextLine());
  17561. lastGeneratedLine++;
  17562. lastGeneratedColumn = 0;
  17563. // The remaining code is added without mapping
  17564. } else {
  17565. // There is no new line in between.
  17566. // Associate the code between "lastGeneratedColumn" and
  17567. // "mapping.generatedColumn" with "lastMapping"
  17568. var nextLine = remainingLines[remainingLinesIndex] || '';
  17569. var code = nextLine.substr(0, mapping.generatedColumn -
  17570. lastGeneratedColumn);
  17571. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  17572. lastGeneratedColumn);
  17573. lastGeneratedColumn = mapping.generatedColumn;
  17574. addMappingWithCode(lastMapping, code);
  17575. // No more remaining code, continue
  17576. lastMapping = mapping;
  17577. return;
  17578. }
  17579. }
  17580. // We add the generated code until the first mapping
  17581. // to the SourceNode without any mapping.
  17582. // Each line is added as separate string.
  17583. while (lastGeneratedLine < mapping.generatedLine) {
  17584. node.add(shiftNextLine());
  17585. lastGeneratedLine++;
  17586. }
  17587. if (lastGeneratedColumn < mapping.generatedColumn) {
  17588. var nextLine = remainingLines[remainingLinesIndex] || '';
  17589. node.add(nextLine.substr(0, mapping.generatedColumn));
  17590. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  17591. lastGeneratedColumn = mapping.generatedColumn;
  17592. }
  17593. lastMapping = mapping;
  17594. }, this);
  17595. // We have processed all mappings.
  17596. if (remainingLinesIndex < remainingLines.length) {
  17597. if (lastMapping) {
  17598. // Associate the remaining code in the current line with "lastMapping"
  17599. addMappingWithCode(lastMapping, shiftNextLine());
  17600. }
  17601. // and add the remaining lines without any mapping
  17602. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  17603. }
  17604. // Copy sourcesContent into SourceNode
  17605. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  17606. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  17607. if (content != null) {
  17608. if (aRelativePath != null) {
  17609. sourceFile = util.join(aRelativePath, sourceFile);
  17610. }
  17611. node.setSourceContent(sourceFile, content);
  17612. }
  17613. });
  17614. return node;
  17615. function addMappingWithCode(mapping, code) {
  17616. if (mapping === null || mapping.source === undefined) {
  17617. node.add(code);
  17618. } else {
  17619. var source = aRelativePath
  17620. ? util.join(aRelativePath, mapping.source)
  17621. : mapping.source;
  17622. node.add(new SourceNode(mapping.originalLine,
  17623. mapping.originalColumn,
  17624. source,
  17625. code,
  17626. mapping.name));
  17627. }
  17628. }
  17629. };
  17630. /**
  17631. * Add a chunk of generated JS to this source node.
  17632. *
  17633. * @param aChunk A string snippet of generated JS code, another instance of
  17634. * SourceNode, or an array where each member is one of those things.
  17635. */
  17636. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  17637. if (Array.isArray(aChunk)) {
  17638. aChunk.forEach(function (chunk) {
  17639. this.add(chunk);
  17640. }, this);
  17641. }
  17642. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  17643. if (aChunk) {
  17644. this.children.push(aChunk);
  17645. }
  17646. }
  17647. else {
  17648. throw new TypeError(
  17649. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  17650. );
  17651. }
  17652. return this;
  17653. };
  17654. /**
  17655. * Add a chunk of generated JS to the beginning of this source node.
  17656. *
  17657. * @param aChunk A string snippet of generated JS code, another instance of
  17658. * SourceNode, or an array where each member is one of those things.
  17659. */
  17660. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  17661. if (Array.isArray(aChunk)) {
  17662. for (var i = aChunk.length-1; i >= 0; i--) {
  17663. this.prepend(aChunk[i]);
  17664. }
  17665. }
  17666. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  17667. this.children.unshift(aChunk);
  17668. }
  17669. else {
  17670. throw new TypeError(
  17671. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  17672. );
  17673. }
  17674. return this;
  17675. };
  17676. /**
  17677. * Walk over the tree of JS snippets in this node and its children. The
  17678. * walking function is called once for each snippet of JS and is passed that
  17679. * snippet and the its original associated source's line/column location.
  17680. *
  17681. * @param aFn The traversal function.
  17682. */
  17683. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  17684. var chunk;
  17685. for (var i = 0, len = this.children.length; i < len; i++) {
  17686. chunk = this.children[i];
  17687. if (chunk[isSourceNode]) {
  17688. chunk.walk(aFn);
  17689. }
  17690. else {
  17691. if (chunk !== '') {
  17692. aFn(chunk, { source: this.source,
  17693. line: this.line,
  17694. column: this.column,
  17695. name: this.name });
  17696. }
  17697. }
  17698. }
  17699. };
  17700. /**
  17701. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  17702. * each of `this.children`.
  17703. *
  17704. * @param aSep The separator.
  17705. */
  17706. SourceNode.prototype.join = function SourceNode_join(aSep) {
  17707. var newChildren;
  17708. var i;
  17709. var len = this.children.length;
  17710. if (len > 0) {
  17711. newChildren = [];
  17712. for (i = 0; i < len-1; i++) {
  17713. newChildren.push(this.children[i]);
  17714. newChildren.push(aSep);
  17715. }
  17716. newChildren.push(this.children[i]);
  17717. this.children = newChildren;
  17718. }
  17719. return this;
  17720. };
  17721. /**
  17722. * Call String.prototype.replace on the very right-most source snippet. Useful
  17723. * for trimming whitespace from the end of a source node, etc.
  17724. *
  17725. * @param aPattern The pattern to replace.
  17726. * @param aReplacement The thing to replace the pattern with.
  17727. */
  17728. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  17729. var lastChild = this.children[this.children.length - 1];
  17730. if (lastChild[isSourceNode]) {
  17731. lastChild.replaceRight(aPattern, aReplacement);
  17732. }
  17733. else if (typeof lastChild === 'string') {
  17734. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  17735. }
  17736. else {
  17737. this.children.push(''.replace(aPattern, aReplacement));
  17738. }
  17739. return this;
  17740. };
  17741. /**
  17742. * Set the source content for a source file. This will be added to the SourceMapGenerator
  17743. * in the sourcesContent field.
  17744. *
  17745. * @param aSourceFile The filename of the source file
  17746. * @param aSourceContent The content of the source file
  17747. */
  17748. SourceNode.prototype.setSourceContent =
  17749. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  17750. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  17751. };
  17752. /**
  17753. * Walk over the tree of SourceNodes. The walking function is called for each
  17754. * source file content and is passed the filename and source content.
  17755. *
  17756. * @param aFn The traversal function.
  17757. */
  17758. SourceNode.prototype.walkSourceContents =
  17759. function SourceNode_walkSourceContents(aFn) {
  17760. for (var i = 0, len = this.children.length; i < len; i++) {
  17761. if (this.children[i][isSourceNode]) {
  17762. this.children[i].walkSourceContents(aFn);
  17763. }
  17764. }
  17765. var sources = Object.keys(this.sourceContents);
  17766. for (var i = 0, len = sources.length; i < len; i++) {
  17767. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  17768. }
  17769. };
  17770. /**
  17771. * Return the string representation of this source node. Walks over the tree
  17772. * and concatenates all the various snippets together to one string.
  17773. */
  17774. SourceNode.prototype.toString = function SourceNode_toString() {
  17775. var str = "";
  17776. this.walk(function (chunk) {
  17777. str += chunk;
  17778. });
  17779. return str;
  17780. };
  17781. /**
  17782. * Returns the string representation of this source node along with a source
  17783. * map.
  17784. */
  17785. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  17786. var generated = {
  17787. code: "",
  17788. line: 1,
  17789. column: 0
  17790. };
  17791. var map = new SourceMapGenerator$1(aArgs);
  17792. var sourceMappingActive = false;
  17793. var lastOriginalSource = null;
  17794. var lastOriginalLine = null;
  17795. var lastOriginalColumn = null;
  17796. var lastOriginalName = null;
  17797. this.walk(function (chunk, original) {
  17798. generated.code += chunk;
  17799. if (original.source !== null
  17800. && original.line !== null
  17801. && original.column !== null) {
  17802. if(lastOriginalSource !== original.source
  17803. || lastOriginalLine !== original.line
  17804. || lastOriginalColumn !== original.column
  17805. || lastOriginalName !== original.name) {
  17806. map.addMapping({
  17807. source: original.source,
  17808. original: {
  17809. line: original.line,
  17810. column: original.column
  17811. },
  17812. generated: {
  17813. line: generated.line,
  17814. column: generated.column
  17815. },
  17816. name: original.name
  17817. });
  17818. }
  17819. lastOriginalSource = original.source;
  17820. lastOriginalLine = original.line;
  17821. lastOriginalColumn = original.column;
  17822. lastOriginalName = original.name;
  17823. sourceMappingActive = true;
  17824. } else if (sourceMappingActive) {
  17825. map.addMapping({
  17826. generated: {
  17827. line: generated.line,
  17828. column: generated.column
  17829. }
  17830. });
  17831. lastOriginalSource = null;
  17832. sourceMappingActive = false;
  17833. }
  17834. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  17835. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  17836. generated.line++;
  17837. generated.column = 0;
  17838. // Mappings end at eol
  17839. if (idx + 1 === length) {
  17840. lastOriginalSource = null;
  17841. sourceMappingActive = false;
  17842. } else if (sourceMappingActive) {
  17843. map.addMapping({
  17844. source: original.source,
  17845. original: {
  17846. line: original.line,
  17847. column: original.column
  17848. },
  17849. generated: {
  17850. line: generated.line,
  17851. column: generated.column
  17852. },
  17853. name: original.name
  17854. });
  17855. }
  17856. } else {
  17857. generated.column++;
  17858. }
  17859. }
  17860. });
  17861. this.walkSourceContents(function (sourceFile, sourceContent) {
  17862. map.setSourceContent(sourceFile, sourceContent);
  17863. });
  17864. return { code: generated.code, map: map };
  17865. };
  17866. var SourceNode_1 = SourceNode;
  17867. var sourceNode = {
  17868. SourceNode: SourceNode_1
  17869. };
  17870. /*
  17871. * Copyright 2009-2011 Mozilla Foundation and contributors
  17872. * Licensed under the New BSD license. See LICENSE.txt or:
  17873. * http://opensource.org/licenses/BSD-3-Clause
  17874. */
  17875. var SourceMapGenerator$2 = sourceMapGenerator.SourceMapGenerator;
  17876. var SourceMapConsumer$1 = sourceMapConsumer.SourceMapConsumer;
  17877. var SourceNode$1 = sourceNode.SourceNode;
  17878. var sourceMap = {
  17879. SourceMapGenerator: SourceMapGenerator$2,
  17880. SourceMapConsumer: SourceMapConsumer$1,
  17881. SourceNode: SourceNode$1
  17882. };
  17883. const PURE_ANNOTATION = `/*#__PURE__*/`;
  17884. const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
  17885. 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 }) {
  17886. const context = {
  17887. mode,
  17888. prefixIdentifiers,
  17889. sourceMap,
  17890. filename,
  17891. scopeId,
  17892. optimizeImports,
  17893. runtimeGlobalName,
  17894. runtimeModuleName,
  17895. ssrRuntimeModuleName,
  17896. ssr,
  17897. isTS,
  17898. inSSR,
  17899. source: ast.loc.source,
  17900. code: ``,
  17901. column: 1,
  17902. line: 1,
  17903. offset: 0,
  17904. indentLevel: 0,
  17905. pure: false,
  17906. map: undefined,
  17907. helper(key) {
  17908. return `_${helperNameMap[key]}`;
  17909. },
  17910. push(code, node) {
  17911. context.code += code;
  17912. if (context.map) {
  17913. if (node) {
  17914. let name;
  17915. if (node.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && !node.isStatic) {
  17916. const content = node.content.replace(/^_ctx\./, '');
  17917. if (content !== node.content && isSimpleIdentifier(content)) {
  17918. name = content;
  17919. }
  17920. }
  17921. addMapping(node.loc.start, name);
  17922. }
  17923. advancePositionWithMutation(context, code);
  17924. if (node && node.loc !== locStub) {
  17925. addMapping(node.loc.end);
  17926. }
  17927. }
  17928. },
  17929. indent() {
  17930. newline(++context.indentLevel);
  17931. },
  17932. deindent(withoutNewLine = false) {
  17933. if (withoutNewLine) {
  17934. --context.indentLevel;
  17935. }
  17936. else {
  17937. newline(--context.indentLevel);
  17938. }
  17939. },
  17940. newline() {
  17941. newline(context.indentLevel);
  17942. }
  17943. };
  17944. function newline(n) {
  17945. context.push('\n' + ` `.repeat(n));
  17946. }
  17947. function addMapping(loc, name) {
  17948. context.map.addMapping({
  17949. name,
  17950. source: context.filename,
  17951. original: {
  17952. line: loc.line,
  17953. column: loc.column - 1 // source-map column is 0 based
  17954. },
  17955. generated: {
  17956. line: context.line,
  17957. column: context.column - 1
  17958. }
  17959. });
  17960. }
  17961. if (sourceMap) {
  17962. // lazy require source-map implementation, only in non-browser builds
  17963. context.map = new SourceMapGenerator$2();
  17964. context.map.setSourceContent(filename, context.source);
  17965. }
  17966. return context;
  17967. }
  17968. function generate(ast, options = {}) {
  17969. const context = createCodegenContext(ast, options);
  17970. if (options.onContextCreated)
  17971. options.onContextCreated(context);
  17972. const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
  17973. const hasHelpers = ast.helpers.length > 0;
  17974. const useWithBlock = !prefixIdentifiers && mode !== 'module';
  17975. const genScopeId = scopeId != null && mode === 'module';
  17976. const isSetupInlined = !!options.inline;
  17977. // preambles
  17978. // in setup() inline mode, the preamble is generated in a sub context
  17979. // and returned separately.
  17980. const preambleContext = isSetupInlined
  17981. ? createCodegenContext(ast, options)
  17982. : context;
  17983. if (mode === 'module') {
  17984. genModulePreamble(ast, preambleContext, genScopeId, isSetupInlined);
  17985. }
  17986. else {
  17987. genFunctionPreamble(ast, preambleContext);
  17988. }
  17989. // enter render function
  17990. const functionName = ssr ? `ssrRender` : `render`;
  17991. const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
  17992. if (options.bindingMetadata && !options.inline) {
  17993. // binding optimization args
  17994. args.push('$props', '$setup', '$data', '$options');
  17995. }
  17996. const signature = options.isTS
  17997. ? args.map(arg => `${arg}: any`).join(',')
  17998. : args.join(', ');
  17999. if (isSetupInlined) {
  18000. push(`(${signature}) => {`);
  18001. }
  18002. else {
  18003. push(`function ${functionName}(${signature}) {`);
  18004. }
  18005. indent();
  18006. if (useWithBlock) {
  18007. push(`with (_ctx) {`);
  18008. indent();
  18009. // function mode const declarations should be inside with block
  18010. // also they should be renamed to avoid collision with user properties
  18011. if (hasHelpers) {
  18012. push(`const { ${ast.helpers.map(aliasHelper).join(', ')} } = _Vue`);
  18013. push(`\n`);
  18014. newline();
  18015. }
  18016. }
  18017. // generate asset resolution statements
  18018. if (ast.components.length) {
  18019. genAssets(ast.components, 'component', context);
  18020. if (ast.directives.length || ast.temps > 0) {
  18021. newline();
  18022. }
  18023. }
  18024. if (ast.directives.length) {
  18025. genAssets(ast.directives, 'directive', context);
  18026. if (ast.temps > 0) {
  18027. newline();
  18028. }
  18029. }
  18030. if (ast.temps > 0) {
  18031. push(`let `);
  18032. for (let i = 0; i < ast.temps; i++) {
  18033. push(`${i > 0 ? `, ` : ``}_temp${i}`);
  18034. }
  18035. }
  18036. if (ast.components.length || ast.directives.length || ast.temps) {
  18037. push(`\n`);
  18038. newline();
  18039. }
  18040. // generate the VNode tree expression
  18041. if (!ssr) {
  18042. push(`return `);
  18043. }
  18044. if (ast.codegenNode) {
  18045. genNode(ast.codegenNode, context);
  18046. }
  18047. else {
  18048. push(`null`);
  18049. }
  18050. if (useWithBlock) {
  18051. deindent();
  18052. push(`}`);
  18053. }
  18054. deindent();
  18055. push(`}`);
  18056. return {
  18057. ast,
  18058. code: context.code,
  18059. preamble: isSetupInlined ? preambleContext.code : ``,
  18060. // SourceMapGenerator does have toJSON() method but it's not in the types
  18061. map: context.map ? context.map.toJSON() : undefined
  18062. };
  18063. }
  18064. function genFunctionPreamble(ast, context) {
  18065. const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName, ssrRuntimeModuleName } = context;
  18066. const VueBinding = ssr
  18067. ? `require(${JSON.stringify(runtimeModuleName)})`
  18068. : runtimeGlobalName;
  18069. // Generate const declaration for helpers
  18070. // In prefix mode, we place the const declaration at top so it's done
  18071. // only once; But if we not prefixing, we place the declaration inside the
  18072. // with block so it doesn't incur the `in` check cost for every helper access.
  18073. if (ast.helpers.length > 0) {
  18074. if (prefixIdentifiers) {
  18075. push(`const { ${ast.helpers.map(aliasHelper).join(', ')} } = ${VueBinding}\n`);
  18076. }
  18077. else {
  18078. // "with" mode.
  18079. // save Vue in a separate variable to avoid collision
  18080. push(`const _Vue = ${VueBinding}\n`);
  18081. // in "with" mode, helpers are declared inside the with block to avoid
  18082. // has check cost, but hoists are lifted out of the function - we need
  18083. // to provide the helper here.
  18084. if (ast.hoists.length) {
  18085. const staticHelpers = [
  18086. CREATE_VNODE,
  18087. CREATE_ELEMENT_VNODE,
  18088. CREATE_COMMENT,
  18089. CREATE_TEXT,
  18090. CREATE_STATIC
  18091. ]
  18092. .filter(helper => ast.helpers.includes(helper))
  18093. .map(aliasHelper)
  18094. .join(', ');
  18095. push(`const { ${staticHelpers} } = _Vue\n`);
  18096. }
  18097. }
  18098. }
  18099. // generate variables for ssr helpers
  18100. if (ast.ssrHelpers && ast.ssrHelpers.length) {
  18101. // ssr guarantees prefixIdentifier: true
  18102. push(`const { ${ast.ssrHelpers
  18103. .map(aliasHelper)
  18104. .join(', ')} } = require("${ssrRuntimeModuleName}")\n`);
  18105. }
  18106. genHoists(ast.hoists, context);
  18107. newline();
  18108. push(`return `);
  18109. }
  18110. function genModulePreamble(ast, context, genScopeId, inline) {
  18111. const { push, newline, optimizeImports, runtimeModuleName, ssrRuntimeModuleName } = context;
  18112. if (genScopeId && ast.hoists.length) {
  18113. ast.helpers.push(PUSH_SCOPE_ID, POP_SCOPE_ID);
  18114. }
  18115. // generate import statements for helpers
  18116. if (ast.helpers.length) {
  18117. if (optimizeImports) {
  18118. // when bundled with webpack with code-split, calling an import binding
  18119. // as a function leads to it being wrapped with `Object(a.b)` or `(0,a.b)`,
  18120. // incurring both payload size increase and potential perf overhead.
  18121. // therefore we assign the imports to variables (which is a constant ~50b
  18122. // cost per-component instead of scaling with template size)
  18123. push(`import { ${ast.helpers
  18124. .map(s => helperNameMap[s])
  18125. .join(', ')} } from ${JSON.stringify(runtimeModuleName)}\n`);
  18126. push(`\n// Binding optimization for webpack code-split\nconst ${ast.helpers
  18127. .map(s => `_${helperNameMap[s]} = ${helperNameMap[s]}`)
  18128. .join(', ')}\n`);
  18129. }
  18130. else {
  18131. push(`import { ${ast.helpers
  18132. .map(s => `${helperNameMap[s]} as _${helperNameMap[s]}`)
  18133. .join(', ')} } from ${JSON.stringify(runtimeModuleName)}\n`);
  18134. }
  18135. }
  18136. if (ast.ssrHelpers && ast.ssrHelpers.length) {
  18137. push(`import { ${ast.ssrHelpers
  18138. .map(s => `${helperNameMap[s]} as _${helperNameMap[s]}`)
  18139. .join(', ')} } from "${ssrRuntimeModuleName}"\n`);
  18140. }
  18141. if (ast.imports.length) {
  18142. genImports(ast.imports, context);
  18143. newline();
  18144. }
  18145. genHoists(ast.hoists, context);
  18146. newline();
  18147. if (!inline) {
  18148. push(`export `);
  18149. }
  18150. }
  18151. function genAssets(assets, type, { helper, push, newline, isTS }) {
  18152. const resolver = helper(type === 'component'
  18153. ? RESOLVE_COMPONENT
  18154. : RESOLVE_DIRECTIVE);
  18155. for (let i = 0; i < assets.length; i++) {
  18156. let id = assets[i];
  18157. // potential component implicit self-reference inferred from SFC filename
  18158. const maybeSelfReference = id.endsWith('__self');
  18159. if (maybeSelfReference) {
  18160. id = id.slice(0, -6);
  18161. }
  18162. push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}`);
  18163. if (i < assets.length - 1) {
  18164. newline();
  18165. }
  18166. }
  18167. }
  18168. function genHoists(hoists, context) {
  18169. if (!hoists.length) {
  18170. return;
  18171. }
  18172. context.pure = true;
  18173. const { push, newline, helper, scopeId, mode } = context;
  18174. const genScopeId = scopeId != null && mode !== 'function';
  18175. newline();
  18176. // generate inlined withScopeId helper
  18177. if (genScopeId) {
  18178. push(`const _withScopeId = n => (${helper(PUSH_SCOPE_ID)}("${scopeId}"),n=n(),${helper(POP_SCOPE_ID)}(),n)`);
  18179. newline();
  18180. }
  18181. for (let i = 0; i < hoists.length; i++) {
  18182. const exp = hoists[i];
  18183. if (exp) {
  18184. const needScopeIdWrapper = genScopeId && exp.type === 13 /* NodeTypes.VNODE_CALL */;
  18185. push(`const _hoisted_${i + 1} = ${needScopeIdWrapper ? `${PURE_ANNOTATION} _withScopeId(() => ` : ``}`);
  18186. genNode(exp, context);
  18187. if (needScopeIdWrapper) {
  18188. push(`)`);
  18189. }
  18190. newline();
  18191. }
  18192. }
  18193. context.pure = false;
  18194. }
  18195. function genImports(importsOptions, context) {
  18196. if (!importsOptions.length) {
  18197. return;
  18198. }
  18199. importsOptions.forEach(imports => {
  18200. context.push(`import `);
  18201. genNode(imports.exp, context);
  18202. context.push(` from '${imports.path}'`);
  18203. context.newline();
  18204. });
  18205. }
  18206. function isText$1(n) {
  18207. return (isString(n) ||
  18208. n.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
  18209. n.type === 2 /* NodeTypes.TEXT */ ||
  18210. n.type === 5 /* NodeTypes.INTERPOLATION */ ||
  18211. n.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */);
  18212. }
  18213. function genNodeListAsArray(nodes, context) {
  18214. const multilines = nodes.length > 3 ||
  18215. (nodes.some(n => isArray(n) || !isText$1(n)));
  18216. context.push(`[`);
  18217. multilines && context.indent();
  18218. genNodeList(nodes, context, multilines);
  18219. multilines && context.deindent();
  18220. context.push(`]`);
  18221. }
  18222. function genNodeList(nodes, context, multilines = false, comma = true) {
  18223. const { push, newline } = context;
  18224. for (let i = 0; i < nodes.length; i++) {
  18225. const node = nodes[i];
  18226. if (isString(node)) {
  18227. push(node);
  18228. }
  18229. else if (isArray(node)) {
  18230. genNodeListAsArray(node, context);
  18231. }
  18232. else {
  18233. genNode(node, context);
  18234. }
  18235. if (i < nodes.length - 1) {
  18236. if (multilines) {
  18237. comma && push(',');
  18238. newline();
  18239. }
  18240. else {
  18241. comma && push(', ');
  18242. }
  18243. }
  18244. }
  18245. }
  18246. function genNode(node, context) {
  18247. if (isString(node)) {
  18248. context.push(node);
  18249. return;
  18250. }
  18251. if (isSymbol(node)) {
  18252. context.push(context.helper(node));
  18253. return;
  18254. }
  18255. switch (node.type) {
  18256. case 1 /* NodeTypes.ELEMENT */:
  18257. case 9 /* NodeTypes.IF */:
  18258. case 11 /* NodeTypes.FOR */:
  18259. assert$1(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
  18260. `Apply appropriate transforms first.`);
  18261. genNode(node.codegenNode, context);
  18262. break;
  18263. case 2 /* NodeTypes.TEXT */:
  18264. genText(node, context);
  18265. break;
  18266. case 4 /* NodeTypes.SIMPLE_EXPRESSION */:
  18267. genExpression(node, context);
  18268. break;
  18269. case 5 /* NodeTypes.INTERPOLATION */:
  18270. genInterpolation(node, context);
  18271. break;
  18272. case 12 /* NodeTypes.TEXT_CALL */:
  18273. genNode(node.codegenNode, context);
  18274. break;
  18275. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  18276. genCompoundExpression(node, context);
  18277. break;
  18278. case 3 /* NodeTypes.COMMENT */:
  18279. genComment(node, context);
  18280. break;
  18281. case 13 /* NodeTypes.VNODE_CALL */:
  18282. genVNodeCall(node, context);
  18283. break;
  18284. case 14 /* NodeTypes.JS_CALL_EXPRESSION */:
  18285. genCallExpression(node, context);
  18286. break;
  18287. case 15 /* NodeTypes.JS_OBJECT_EXPRESSION */:
  18288. genObjectExpression(node, context);
  18289. break;
  18290. case 17 /* NodeTypes.JS_ARRAY_EXPRESSION */:
  18291. genArrayExpression(node, context);
  18292. break;
  18293. case 18 /* NodeTypes.JS_FUNCTION_EXPRESSION */:
  18294. genFunctionExpression(node, context);
  18295. break;
  18296. case 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */:
  18297. genConditionalExpression(node, context);
  18298. break;
  18299. case 20 /* NodeTypes.JS_CACHE_EXPRESSION */:
  18300. genCacheExpression(node, context);
  18301. break;
  18302. case 21 /* NodeTypes.JS_BLOCK_STATEMENT */:
  18303. genNodeList(node.body, context, true, false);
  18304. break;
  18305. // SSR only types
  18306. case 22 /* NodeTypes.JS_TEMPLATE_LITERAL */:
  18307. genTemplateLiteral(node, context);
  18308. break;
  18309. case 23 /* NodeTypes.JS_IF_STATEMENT */:
  18310. genIfStatement(node, context);
  18311. break;
  18312. case 24 /* NodeTypes.JS_ASSIGNMENT_EXPRESSION */:
  18313. genAssignmentExpression(node, context);
  18314. break;
  18315. case 25 /* NodeTypes.JS_SEQUENCE_EXPRESSION */:
  18316. genSequenceExpression(node, context);
  18317. break;
  18318. case 26 /* NodeTypes.JS_RETURN_STATEMENT */:
  18319. genReturnStatement(node, context);
  18320. break;
  18321. /* istanbul ignore next */
  18322. case 10 /* NodeTypes.IF_BRANCH */:
  18323. // noop
  18324. break;
  18325. default:
  18326. {
  18327. assert$1(false, `unhandled codegen node type: ${node.type}`);
  18328. // make sure we exhaust all possible types
  18329. const exhaustiveCheck = node;
  18330. return exhaustiveCheck;
  18331. }
  18332. }
  18333. }
  18334. function genText(node, context) {
  18335. context.push(JSON.stringify(node.content), node);
  18336. }
  18337. function genExpression(node, context) {
  18338. const { content, isStatic } = node;
  18339. context.push(isStatic ? JSON.stringify(content) : content, node);
  18340. }
  18341. function genInterpolation(node, context) {
  18342. const { push, helper, pure } = context;
  18343. if (pure)
  18344. push(PURE_ANNOTATION);
  18345. push(`${helper(TO_DISPLAY_STRING)}(`);
  18346. genNode(node.content, context);
  18347. push(`)`);
  18348. }
  18349. function genCompoundExpression(node, context) {
  18350. for (let i = 0; i < node.children.length; i++) {
  18351. const child = node.children[i];
  18352. if (isString(child)) {
  18353. context.push(child);
  18354. }
  18355. else {
  18356. genNode(child, context);
  18357. }
  18358. }
  18359. }
  18360. function genExpressionAsPropertyKey(node, context) {
  18361. const { push } = context;
  18362. if (node.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) {
  18363. push(`[`);
  18364. genCompoundExpression(node, context);
  18365. push(`]`);
  18366. }
  18367. else if (node.isStatic) {
  18368. // only quote keys if necessary
  18369. const text = isSimpleIdentifier(node.content)
  18370. ? node.content
  18371. : JSON.stringify(node.content);
  18372. push(text, node);
  18373. }
  18374. else {
  18375. push(`[${node.content}]`, node);
  18376. }
  18377. }
  18378. function genComment(node, context) {
  18379. const { push, helper, pure } = context;
  18380. if (pure) {
  18381. push(PURE_ANNOTATION);
  18382. }
  18383. push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
  18384. }
  18385. function genVNodeCall(node, context) {
  18386. const { push, helper, pure } = context;
  18387. const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking, isComponent } = node;
  18388. if (directives) {
  18389. push(helper(WITH_DIRECTIVES) + `(`);
  18390. }
  18391. if (isBlock) {
  18392. push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
  18393. }
  18394. if (pure) {
  18395. push(PURE_ANNOTATION);
  18396. }
  18397. const callHelper = isBlock
  18398. ? getVNodeBlockHelper(context.inSSR, isComponent)
  18399. : getVNodeHelper(context.inSSR, isComponent);
  18400. push(helper(callHelper) + `(`, node);
  18401. genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
  18402. push(`)`);
  18403. if (isBlock) {
  18404. push(`)`);
  18405. }
  18406. if (directives) {
  18407. push(`, `);
  18408. genNode(directives, context);
  18409. push(`)`);
  18410. }
  18411. }
  18412. function genNullableArgs(args) {
  18413. let i = args.length;
  18414. while (i--) {
  18415. if (args[i] != null)
  18416. break;
  18417. }
  18418. return args.slice(0, i + 1).map(arg => arg || `null`);
  18419. }
  18420. // JavaScript
  18421. function genCallExpression(node, context) {
  18422. const { push, helper, pure } = context;
  18423. const callee = isString(node.callee) ? node.callee : helper(node.callee);
  18424. if (pure) {
  18425. push(PURE_ANNOTATION);
  18426. }
  18427. push(callee + `(`, node);
  18428. genNodeList(node.arguments, context);
  18429. push(`)`);
  18430. }
  18431. function genObjectExpression(node, context) {
  18432. const { push, indent, deindent, newline } = context;
  18433. const { properties } = node;
  18434. if (!properties.length) {
  18435. push(`{}`, node);
  18436. return;
  18437. }
  18438. const multilines = properties.length > 1 ||
  18439. (properties.some(p => p.value.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */));
  18440. push(multilines ? `{` : `{ `);
  18441. multilines && indent();
  18442. for (let i = 0; i < properties.length; i++) {
  18443. const { key, value } = properties[i];
  18444. // key
  18445. genExpressionAsPropertyKey(key, context);
  18446. push(`: `);
  18447. // value
  18448. genNode(value, context);
  18449. if (i < properties.length - 1) {
  18450. // will only reach this if it's multilines
  18451. push(`,`);
  18452. newline();
  18453. }
  18454. }
  18455. multilines && deindent();
  18456. push(multilines ? `}` : ` }`);
  18457. }
  18458. function genArrayExpression(node, context) {
  18459. genNodeListAsArray(node.elements, context);
  18460. }
  18461. function genFunctionExpression(node, context) {
  18462. const { push, indent, deindent } = context;
  18463. const { params, returns, body, newline, isSlot } = node;
  18464. if (isSlot) {
  18465. // wrap slot functions with owner context
  18466. push(`_${helperNameMap[WITH_CTX]}(`);
  18467. }
  18468. push(`(`, node);
  18469. if (isArray(params)) {
  18470. genNodeList(params, context);
  18471. }
  18472. else if (params) {
  18473. genNode(params, context);
  18474. }
  18475. push(`) => `);
  18476. if (newline || body) {
  18477. push(`{`);
  18478. indent();
  18479. }
  18480. if (returns) {
  18481. if (newline) {
  18482. push(`return `);
  18483. }
  18484. if (isArray(returns)) {
  18485. genNodeListAsArray(returns, context);
  18486. }
  18487. else {
  18488. genNode(returns, context);
  18489. }
  18490. }
  18491. else if (body) {
  18492. genNode(body, context);
  18493. }
  18494. if (newline || body) {
  18495. deindent();
  18496. push(`}`);
  18497. }
  18498. if (isSlot) {
  18499. push(`)`);
  18500. }
  18501. }
  18502. function genConditionalExpression(node, context) {
  18503. const { test, consequent, alternate, newline: needNewline } = node;
  18504. const { push, indent, deindent, newline } = context;
  18505. if (test.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  18506. const needsParens = !isSimpleIdentifier(test.content);
  18507. needsParens && push(`(`);
  18508. genExpression(test, context);
  18509. needsParens && push(`)`);
  18510. }
  18511. else {
  18512. push(`(`);
  18513. genNode(test, context);
  18514. push(`)`);
  18515. }
  18516. needNewline && indent();
  18517. context.indentLevel++;
  18518. needNewline || push(` `);
  18519. push(`? `);
  18520. genNode(consequent, context);
  18521. context.indentLevel--;
  18522. needNewline && newline();
  18523. needNewline || push(` `);
  18524. push(`: `);
  18525. const isNested = alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */;
  18526. if (!isNested) {
  18527. context.indentLevel++;
  18528. }
  18529. genNode(alternate, context);
  18530. if (!isNested) {
  18531. context.indentLevel--;
  18532. }
  18533. needNewline && deindent(true /* without newline */);
  18534. }
  18535. function genCacheExpression(node, context) {
  18536. const { push, helper, indent, deindent, newline } = context;
  18537. push(`_cache[${node.index}] || (`);
  18538. if (node.isVNode) {
  18539. indent();
  18540. push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
  18541. newline();
  18542. }
  18543. push(`_cache[${node.index}] = `);
  18544. genNode(node.value, context);
  18545. if (node.isVNode) {
  18546. push(`,`);
  18547. newline();
  18548. push(`${helper(SET_BLOCK_TRACKING)}(1),`);
  18549. newline();
  18550. push(`_cache[${node.index}]`);
  18551. deindent();
  18552. }
  18553. push(`)`);
  18554. }
  18555. function genTemplateLiteral(node, context) {
  18556. const { push, indent, deindent } = context;
  18557. push('`');
  18558. const l = node.elements.length;
  18559. const multilines = l > 3;
  18560. for (let i = 0; i < l; i++) {
  18561. const e = node.elements[i];
  18562. if (isString(e)) {
  18563. push(e.replace(/(`|\$|\\)/g, '\\$1'));
  18564. }
  18565. else {
  18566. push('${');
  18567. if (multilines)
  18568. indent();
  18569. genNode(e, context);
  18570. if (multilines)
  18571. deindent();
  18572. push('}');
  18573. }
  18574. }
  18575. push('`');
  18576. }
  18577. function genIfStatement(node, context) {
  18578. const { push, indent, deindent } = context;
  18579. const { test, consequent, alternate } = node;
  18580. push(`if (`);
  18581. genNode(test, context);
  18582. push(`) {`);
  18583. indent();
  18584. genNode(consequent, context);
  18585. deindent();
  18586. push(`}`);
  18587. if (alternate) {
  18588. push(` else `);
  18589. if (alternate.type === 23 /* NodeTypes.JS_IF_STATEMENT */) {
  18590. genIfStatement(alternate, context);
  18591. }
  18592. else {
  18593. push(`{`);
  18594. indent();
  18595. genNode(alternate, context);
  18596. deindent();
  18597. push(`}`);
  18598. }
  18599. }
  18600. }
  18601. function genAssignmentExpression(node, context) {
  18602. genNode(node.left, context);
  18603. context.push(` = `);
  18604. genNode(node.right, context);
  18605. }
  18606. function genSequenceExpression(node, context) {
  18607. context.push(`(`);
  18608. genNodeList(node.expressions, context);
  18609. context.push(`)`);
  18610. }
  18611. function genReturnStatement({ returns }, context) {
  18612. context.push(`return `);
  18613. if (isArray(returns)) {
  18614. genNodeListAsArray(returns, context);
  18615. }
  18616. else {
  18617. genNode(returns, context);
  18618. }
  18619. }
  18620. // @ts-check
  18621. /** @typedef { import('estree').BaseNode} BaseNode */
  18622. /** @typedef {{
  18623. skip: () => void;
  18624. remove: () => void;
  18625. replace: (node: BaseNode) => void;
  18626. }} WalkerContext */
  18627. class WalkerBase {
  18628. constructor() {
  18629. /** @type {boolean} */
  18630. this.should_skip = false;
  18631. /** @type {boolean} */
  18632. this.should_remove = false;
  18633. /** @type {BaseNode | null} */
  18634. this.replacement = null;
  18635. /** @type {WalkerContext} */
  18636. this.context = {
  18637. skip: () => (this.should_skip = true),
  18638. remove: () => (this.should_remove = true),
  18639. replace: (node) => (this.replacement = node)
  18640. };
  18641. }
  18642. /**
  18643. *
  18644. * @param {any} parent
  18645. * @param {string} prop
  18646. * @param {number} index
  18647. * @param {BaseNode} node
  18648. */
  18649. replace(parent, prop, index, node) {
  18650. if (parent) {
  18651. if (index !== null) {
  18652. parent[prop][index] = node;
  18653. } else {
  18654. parent[prop] = node;
  18655. }
  18656. }
  18657. }
  18658. /**
  18659. *
  18660. * @param {any} parent
  18661. * @param {string} prop
  18662. * @param {number} index
  18663. */
  18664. remove(parent, prop, index) {
  18665. if (parent) {
  18666. if (index !== null) {
  18667. parent[prop].splice(index, 1);
  18668. } else {
  18669. delete parent[prop];
  18670. }
  18671. }
  18672. }
  18673. }
  18674. // @ts-check
  18675. /** @typedef { import('estree').BaseNode} BaseNode */
  18676. /** @typedef { import('./walker.js').WalkerContext} WalkerContext */
  18677. /** @typedef {(
  18678. * this: WalkerContext,
  18679. * node: BaseNode,
  18680. * parent: BaseNode,
  18681. * key: string,
  18682. * index: number
  18683. * ) => void} SyncHandler */
  18684. class SyncWalker extends WalkerBase {
  18685. /**
  18686. *
  18687. * @param {SyncHandler} enter
  18688. * @param {SyncHandler} leave
  18689. */
  18690. constructor(enter, leave) {
  18691. super();
  18692. /** @type {SyncHandler} */
  18693. this.enter = enter;
  18694. /** @type {SyncHandler} */
  18695. this.leave = leave;
  18696. }
  18697. /**
  18698. *
  18699. * @param {BaseNode} node
  18700. * @param {BaseNode} parent
  18701. * @param {string} [prop]
  18702. * @param {number} [index]
  18703. * @returns {BaseNode}
  18704. */
  18705. visit(node, parent, prop, index) {
  18706. if (node) {
  18707. if (this.enter) {
  18708. const _should_skip = this.should_skip;
  18709. const _should_remove = this.should_remove;
  18710. const _replacement = this.replacement;
  18711. this.should_skip = false;
  18712. this.should_remove = false;
  18713. this.replacement = null;
  18714. this.enter.call(this.context, node, parent, prop, index);
  18715. if (this.replacement) {
  18716. node = this.replacement;
  18717. this.replace(parent, prop, index, node);
  18718. }
  18719. if (this.should_remove) {
  18720. this.remove(parent, prop, index);
  18721. }
  18722. const skipped = this.should_skip;
  18723. const removed = this.should_remove;
  18724. this.should_skip = _should_skip;
  18725. this.should_remove = _should_remove;
  18726. this.replacement = _replacement;
  18727. if (skipped) return node;
  18728. if (removed) return null;
  18729. }
  18730. for (const key in node) {
  18731. const value = node[key];
  18732. if (typeof value !== "object") {
  18733. continue;
  18734. } else if (Array.isArray(value)) {
  18735. for (let i = 0; i < value.length; i += 1) {
  18736. if (value[i] !== null && typeof value[i].type === 'string') {
  18737. if (!this.visit(value[i], node, key, i)) {
  18738. // removed
  18739. i--;
  18740. }
  18741. }
  18742. }
  18743. } else if (value !== null && typeof value.type === "string") {
  18744. this.visit(value, node, key, null);
  18745. }
  18746. }
  18747. if (this.leave) {
  18748. const _replacement = this.replacement;
  18749. const _should_remove = this.should_remove;
  18750. this.replacement = null;
  18751. this.should_remove = false;
  18752. this.leave.call(this.context, node, parent, prop, index);
  18753. if (this.replacement) {
  18754. node = this.replacement;
  18755. this.replace(parent, prop, index, node);
  18756. }
  18757. if (this.should_remove) {
  18758. this.remove(parent, prop, index);
  18759. }
  18760. const removed = this.should_remove;
  18761. this.replacement = _replacement;
  18762. this.should_remove = _should_remove;
  18763. if (removed) return null;
  18764. }
  18765. }
  18766. return node;
  18767. }
  18768. }
  18769. // @ts-check
  18770. /** @typedef { import('estree').BaseNode} BaseNode */
  18771. /** @typedef { import('./sync.js').SyncHandler} SyncHandler */
  18772. /** @typedef { import('./async.js').AsyncHandler} AsyncHandler */
  18773. /**
  18774. *
  18775. * @param {BaseNode} ast
  18776. * @param {{
  18777. * enter?: SyncHandler
  18778. * leave?: SyncHandler
  18779. * }} walker
  18780. * @returns {BaseNode}
  18781. */
  18782. function walk$1(ast, { enter, leave }) {
  18783. const instance = new SyncWalker(enter, leave);
  18784. return instance.visit(ast, null);
  18785. }
  18786. function walkIdentifiers(root, onIdentifier, includeAll = false, parentStack = [], knownIds = Object.create(null)) {
  18787. const rootExp = root.type === 'Program' &&
  18788. root.body[0].type === 'ExpressionStatement' &&
  18789. root.body[0].expression;
  18790. walk$1(root, {
  18791. enter(node, parent) {
  18792. parent && parentStack.push(parent);
  18793. if (parent &&
  18794. parent.type.startsWith('TS') &&
  18795. parent.type !== 'TSAsExpression' &&
  18796. parent.type !== 'TSNonNullExpression' &&
  18797. parent.type !== 'TSTypeAssertion') {
  18798. return this.skip();
  18799. }
  18800. if (node.type === 'Identifier') {
  18801. const isLocal = !!knownIds[node.name];
  18802. const isRefed = isReferencedIdentifier(node, parent, parentStack);
  18803. if (includeAll || (isRefed && !isLocal)) {
  18804. onIdentifier(node, parent, parentStack, isRefed, isLocal);
  18805. }
  18806. }
  18807. else if (node.type === 'ObjectProperty' &&
  18808. parent.type === 'ObjectPattern') {
  18809. node.inPattern = true;
  18810. }
  18811. else if (isFunctionType(node)) {
  18812. // walk function expressions and add its arguments to known identifiers
  18813. // so that we don't prefix them
  18814. walkFunctionParams(node, id => markScopeIdentifier(node, id, knownIds));
  18815. }
  18816. else if (node.type === 'BlockStatement') {
  18817. // #3445 record block-level local variables
  18818. walkBlockDeclarations(node, id => markScopeIdentifier(node, id, knownIds));
  18819. }
  18820. },
  18821. leave(node, parent) {
  18822. parent && parentStack.pop();
  18823. if (node !== rootExp && node.scopeIds) {
  18824. for (const id of node.scopeIds) {
  18825. knownIds[id]--;
  18826. if (knownIds[id] === 0) {
  18827. delete knownIds[id];
  18828. }
  18829. }
  18830. }
  18831. }
  18832. });
  18833. }
  18834. function isReferencedIdentifier(id, parent, parentStack) {
  18835. if (!parent) {
  18836. return true;
  18837. }
  18838. // is a special keyword but parsed as identifier
  18839. if (id.name === 'arguments') {
  18840. return false;
  18841. }
  18842. if (isReferenced(id, parent)) {
  18843. return true;
  18844. }
  18845. // babel's isReferenced check returns false for ids being assigned to, so we
  18846. // need to cover those cases here
  18847. switch (parent.type) {
  18848. case 'AssignmentExpression':
  18849. case 'AssignmentPattern':
  18850. return true;
  18851. case 'ObjectPattern':
  18852. case 'ArrayPattern':
  18853. return isInDestructureAssignment(parent, parentStack);
  18854. }
  18855. return false;
  18856. }
  18857. function isInDestructureAssignment(parent, parentStack) {
  18858. if (parent &&
  18859. (parent.type === 'ObjectProperty' || parent.type === 'ArrayPattern')) {
  18860. let i = parentStack.length;
  18861. while (i--) {
  18862. const p = parentStack[i];
  18863. if (p.type === 'AssignmentExpression') {
  18864. return true;
  18865. }
  18866. else if (p.type !== 'ObjectProperty' && !p.type.endsWith('Pattern')) {
  18867. break;
  18868. }
  18869. }
  18870. }
  18871. return false;
  18872. }
  18873. function walkFunctionParams(node, onIdent) {
  18874. for (const p of node.params) {
  18875. for (const id of extractIdentifiers(p)) {
  18876. onIdent(id);
  18877. }
  18878. }
  18879. }
  18880. function walkBlockDeclarations(block, onIdent) {
  18881. for (const stmt of block.body) {
  18882. if (stmt.type === 'VariableDeclaration') {
  18883. if (stmt.declare)
  18884. continue;
  18885. for (const decl of stmt.declarations) {
  18886. for (const id of extractIdentifiers(decl.id)) {
  18887. onIdent(id);
  18888. }
  18889. }
  18890. }
  18891. else if (stmt.type === 'FunctionDeclaration' ||
  18892. stmt.type === 'ClassDeclaration') {
  18893. if (stmt.declare || !stmt.id)
  18894. continue;
  18895. onIdent(stmt.id);
  18896. }
  18897. }
  18898. }
  18899. function extractIdentifiers(param, nodes = []) {
  18900. switch (param.type) {
  18901. case 'Identifier':
  18902. nodes.push(param);
  18903. break;
  18904. case 'MemberExpression':
  18905. let object = param;
  18906. while (object.type === 'MemberExpression') {
  18907. object = object.object;
  18908. }
  18909. nodes.push(object);
  18910. break;
  18911. case 'ObjectPattern':
  18912. for (const prop of param.properties) {
  18913. if (prop.type === 'RestElement') {
  18914. extractIdentifiers(prop.argument, nodes);
  18915. }
  18916. else {
  18917. extractIdentifiers(prop.value, nodes);
  18918. }
  18919. }
  18920. break;
  18921. case 'ArrayPattern':
  18922. param.elements.forEach(element => {
  18923. if (element)
  18924. extractIdentifiers(element, nodes);
  18925. });
  18926. break;
  18927. case 'RestElement':
  18928. extractIdentifiers(param.argument, nodes);
  18929. break;
  18930. case 'AssignmentPattern':
  18931. extractIdentifiers(param.left, nodes);
  18932. break;
  18933. }
  18934. return nodes;
  18935. }
  18936. function markScopeIdentifier(node, child, knownIds) {
  18937. const { name } = child;
  18938. if (node.scopeIds && node.scopeIds.has(name)) {
  18939. return;
  18940. }
  18941. if (name in knownIds) {
  18942. knownIds[name]++;
  18943. }
  18944. else {
  18945. knownIds[name] = 1;
  18946. }
  18947. (node.scopeIds || (node.scopeIds = new Set())).add(name);
  18948. }
  18949. const isFunctionType = (node) => {
  18950. return /Function(?:Expression|Declaration)$|Method$/.test(node.type);
  18951. };
  18952. const isStaticProperty = (node) => node &&
  18953. (node.type === 'ObjectProperty' || node.type === 'ObjectMethod') &&
  18954. !node.computed;
  18955. const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node;
  18956. /**
  18957. * Copied from https://github.com/babel/babel/blob/main/packages/babel-types/src/validators/isReferenced.ts
  18958. * To avoid runtime dependency on @babel/types (which includes process references)
  18959. * This file should not change very often in babel but we may need to keep it
  18960. * up-to-date from time to time.
  18961. *
  18962. * https://github.com/babel/babel/blob/main/LICENSE
  18963. *
  18964. */
  18965. function isReferenced(node, parent, grandparent) {
  18966. switch (parent.type) {
  18967. // yes: PARENT[NODE]
  18968. // yes: NODE.child
  18969. // no: parent.NODE
  18970. case 'MemberExpression':
  18971. case 'OptionalMemberExpression':
  18972. if (parent.property === node) {
  18973. return !!parent.computed;
  18974. }
  18975. return parent.object === node;
  18976. case 'JSXMemberExpression':
  18977. return parent.object === node;
  18978. // no: let NODE = init;
  18979. // yes: let id = NODE;
  18980. case 'VariableDeclarator':
  18981. return parent.init === node;
  18982. // yes: () => NODE
  18983. // no: (NODE) => {}
  18984. case 'ArrowFunctionExpression':
  18985. return parent.body === node;
  18986. // no: class { #NODE; }
  18987. // no: class { get #NODE() {} }
  18988. // no: class { #NODE() {} }
  18989. // no: class { fn() { return this.#NODE; } }
  18990. case 'PrivateName':
  18991. return false;
  18992. // no: class { NODE() {} }
  18993. // yes: class { [NODE]() {} }
  18994. // no: class { foo(NODE) {} }
  18995. case 'ClassMethod':
  18996. case 'ClassPrivateMethod':
  18997. case 'ObjectMethod':
  18998. if (parent.key === node) {
  18999. return !!parent.computed;
  19000. }
  19001. return false;
  19002. // yes: { [NODE]: "" }
  19003. // no: { NODE: "" }
  19004. // depends: { NODE }
  19005. // depends: { key: NODE }
  19006. case 'ObjectProperty':
  19007. if (parent.key === node) {
  19008. return !!parent.computed;
  19009. }
  19010. // parent.value === node
  19011. return !grandparent || grandparent.type !== 'ObjectPattern';
  19012. // no: class { NODE = value; }
  19013. // yes: class { [NODE] = value; }
  19014. // yes: class { key = NODE; }
  19015. case 'ClassProperty':
  19016. if (parent.key === node) {
  19017. return !!parent.computed;
  19018. }
  19019. return true;
  19020. case 'ClassPrivateProperty':
  19021. return parent.key !== node;
  19022. // no: class NODE {}
  19023. // yes: class Foo extends NODE {}
  19024. case 'ClassDeclaration':
  19025. case 'ClassExpression':
  19026. return parent.superClass === node;
  19027. // yes: left = NODE;
  19028. // no: NODE = right;
  19029. case 'AssignmentExpression':
  19030. return parent.right === node;
  19031. // no: [NODE = foo] = [];
  19032. // yes: [foo = NODE] = [];
  19033. case 'AssignmentPattern':
  19034. return parent.right === node;
  19035. // no: NODE: for (;;) {}
  19036. case 'LabeledStatement':
  19037. return false;
  19038. // no: try {} catch (NODE) {}
  19039. case 'CatchClause':
  19040. return false;
  19041. // no: function foo(...NODE) {}
  19042. case 'RestElement':
  19043. return false;
  19044. case 'BreakStatement':
  19045. case 'ContinueStatement':
  19046. return false;
  19047. // no: function NODE() {}
  19048. // no: function foo(NODE) {}
  19049. case 'FunctionDeclaration':
  19050. case 'FunctionExpression':
  19051. return false;
  19052. // no: export NODE from "foo";
  19053. // no: export * as NODE from "foo";
  19054. case 'ExportNamespaceSpecifier':
  19055. case 'ExportDefaultSpecifier':
  19056. return false;
  19057. // no: export { foo as NODE };
  19058. // yes: export { NODE as foo };
  19059. // no: export { NODE as foo } from "foo";
  19060. case 'ExportSpecifier':
  19061. // @ts-expect-error
  19062. if (grandparent === null || grandparent === void 0 ? void 0 : grandparent.source) {
  19063. return false;
  19064. }
  19065. return parent.local === node;
  19066. // no: import NODE from "foo";
  19067. // no: import * as NODE from "foo";
  19068. // no: import { NODE as foo } from "foo";
  19069. // no: import { foo as NODE } from "foo";
  19070. // no: import NODE from "bar";
  19071. case 'ImportDefaultSpecifier':
  19072. case 'ImportNamespaceSpecifier':
  19073. case 'ImportSpecifier':
  19074. return false;
  19075. // no: import "foo" assert { NODE: "json" }
  19076. case 'ImportAttribute':
  19077. return false;
  19078. // no: <div NODE="foo" />
  19079. case 'JSXAttribute':
  19080. return false;
  19081. // no: [NODE] = [];
  19082. // no: ({ NODE }) = [];
  19083. case 'ObjectPattern':
  19084. case 'ArrayPattern':
  19085. return false;
  19086. // no: new.NODE
  19087. // no: NODE.target
  19088. case 'MetaProperty':
  19089. return false;
  19090. // yes: type X = { someProperty: NODE }
  19091. // no: type X = { NODE: OtherType }
  19092. case 'ObjectTypeProperty':
  19093. return parent.key !== node;
  19094. // yes: enum X { Foo = NODE }
  19095. // no: enum X { NODE }
  19096. case 'TSEnumMember':
  19097. return parent.id !== node;
  19098. // yes: { [NODE]: value }
  19099. // no: { NODE: value }
  19100. case 'TSPropertySignature':
  19101. if (parent.key === node) {
  19102. return !!parent.computed;
  19103. }
  19104. return true;
  19105. }
  19106. return true;
  19107. }
  19108. const isLiteralWhitelisted = /*#__PURE__*/ makeMap('true,false,null,this');
  19109. const transformExpression = (node, context) => {
  19110. if (node.type === 5 /* NodeTypes.INTERPOLATION */) {
  19111. node.content = processExpression(node.content, context);
  19112. }
  19113. else if (node.type === 1 /* NodeTypes.ELEMENT */) {
  19114. // handle directives on element
  19115. for (let i = 0; i < node.props.length; i++) {
  19116. const dir = node.props[i];
  19117. // do not process for v-on & v-for since they are special handled
  19118. if (dir.type === 7 /* NodeTypes.DIRECTIVE */ && dir.name !== 'for') {
  19119. const exp = dir.exp;
  19120. const arg = dir.arg;
  19121. // do not process exp if this is v-on:arg - we need special handling
  19122. // for wrapping inline statements.
  19123. if (exp &&
  19124. exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  19125. !(dir.name === 'on' && arg)) {
  19126. dir.exp = processExpression(exp, context,
  19127. // slot args must be processed as function params
  19128. dir.name === 'slot');
  19129. }
  19130. if (arg && arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && !arg.isStatic) {
  19131. dir.arg = processExpression(arg, context);
  19132. }
  19133. }
  19134. }
  19135. }
  19136. };
  19137. // Important: since this function uses Node.js only dependencies, it should
  19138. // always be used with a leading !false check so that it can be
  19139. // tree-shaken from the browser build.
  19140. function processExpression(node, context,
  19141. // some expressions like v-slot props & v-for aliases should be parsed as
  19142. // function params
  19143. asParams = false,
  19144. // v-on handler values may contain multiple statements
  19145. asRawStatements = false, localVars = Object.create(context.identifiers)) {
  19146. if (!context.prefixIdentifiers || !node.content.trim()) {
  19147. return node;
  19148. }
  19149. const { inline, bindingMetadata } = context;
  19150. const rewriteIdentifier = (raw, parent, id) => {
  19151. const type = hasOwn(bindingMetadata, raw) && bindingMetadata[raw];
  19152. if (inline) {
  19153. // x = y
  19154. const isAssignmentLVal = parent && parent.type === 'AssignmentExpression' && parent.left === id;
  19155. // x++
  19156. const isUpdateArg = parent && parent.type === 'UpdateExpression' && parent.argument === id;
  19157. // ({ x } = y)
  19158. const isDestructureAssignment = parent && isInDestructureAssignment(parent, parentStack);
  19159. if (type === "setup-const" /* BindingTypes.SETUP_CONST */ ||
  19160. type === "setup-reactive-const" /* BindingTypes.SETUP_REACTIVE_CONST */ ||
  19161. localVars[raw]) {
  19162. return raw;
  19163. }
  19164. else if (type === "setup-ref" /* BindingTypes.SETUP_REF */) {
  19165. return `${raw}.value`;
  19166. }
  19167. else if (type === "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */) {
  19168. // const binding that may or may not be ref
  19169. // if it's not a ref, then assignments don't make sense -
  19170. // so we ignore the non-ref assignment case and generate code
  19171. // that assumes the value to be a ref for more efficiency
  19172. return isAssignmentLVal || isUpdateArg || isDestructureAssignment
  19173. ? `${raw}.value`
  19174. : `${context.helperString(UNREF)}(${raw})`;
  19175. }
  19176. else if (type === "setup-let" /* BindingTypes.SETUP_LET */) {
  19177. if (isAssignmentLVal) {
  19178. // let binding.
  19179. // this is a bit more tricky as we need to cover the case where
  19180. // let is a local non-ref value, and we need to replicate the
  19181. // right hand side value.
  19182. // x = y --> isRef(x) ? x.value = y : x = y
  19183. const { right: rVal, operator } = parent;
  19184. const rExp = rawExp.slice(rVal.start - 1, rVal.end - 1);
  19185. const rExpString = stringifyExpression(processExpression(createSimpleExpression(rExp, false), context, false, false, knownIds));
  19186. return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore\n` : ``} ? ${raw}.value ${operator} ${rExpString} : ${raw}`;
  19187. }
  19188. else if (isUpdateArg) {
  19189. // make id replace parent in the code range so the raw update operator
  19190. // is removed
  19191. id.start = parent.start;
  19192. id.end = parent.end;
  19193. const { prefix: isPrefix, operator } = parent;
  19194. const prefix = isPrefix ? operator : ``;
  19195. const postfix = isPrefix ? `` : operator;
  19196. // let binding.
  19197. // x++ --> isRef(a) ? a.value++ : a++
  19198. return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore\n` : ``} ? ${prefix}${raw}.value${postfix} : ${prefix}${raw}${postfix}`;
  19199. }
  19200. else if (isDestructureAssignment) {
  19201. // TODO
  19202. // let binding in a destructure assignment - it's very tricky to
  19203. // handle both possible cases here without altering the original
  19204. // structure of the code, so we just assume it's not a ref here
  19205. // for now
  19206. return raw;
  19207. }
  19208. else {
  19209. return `${context.helperString(UNREF)}(${raw})`;
  19210. }
  19211. }
  19212. else if (type === "props" /* BindingTypes.PROPS */) {
  19213. // use __props which is generated by compileScript so in ts mode
  19214. // it gets correct type
  19215. return genPropsAccessExp(raw);
  19216. }
  19217. else if (type === "props-aliased" /* BindingTypes.PROPS_ALIASED */) {
  19218. // prop with a different local alias (from defineProps() destructure)
  19219. return genPropsAccessExp(bindingMetadata.__propsAliases[raw]);
  19220. }
  19221. }
  19222. else {
  19223. if (type && type.startsWith('setup')) {
  19224. // setup bindings in non-inline mode
  19225. return `$setup.${raw}`;
  19226. }
  19227. else if (type === "props-aliased" /* BindingTypes.PROPS_ALIASED */) {
  19228. return `$props['${bindingMetadata.__propsAliases[raw]}']`;
  19229. }
  19230. else if (type) {
  19231. return `$${type}.${raw}`;
  19232. }
  19233. }
  19234. // fallback to ctx
  19235. return `_ctx.${raw}`;
  19236. };
  19237. // fast path if expression is a simple identifier.
  19238. const rawExp = node.content;
  19239. // bail constant on parens (function invocation) and dot (member access)
  19240. const bailConstant = rawExp.indexOf(`(`) > -1 || rawExp.indexOf('.') > 0;
  19241. if (isSimpleIdentifier(rawExp)) {
  19242. const isScopeVarReference = context.identifiers[rawExp];
  19243. const isAllowedGlobal = isGloballyWhitelisted(rawExp);
  19244. const isLiteral = isLiteralWhitelisted(rawExp);
  19245. if (!asParams && !isScopeVarReference && !isAllowedGlobal && !isLiteral) {
  19246. // const bindings exposed from setup can be skipped for patching but
  19247. // cannot be hoisted to module scope
  19248. if (bindingMetadata[node.content] === "setup-const" /* BindingTypes.SETUP_CONST */) {
  19249. node.constType = 1 /* ConstantTypes.CAN_SKIP_PATCH */;
  19250. }
  19251. node.content = rewriteIdentifier(rawExp);
  19252. }
  19253. else if (!isScopeVarReference) {
  19254. if (isLiteral) {
  19255. node.constType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  19256. }
  19257. else {
  19258. node.constType = 2 /* ConstantTypes.CAN_HOIST */;
  19259. }
  19260. }
  19261. return node;
  19262. }
  19263. let ast;
  19264. // exp needs to be parsed differently:
  19265. // 1. Multiple inline statements (v-on, with presence of `;`): parse as raw
  19266. // exp, but make sure to pad with spaces for consistent ranges
  19267. // 2. Expressions: wrap with parens (for e.g. object expressions)
  19268. // 3. Function arguments (v-for, v-slot): place in a function argument position
  19269. const source = asRawStatements
  19270. ? ` ${rawExp} `
  19271. : `(${rawExp})${asParams ? `=>{}` : ``}`;
  19272. try {
  19273. ast = parse_1(source, {
  19274. plugins: context.expressionPlugins
  19275. }).program;
  19276. }
  19277. catch (e) {
  19278. context.onError(createCompilerError(45 /* ErrorCodes.X_INVALID_EXPRESSION */, node.loc, undefined, e.message));
  19279. return node;
  19280. }
  19281. const ids = [];
  19282. const parentStack = [];
  19283. const knownIds = Object.create(context.identifiers);
  19284. walkIdentifiers(ast, (node, parent, _, isReferenced, isLocal) => {
  19285. if (isStaticPropertyKey(node, parent)) {
  19286. return;
  19287. }
  19288. const needPrefix = isReferenced && canPrefix(node);
  19289. if (needPrefix && !isLocal) {
  19290. if (isStaticProperty(parent) && parent.shorthand) {
  19291. node.prefix = `${node.name}: `;
  19292. }
  19293. node.name = rewriteIdentifier(node.name, parent, node);
  19294. ids.push(node);
  19295. }
  19296. else {
  19297. // The identifier is considered constant unless it's pointing to a
  19298. // local scope variable (a v-for alias, or a v-slot prop)
  19299. if (!(needPrefix && isLocal) && !bailConstant) {
  19300. node.isConstant = true;
  19301. }
  19302. // also generate sub-expressions for other identifiers for better
  19303. // source map support. (except for property keys which are static)
  19304. ids.push(node);
  19305. }
  19306. }, true, // invoke on ALL identifiers
  19307. parentStack, knownIds);
  19308. // We break up the compound expression into an array of strings and sub
  19309. // expressions (for identifiers that have been prefixed). In codegen, if
  19310. // an ExpressionNode has the `.children` property, it will be used instead of
  19311. // `.content`.
  19312. const children = [];
  19313. ids.sort((a, b) => a.start - b.start);
  19314. ids.forEach((id, i) => {
  19315. // range is offset by -1 due to the wrapping parens when parsed
  19316. const start = id.start - 1;
  19317. const end = id.end - 1;
  19318. const last = ids[i - 1];
  19319. const leadingText = rawExp.slice(last ? last.end - 1 : 0, start);
  19320. if (leadingText.length || id.prefix) {
  19321. children.push(leadingText + (id.prefix || ``));
  19322. }
  19323. const source = rawExp.slice(start, end);
  19324. children.push(createSimpleExpression(id.name, false, {
  19325. source,
  19326. start: advancePositionWithClone(node.loc.start, source, start),
  19327. end: advancePositionWithClone(node.loc.start, source, end)
  19328. }, id.isConstant ? 3 /* ConstantTypes.CAN_STRINGIFY */ : 0 /* ConstantTypes.NOT_CONSTANT */));
  19329. if (i === ids.length - 1 && end < rawExp.length) {
  19330. children.push(rawExp.slice(end));
  19331. }
  19332. });
  19333. let ret;
  19334. if (children.length) {
  19335. ret = createCompoundExpression(children, node.loc);
  19336. }
  19337. else {
  19338. ret = node;
  19339. ret.constType = bailConstant
  19340. ? 0 /* ConstantTypes.NOT_CONSTANT */
  19341. : 3 /* ConstantTypes.CAN_STRINGIFY */;
  19342. }
  19343. ret.identifiers = Object.keys(knownIds);
  19344. return ret;
  19345. }
  19346. function canPrefix(id) {
  19347. // skip whitelisted globals
  19348. if (isGloballyWhitelisted(id.name)) {
  19349. return false;
  19350. }
  19351. // special case for webpack compilation
  19352. if (id.name === 'require') {
  19353. return false;
  19354. }
  19355. return true;
  19356. }
  19357. function stringifyExpression(exp) {
  19358. if (isString(exp)) {
  19359. return exp;
  19360. }
  19361. else if (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  19362. return exp.content;
  19363. }
  19364. else {
  19365. return exp.children
  19366. .map(stringifyExpression)
  19367. .join('');
  19368. }
  19369. }
  19370. const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
  19371. return processIf(node, dir, context, (ifNode, branch, isRoot) => {
  19372. // #1587: We need to dynamically increment the key based on the current
  19373. // node's sibling nodes, since chained v-if/else branches are
  19374. // rendered at the same depth
  19375. const siblings = context.parent.children;
  19376. let i = siblings.indexOf(ifNode);
  19377. let key = 0;
  19378. while (i-- >= 0) {
  19379. const sibling = siblings[i];
  19380. if (sibling && sibling.type === 9 /* NodeTypes.IF */) {
  19381. key += sibling.branches.length;
  19382. }
  19383. }
  19384. // Exit callback. Complete the codegenNode when all children have been
  19385. // transformed.
  19386. return () => {
  19387. if (isRoot) {
  19388. ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
  19389. }
  19390. else {
  19391. // attach this branch's codegen node to the v-if root.
  19392. const parentCondition = getParentCondition(ifNode.codegenNode);
  19393. parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
  19394. }
  19395. };
  19396. });
  19397. });
  19398. // target-agnostic transform used for both Client and SSR
  19399. function processIf(node, dir, context, processCodegen) {
  19400. if (dir.name !== 'else' &&
  19401. (!dir.exp || !dir.exp.content.trim())) {
  19402. const loc = dir.exp ? dir.exp.loc : node.loc;
  19403. context.onError(createCompilerError(28 /* ErrorCodes.X_V_IF_NO_EXPRESSION */, dir.loc));
  19404. dir.exp = createSimpleExpression(`true`, false, loc);
  19405. }
  19406. if (context.prefixIdentifiers && dir.exp) {
  19407. // dir.exp can only be simple expression because vIf transform is applied
  19408. // before expression transform.
  19409. dir.exp = processExpression(dir.exp, context);
  19410. }
  19411. if (dir.name === 'if') {
  19412. const branch = createIfBranch(node, dir);
  19413. const ifNode = {
  19414. type: 9 /* NodeTypes.IF */,
  19415. loc: node.loc,
  19416. branches: [branch]
  19417. };
  19418. context.replaceNode(ifNode);
  19419. if (processCodegen) {
  19420. return processCodegen(ifNode, branch, true);
  19421. }
  19422. }
  19423. else {
  19424. // locate the adjacent v-if
  19425. const siblings = context.parent.children;
  19426. const comments = [];
  19427. let i = siblings.indexOf(node);
  19428. while (i-- >= -1) {
  19429. const sibling = siblings[i];
  19430. if (sibling && sibling.type === 3 /* NodeTypes.COMMENT */) {
  19431. context.removeNode(sibling);
  19432. comments.unshift(sibling);
  19433. continue;
  19434. }
  19435. if (sibling &&
  19436. sibling.type === 2 /* NodeTypes.TEXT */ &&
  19437. !sibling.content.trim().length) {
  19438. context.removeNode(sibling);
  19439. continue;
  19440. }
  19441. if (sibling && sibling.type === 9 /* NodeTypes.IF */) {
  19442. // Check if v-else was followed by v-else-if
  19443. if (dir.name === 'else-if' &&
  19444. sibling.branches[sibling.branches.length - 1].condition === undefined) {
  19445. context.onError(createCompilerError(30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  19446. }
  19447. // move the node to the if node's branches
  19448. context.removeNode();
  19449. const branch = createIfBranch(node, dir);
  19450. if (comments.length &&
  19451. // #3619 ignore comments if the v-if is direct child of <transition>
  19452. !(context.parent &&
  19453. context.parent.type === 1 /* NodeTypes.ELEMENT */ &&
  19454. isBuiltInType(context.parent.tag, 'transition'))) {
  19455. branch.children = [...comments, ...branch.children];
  19456. }
  19457. // check if user is forcing same key on different branches
  19458. {
  19459. const key = branch.userKey;
  19460. if (key) {
  19461. sibling.branches.forEach(({ userKey }) => {
  19462. if (isSameKey(userKey, key)) {
  19463. context.onError(createCompilerError(29 /* ErrorCodes.X_V_IF_SAME_KEY */, branch.userKey.loc));
  19464. }
  19465. });
  19466. }
  19467. }
  19468. sibling.branches.push(branch);
  19469. const onExit = processCodegen && processCodegen(sibling, branch, false);
  19470. // since the branch was removed, it will not be traversed.
  19471. // make sure to traverse here.
  19472. traverseNode(branch, context);
  19473. // call on exit
  19474. if (onExit)
  19475. onExit();
  19476. // make sure to reset currentNode after traversal to indicate this
  19477. // node has been removed.
  19478. context.currentNode = null;
  19479. }
  19480. else {
  19481. context.onError(createCompilerError(30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  19482. }
  19483. break;
  19484. }
  19485. }
  19486. }
  19487. function createIfBranch(node, dir) {
  19488. const isTemplateIf = node.tagType === 3 /* ElementTypes.TEMPLATE */;
  19489. return {
  19490. type: 10 /* NodeTypes.IF_BRANCH */,
  19491. loc: node.loc,
  19492. condition: dir.name === 'else' ? undefined : dir.exp,
  19493. children: isTemplateIf && !findDir(node, 'for') ? node.children : [node],
  19494. userKey: findProp(node, `key`),
  19495. isTemplateIf
  19496. };
  19497. }
  19498. function createCodegenNodeForBranch(branch, keyIndex, context) {
  19499. if (branch.condition) {
  19500. return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
  19501. // make sure to pass in asBlock: true so that the comment node call
  19502. // closes the current block.
  19503. createCallExpression(context.helper(CREATE_COMMENT), [
  19504. '"v-if"' ,
  19505. 'true'
  19506. ]));
  19507. }
  19508. else {
  19509. return createChildrenCodegenNode(branch, keyIndex, context);
  19510. }
  19511. }
  19512. function createChildrenCodegenNode(branch, keyIndex, context) {
  19513. const { helper } = context;
  19514. const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* ConstantTypes.CAN_HOIST */));
  19515. const { children } = branch;
  19516. const firstChild = children[0];
  19517. const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* NodeTypes.ELEMENT */;
  19518. if (needFragmentWrapper) {
  19519. if (children.length === 1 && firstChild.type === 11 /* NodeTypes.FOR */) {
  19520. // optimize away nested fragments when child is a ForNode
  19521. const vnodeCall = firstChild.codegenNode;
  19522. injectProp(vnodeCall, keyProperty, context);
  19523. return vnodeCall;
  19524. }
  19525. else {
  19526. let patchFlag = 64 /* PatchFlags.STABLE_FRAGMENT */;
  19527. let patchFlagText = PatchFlagNames[64 /* PatchFlags.STABLE_FRAGMENT */];
  19528. // check if the fragment actually contains a single valid child with
  19529. // the rest being comments
  19530. if (!branch.isTemplateIf &&
  19531. children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */).length === 1) {
  19532. patchFlag |= 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */;
  19533. patchFlagText += `, ${PatchFlagNames[2048 /* PatchFlags.DEV_ROOT_FRAGMENT */]}`;
  19534. }
  19535. return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, false, false /* isComponent */, branch.loc);
  19536. }
  19537. }
  19538. else {
  19539. const ret = firstChild.codegenNode;
  19540. const vnodeCall = getMemoedVNodeCall(ret);
  19541. // Change createVNode to createBlock.
  19542. if (vnodeCall.type === 13 /* NodeTypes.VNODE_CALL */) {
  19543. makeBlock(vnodeCall, context);
  19544. }
  19545. // inject branch key
  19546. injectProp(vnodeCall, keyProperty, context);
  19547. return ret;
  19548. }
  19549. }
  19550. function isSameKey(a, b) {
  19551. if (!a || a.type !== b.type) {
  19552. return false;
  19553. }
  19554. if (a.type === 6 /* NodeTypes.ATTRIBUTE */) {
  19555. if (a.value.content !== b.value.content) {
  19556. return false;
  19557. }
  19558. }
  19559. else {
  19560. // directive
  19561. const exp = a.exp;
  19562. const branchExp = b.exp;
  19563. if (exp.type !== branchExp.type) {
  19564. return false;
  19565. }
  19566. if (exp.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
  19567. exp.isStatic !== branchExp.isStatic ||
  19568. exp.content !== branchExp.content) {
  19569. return false;
  19570. }
  19571. }
  19572. return true;
  19573. }
  19574. function getParentCondition(node) {
  19575. while (true) {
  19576. if (node.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */) {
  19577. if (node.alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */) {
  19578. node = node.alternate;
  19579. }
  19580. else {
  19581. return node;
  19582. }
  19583. }
  19584. else if (node.type === 20 /* NodeTypes.JS_CACHE_EXPRESSION */) {
  19585. node = node.value;
  19586. }
  19587. }
  19588. }
  19589. const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
  19590. const { helper, removeHelper } = context;
  19591. return processFor(node, dir, context, forNode => {
  19592. // create the loop render function expression now, and add the
  19593. // iterator on exit after all children have been traversed
  19594. const renderExp = createCallExpression(helper(RENDER_LIST), [
  19595. forNode.source
  19596. ]);
  19597. const isTemplate = isTemplateNode(node);
  19598. const memo = findDir(node, 'memo');
  19599. const keyProp = findProp(node, `key`);
  19600. const keyExp = keyProp &&
  19601. (keyProp.type === 6 /* NodeTypes.ATTRIBUTE */
  19602. ? createSimpleExpression(keyProp.value.content, true)
  19603. : keyProp.exp);
  19604. const keyProperty = keyProp ? createObjectProperty(`key`, keyExp) : null;
  19605. if (isTemplate) {
  19606. // #2085 / #5288 process :key and v-memo expressions need to be
  19607. // processed on `<template v-for>`. In this case the node is discarded
  19608. // and never traversed so its binding expressions won't be processed
  19609. // by the normal transforms.
  19610. if (memo) {
  19611. memo.exp = processExpression(memo.exp, context);
  19612. }
  19613. if (keyProperty && keyProp.type !== 6 /* NodeTypes.ATTRIBUTE */) {
  19614. keyProperty.value = processExpression(keyProperty.value, context);
  19615. }
  19616. }
  19617. const isStableFragment = forNode.source.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  19618. forNode.source.constType > 0 /* ConstantTypes.NOT_CONSTANT */;
  19619. const fragmentFlag = isStableFragment
  19620. ? 64 /* PatchFlags.STABLE_FRAGMENT */
  19621. : keyProp
  19622. ? 128 /* PatchFlags.KEYED_FRAGMENT */
  19623. : 256 /* PatchFlags.UNKEYED_FRAGMENT */;
  19624. forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
  19625. (` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, false /* isComponent */, node.loc);
  19626. return () => {
  19627. // finish the codegen now that all children have been traversed
  19628. let childBlock;
  19629. const { children } = forNode;
  19630. // check <template v-for> key placement
  19631. if (isTemplate) {
  19632. node.children.some(c => {
  19633. if (c.type === 1 /* NodeTypes.ELEMENT */) {
  19634. const key = findProp(c, 'key');
  19635. if (key) {
  19636. context.onError(createCompilerError(33 /* ErrorCodes.X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
  19637. return true;
  19638. }
  19639. }
  19640. });
  19641. }
  19642. const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* NodeTypes.ELEMENT */;
  19643. const slotOutlet = isSlotOutlet(node)
  19644. ? node
  19645. : isTemplate &&
  19646. node.children.length === 1 &&
  19647. isSlotOutlet(node.children[0])
  19648. ? node.children[0] // api-extractor somehow fails to infer this
  19649. : null;
  19650. if (slotOutlet) {
  19651. // <slot v-for="..."> or <template v-for="..."><slot/></template>
  19652. childBlock = slotOutlet.codegenNode;
  19653. if (isTemplate && keyProperty) {
  19654. // <template v-for="..." :key="..."><slot/></template>
  19655. // we need to inject the key to the renderSlot() call.
  19656. // the props for renderSlot is passed as the 3rd argument.
  19657. injectProp(childBlock, keyProperty, context);
  19658. }
  19659. }
  19660. else if (needFragmentWrapper) {
  19661. // <template v-for="..."> with text or multi-elements
  19662. // should generate a fragment block for each loop
  19663. childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* PatchFlags.STABLE_FRAGMENT */ +
  19664. (` /* ${PatchFlagNames[64 /* PatchFlags.STABLE_FRAGMENT */]} */`
  19665. ), undefined, undefined, true, undefined, false /* isComponent */);
  19666. }
  19667. else {
  19668. // Normal element v-for. Directly use the child's codegenNode
  19669. // but mark it as a block.
  19670. childBlock = children[0]
  19671. .codegenNode;
  19672. if (isTemplate && keyProperty) {
  19673. injectProp(childBlock, keyProperty, context);
  19674. }
  19675. if (childBlock.isBlock !== !isStableFragment) {
  19676. if (childBlock.isBlock) {
  19677. // switch from block to vnode
  19678. removeHelper(OPEN_BLOCK);
  19679. removeHelper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
  19680. }
  19681. else {
  19682. // switch from vnode to block
  19683. removeHelper(getVNodeHelper(context.inSSR, childBlock.isComponent));
  19684. }
  19685. }
  19686. childBlock.isBlock = !isStableFragment;
  19687. if (childBlock.isBlock) {
  19688. helper(OPEN_BLOCK);
  19689. helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
  19690. }
  19691. else {
  19692. helper(getVNodeHelper(context.inSSR, childBlock.isComponent));
  19693. }
  19694. }
  19695. if (memo) {
  19696. const loop = createFunctionExpression(createForLoopParams(forNode.parseResult, [
  19697. createSimpleExpression(`_cached`)
  19698. ]));
  19699. loop.body = createBlockStatement([
  19700. createCompoundExpression([`const _memo = (`, memo.exp, `)`]),
  19701. createCompoundExpression([
  19702. `if (_cached`,
  19703. ...(keyExp ? [` && _cached.key === `, keyExp] : []),
  19704. ` && ${context.helperString(IS_MEMO_SAME)}(_cached, _memo)) return _cached`
  19705. ]),
  19706. createCompoundExpression([`const _item = `, childBlock]),
  19707. createSimpleExpression(`_item.memo = _memo`),
  19708. createSimpleExpression(`return _item`)
  19709. ]);
  19710. renderExp.arguments.push(loop, createSimpleExpression(`_cache`), createSimpleExpression(String(context.cached++)));
  19711. }
  19712. else {
  19713. renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
  19714. }
  19715. };
  19716. });
  19717. });
  19718. // target-agnostic transform used for both Client and SSR
  19719. function processFor(node, dir, context, processCodegen) {
  19720. if (!dir.exp) {
  19721. context.onError(createCompilerError(31 /* ErrorCodes.X_V_FOR_NO_EXPRESSION */, dir.loc));
  19722. return;
  19723. }
  19724. const parseResult = parseForExpression(
  19725. // can only be simple expression because vFor transform is applied
  19726. // before expression transform.
  19727. dir.exp, context);
  19728. if (!parseResult) {
  19729. context.onError(createCompilerError(32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
  19730. return;
  19731. }
  19732. const { addIdentifiers, removeIdentifiers, scopes } = context;
  19733. const { source, value, key, index } = parseResult;
  19734. const forNode = {
  19735. type: 11 /* NodeTypes.FOR */,
  19736. loc: dir.loc,
  19737. source,
  19738. valueAlias: value,
  19739. keyAlias: key,
  19740. objectIndexAlias: index,
  19741. parseResult,
  19742. children: isTemplateNode(node) ? node.children : [node]
  19743. };
  19744. context.replaceNode(forNode);
  19745. // bookkeeping
  19746. scopes.vFor++;
  19747. if (context.prefixIdentifiers) {
  19748. // scope management
  19749. // inject identifiers to context
  19750. value && addIdentifiers(value);
  19751. key && addIdentifiers(key);
  19752. index && addIdentifiers(index);
  19753. }
  19754. const onExit = processCodegen && processCodegen(forNode);
  19755. return () => {
  19756. scopes.vFor--;
  19757. if (context.prefixIdentifiers) {
  19758. value && removeIdentifiers(value);
  19759. key && removeIdentifiers(key);
  19760. index && removeIdentifiers(index);
  19761. }
  19762. if (onExit)
  19763. onExit();
  19764. };
  19765. }
  19766. const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
  19767. // This regex doesn't cover the case if key or index aliases have destructuring,
  19768. // but those do not make sense in the first place, so this works in practice.
  19769. const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
  19770. const stripParensRE = /^\(|\)$/g;
  19771. function parseForExpression(input, context) {
  19772. const loc = input.loc;
  19773. const exp = input.content;
  19774. const inMatch = exp.match(forAliasRE);
  19775. if (!inMatch)
  19776. return;
  19777. const [, LHS, RHS] = inMatch;
  19778. const result = {
  19779. source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
  19780. value: undefined,
  19781. key: undefined,
  19782. index: undefined
  19783. };
  19784. if (context.prefixIdentifiers) {
  19785. result.source = processExpression(result.source, context);
  19786. }
  19787. let valueContent = LHS.trim().replace(stripParensRE, '').trim();
  19788. const trimmedOffset = LHS.indexOf(valueContent);
  19789. const iteratorMatch = valueContent.match(forIteratorRE);
  19790. if (iteratorMatch) {
  19791. valueContent = valueContent.replace(forIteratorRE, '').trim();
  19792. const keyContent = iteratorMatch[1].trim();
  19793. let keyOffset;
  19794. if (keyContent) {
  19795. keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
  19796. result.key = createAliasExpression(loc, keyContent, keyOffset);
  19797. if (context.prefixIdentifiers) {
  19798. result.key = processExpression(result.key, context, true);
  19799. }
  19800. }
  19801. if (iteratorMatch[2]) {
  19802. const indexContent = iteratorMatch[2].trim();
  19803. if (indexContent) {
  19804. result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
  19805. ? keyOffset + keyContent.length
  19806. : trimmedOffset + valueContent.length));
  19807. if (context.prefixIdentifiers) {
  19808. result.index = processExpression(result.index, context, true);
  19809. }
  19810. }
  19811. }
  19812. }
  19813. if (valueContent) {
  19814. result.value = createAliasExpression(loc, valueContent, trimmedOffset);
  19815. if (context.prefixIdentifiers) {
  19816. result.value = processExpression(result.value, context, true);
  19817. }
  19818. }
  19819. return result;
  19820. }
  19821. function createAliasExpression(range, content, offset) {
  19822. return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
  19823. }
  19824. function createForLoopParams({ value, key, index }, memoArgs = []) {
  19825. return createParamsList([value, key, index, ...memoArgs]);
  19826. }
  19827. function createParamsList(args) {
  19828. let i = args.length;
  19829. while (i--) {
  19830. if (args[i])
  19831. break;
  19832. }
  19833. return args
  19834. .slice(0, i + 1)
  19835. .map((arg, i) => arg || createSimpleExpression(`_`.repeat(i + 1), false));
  19836. }
  19837. const defaultFallback = createSimpleExpression(`undefined`, false);
  19838. // A NodeTransform that:
  19839. // 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
  19840. // by transformExpression. This is only applied in non-browser builds with
  19841. // { prefixIdentifiers: true }.
  19842. // 2. Track v-slot depths so that we know a slot is inside another slot.
  19843. // Note the exit callback is executed before buildSlots() on the same node,
  19844. // so only nested slots see positive numbers.
  19845. const trackSlotScopes = (node, context) => {
  19846. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  19847. (node.tagType === 1 /* ElementTypes.COMPONENT */ ||
  19848. node.tagType === 3 /* ElementTypes.TEMPLATE */)) {
  19849. // We are only checking non-empty v-slot here
  19850. // since we only care about slots that introduce scope variables.
  19851. const vSlot = findDir(node, 'slot');
  19852. if (vSlot) {
  19853. const slotProps = vSlot.exp;
  19854. if (context.prefixIdentifiers) {
  19855. slotProps && context.addIdentifiers(slotProps);
  19856. }
  19857. context.scopes.vSlot++;
  19858. return () => {
  19859. if (context.prefixIdentifiers) {
  19860. slotProps && context.removeIdentifiers(slotProps);
  19861. }
  19862. context.scopes.vSlot--;
  19863. };
  19864. }
  19865. }
  19866. };
  19867. // A NodeTransform that tracks scope identifiers for scoped slots with v-for.
  19868. // This transform is only applied in non-browser builds with { prefixIdentifiers: true }
  19869. const trackVForSlotScopes = (node, context) => {
  19870. let vFor;
  19871. if (isTemplateNode(node) &&
  19872. node.props.some(isVSlot) &&
  19873. (vFor = findDir(node, 'for'))) {
  19874. const result = (vFor.parseResult = parseForExpression(vFor.exp, context));
  19875. if (result) {
  19876. const { value, key, index } = result;
  19877. const { addIdentifiers, removeIdentifiers } = context;
  19878. value && addIdentifiers(value);
  19879. key && addIdentifiers(key);
  19880. index && addIdentifiers(index);
  19881. return () => {
  19882. value && removeIdentifiers(value);
  19883. key && removeIdentifiers(key);
  19884. index && removeIdentifiers(index);
  19885. };
  19886. }
  19887. }
  19888. };
  19889. const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
  19890. // Instead of being a DirectiveTransform, v-slot processing is called during
  19891. // transformElement to build the slots object for a component.
  19892. function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
  19893. context.helper(WITH_CTX);
  19894. const { children, loc } = node;
  19895. const slotsProperties = [];
  19896. const dynamicSlots = [];
  19897. // If the slot is inside a v-for or another v-slot, force it to be dynamic
  19898. // since it likely uses a scope variable.
  19899. let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
  19900. // with `prefixIdentifiers: true`, this can be further optimized to make
  19901. // it dynamic only when the slot actually uses the scope variables.
  19902. if (!context.ssr && context.prefixIdentifiers) {
  19903. hasDynamicSlots = hasScopeRef(node, context.identifiers);
  19904. }
  19905. // 1. Check for slot with slotProps on component itself.
  19906. // <Comp v-slot="{ prop }"/>
  19907. const onComponentSlot = findDir(node, 'slot', true);
  19908. if (onComponentSlot) {
  19909. const { arg, exp } = onComponentSlot;
  19910. if (arg && !isStaticExp(arg)) {
  19911. hasDynamicSlots = true;
  19912. }
  19913. slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
  19914. }
  19915. // 2. Iterate through children and check for template slots
  19916. // <template v-slot:foo="{ prop }">
  19917. let hasTemplateSlots = false;
  19918. let hasNamedDefaultSlot = false;
  19919. const implicitDefaultChildren = [];
  19920. const seenSlotNames = new Set();
  19921. let conditionalBranchIndex = 0;
  19922. for (let i = 0; i < children.length; i++) {
  19923. const slotElement = children[i];
  19924. let slotDir;
  19925. if (!isTemplateNode(slotElement) ||
  19926. !(slotDir = findDir(slotElement, 'slot', true))) {
  19927. // not a <template v-slot>, skip.
  19928. if (slotElement.type !== 3 /* NodeTypes.COMMENT */) {
  19929. implicitDefaultChildren.push(slotElement);
  19930. }
  19931. continue;
  19932. }
  19933. if (onComponentSlot) {
  19934. // already has on-component slot - this is incorrect usage.
  19935. context.onError(createCompilerError(37 /* ErrorCodes.X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
  19936. break;
  19937. }
  19938. hasTemplateSlots = true;
  19939. const { children: slotChildren, loc: slotLoc } = slotElement;
  19940. const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
  19941. // check if name is dynamic.
  19942. let staticSlotName;
  19943. if (isStaticExp(slotName)) {
  19944. staticSlotName = slotName ? slotName.content : `default`;
  19945. }
  19946. else {
  19947. hasDynamicSlots = true;
  19948. }
  19949. const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
  19950. // check if this slot is conditional (v-if/v-for)
  19951. let vIf;
  19952. let vElse;
  19953. let vFor;
  19954. if ((vIf = findDir(slotElement, 'if'))) {
  19955. hasDynamicSlots = true;
  19956. dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++), defaultFallback));
  19957. }
  19958. else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
  19959. // find adjacent v-if
  19960. let j = i;
  19961. let prev;
  19962. while (j--) {
  19963. prev = children[j];
  19964. if (prev.type !== 3 /* NodeTypes.COMMENT */) {
  19965. break;
  19966. }
  19967. }
  19968. if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
  19969. // remove node
  19970. children.splice(i, 1);
  19971. i--;
  19972. // attach this slot to previous conditional
  19973. let conditional = dynamicSlots[dynamicSlots.length - 1];
  19974. while (conditional.alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */) {
  19975. conditional = conditional.alternate;
  19976. }
  19977. conditional.alternate = vElse.exp
  19978. ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++), defaultFallback)
  19979. : buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++);
  19980. }
  19981. else {
  19982. context.onError(createCompilerError(30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
  19983. }
  19984. }
  19985. else if ((vFor = findDir(slotElement, 'for'))) {
  19986. hasDynamicSlots = true;
  19987. const parseResult = vFor.parseResult ||
  19988. parseForExpression(vFor.exp, context);
  19989. if (parseResult) {
  19990. // Render the dynamic slots as an array and add it to the createSlot()
  19991. // args. The runtime knows how to handle it appropriately.
  19992. dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
  19993. parseResult.source,
  19994. createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
  19995. ]));
  19996. }
  19997. else {
  19998. context.onError(createCompilerError(32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
  19999. }
  20000. }
  20001. else {
  20002. // check duplicate static names
  20003. if (staticSlotName) {
  20004. if (seenSlotNames.has(staticSlotName)) {
  20005. context.onError(createCompilerError(38 /* ErrorCodes.X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
  20006. continue;
  20007. }
  20008. seenSlotNames.add(staticSlotName);
  20009. if (staticSlotName === 'default') {
  20010. hasNamedDefaultSlot = true;
  20011. }
  20012. }
  20013. slotsProperties.push(createObjectProperty(slotName, slotFunction));
  20014. }
  20015. }
  20016. if (!onComponentSlot) {
  20017. const buildDefaultSlotProperty = (props, children) => {
  20018. const fn = buildSlotFn(props, children, loc);
  20019. return createObjectProperty(`default`, fn);
  20020. };
  20021. if (!hasTemplateSlots) {
  20022. // implicit default slot (on component)
  20023. slotsProperties.push(buildDefaultSlotProperty(undefined, children));
  20024. }
  20025. else if (implicitDefaultChildren.length &&
  20026. // #3766
  20027. // with whitespace: 'preserve', whitespaces between slots will end up in
  20028. // implicitDefaultChildren. Ignore if all implicit children are whitespaces.
  20029. implicitDefaultChildren.some(node => isNonWhitespaceContent(node))) {
  20030. // implicit default slot (mixed with named slots)
  20031. if (hasNamedDefaultSlot) {
  20032. context.onError(createCompilerError(39 /* ErrorCodes.X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
  20033. }
  20034. else {
  20035. slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
  20036. }
  20037. }
  20038. }
  20039. const slotFlag = hasDynamicSlots
  20040. ? 2 /* SlotFlags.DYNAMIC */
  20041. : hasForwardedSlots(node.children)
  20042. ? 3 /* SlotFlags.FORWARDED */
  20043. : 1 /* SlotFlags.STABLE */;
  20044. let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
  20045. // 2 = compiled but dynamic = can skip normalization, but must run diff
  20046. // 1 = compiled and static = can skip normalization AND diff as optimized
  20047. createSimpleExpression(slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
  20048. if (dynamicSlots.length) {
  20049. slots = createCallExpression(context.helper(CREATE_SLOTS), [
  20050. slots,
  20051. createArrayExpression(dynamicSlots)
  20052. ]);
  20053. }
  20054. return {
  20055. slots,
  20056. hasDynamicSlots
  20057. };
  20058. }
  20059. function buildDynamicSlot(name, fn, index) {
  20060. const props = [
  20061. createObjectProperty(`name`, name),
  20062. createObjectProperty(`fn`, fn)
  20063. ];
  20064. if (index != null) {
  20065. props.push(createObjectProperty(`key`, createSimpleExpression(String(index), true)));
  20066. }
  20067. return createObjectExpression(props);
  20068. }
  20069. function hasForwardedSlots(children) {
  20070. for (let i = 0; i < children.length; i++) {
  20071. const child = children[i];
  20072. switch (child.type) {
  20073. case 1 /* NodeTypes.ELEMENT */:
  20074. if (child.tagType === 2 /* ElementTypes.SLOT */ ||
  20075. hasForwardedSlots(child.children)) {
  20076. return true;
  20077. }
  20078. break;
  20079. case 9 /* NodeTypes.IF */:
  20080. if (hasForwardedSlots(child.branches))
  20081. return true;
  20082. break;
  20083. case 10 /* NodeTypes.IF_BRANCH */:
  20084. case 11 /* NodeTypes.FOR */:
  20085. if (hasForwardedSlots(child.children))
  20086. return true;
  20087. break;
  20088. }
  20089. }
  20090. return false;
  20091. }
  20092. function isNonWhitespaceContent(node) {
  20093. if (node.type !== 2 /* NodeTypes.TEXT */ && node.type !== 12 /* NodeTypes.TEXT_CALL */)
  20094. return true;
  20095. return node.type === 2 /* NodeTypes.TEXT */
  20096. ? !!node.content.trim()
  20097. : isNonWhitespaceContent(node.content);
  20098. }
  20099. // some directive transforms (e.g. v-model) may return a symbol for runtime
  20100. // import, which should be used instead of a resolveDirective call.
  20101. const directiveImportMap = new WeakMap();
  20102. // generate a JavaScript AST for this element's codegen
  20103. const transformElement = (node, context) => {
  20104. // perform the work on exit, after all child expressions have been
  20105. // processed and merged.
  20106. return function postTransformElement() {
  20107. node = context.currentNode;
  20108. if (!(node.type === 1 /* NodeTypes.ELEMENT */ &&
  20109. (node.tagType === 0 /* ElementTypes.ELEMENT */ ||
  20110. node.tagType === 1 /* ElementTypes.COMPONENT */))) {
  20111. return;
  20112. }
  20113. const { tag, props } = node;
  20114. const isComponent = node.tagType === 1 /* ElementTypes.COMPONENT */;
  20115. // The goal of the transform is to create a codegenNode implementing the
  20116. // VNodeCall interface.
  20117. let vnodeTag = isComponent
  20118. ? resolveComponentType(node, context)
  20119. : `"${tag}"`;
  20120. const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
  20121. let vnodeProps;
  20122. let vnodeChildren;
  20123. let vnodePatchFlag;
  20124. let patchFlag = 0;
  20125. let vnodeDynamicProps;
  20126. let dynamicPropNames;
  20127. let vnodeDirectives;
  20128. let shouldUseBlock =
  20129. // dynamic component may resolve to plain elements
  20130. isDynamicComponent ||
  20131. vnodeTag === TELEPORT ||
  20132. vnodeTag === SUSPENSE ||
  20133. (!isComponent &&
  20134. // <svg> and <foreignObject> must be forced into blocks so that block
  20135. // updates inside get proper isSVG flag at runtime. (#639, #643)
  20136. // This is technically web-specific, but splitting the logic out of core
  20137. // leads to too much unnecessary complexity.
  20138. (tag === 'svg' || tag === 'foreignObject'));
  20139. // props
  20140. if (props.length > 0) {
  20141. const propsBuildResult = buildProps(node, context, undefined, isComponent, isDynamicComponent);
  20142. vnodeProps = propsBuildResult.props;
  20143. patchFlag = propsBuildResult.patchFlag;
  20144. dynamicPropNames = propsBuildResult.dynamicPropNames;
  20145. const directives = propsBuildResult.directives;
  20146. vnodeDirectives =
  20147. directives && directives.length
  20148. ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
  20149. : undefined;
  20150. if (propsBuildResult.shouldUseBlock) {
  20151. shouldUseBlock = true;
  20152. }
  20153. }
  20154. // children
  20155. if (node.children.length > 0) {
  20156. if (vnodeTag === KEEP_ALIVE) {
  20157. // Although a built-in component, we compile KeepAlive with raw children
  20158. // instead of slot functions so that it can be used inside Transition
  20159. // or other Transition-wrapping HOCs.
  20160. // To ensure correct updates with block optimizations, we need to:
  20161. // 1. Force keep-alive into a block. This avoids its children being
  20162. // collected by a parent block.
  20163. shouldUseBlock = true;
  20164. // 2. Force keep-alive to always be updated, since it uses raw children.
  20165. patchFlag |= 1024 /* PatchFlags.DYNAMIC_SLOTS */;
  20166. if (node.children.length > 1) {
  20167. context.onError(createCompilerError(46 /* ErrorCodes.X_KEEP_ALIVE_INVALID_CHILDREN */, {
  20168. start: node.children[0].loc.start,
  20169. end: node.children[node.children.length - 1].loc.end,
  20170. source: ''
  20171. }));
  20172. }
  20173. }
  20174. const shouldBuildAsSlots = isComponent &&
  20175. // Teleport is not a real component and has dedicated runtime handling
  20176. vnodeTag !== TELEPORT &&
  20177. // explained above.
  20178. vnodeTag !== KEEP_ALIVE;
  20179. if (shouldBuildAsSlots) {
  20180. const { slots, hasDynamicSlots } = buildSlots(node, context);
  20181. vnodeChildren = slots;
  20182. if (hasDynamicSlots) {
  20183. patchFlag |= 1024 /* PatchFlags.DYNAMIC_SLOTS */;
  20184. }
  20185. }
  20186. else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
  20187. const child = node.children[0];
  20188. const type = child.type;
  20189. // check for dynamic text children
  20190. const hasDynamicTextChild = type === 5 /* NodeTypes.INTERPOLATION */ ||
  20191. type === 8 /* NodeTypes.COMPOUND_EXPRESSION */;
  20192. if (hasDynamicTextChild &&
  20193. getConstantType(child, context) === 0 /* ConstantTypes.NOT_CONSTANT */) {
  20194. patchFlag |= 1 /* PatchFlags.TEXT */;
  20195. }
  20196. // pass directly if the only child is a text node
  20197. // (plain / interpolation / expression)
  20198. if (hasDynamicTextChild || type === 2 /* NodeTypes.TEXT */) {
  20199. vnodeChildren = child;
  20200. }
  20201. else {
  20202. vnodeChildren = node.children;
  20203. }
  20204. }
  20205. else {
  20206. vnodeChildren = node.children;
  20207. }
  20208. }
  20209. // patchFlag & dynamicPropNames
  20210. if (patchFlag !== 0) {
  20211. {
  20212. if (patchFlag < 0) {
  20213. // special flags (negative and mutually exclusive)
  20214. vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
  20215. }
  20216. else {
  20217. // bitwise flags
  20218. const flagNames = Object.keys(PatchFlagNames)
  20219. .map(Number)
  20220. .filter(n => n > 0 && patchFlag & n)
  20221. .map(n => PatchFlagNames[n])
  20222. .join(`, `);
  20223. vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
  20224. }
  20225. }
  20226. if (dynamicPropNames && dynamicPropNames.length) {
  20227. vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
  20228. }
  20229. }
  20230. node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, isComponent, node.loc);
  20231. };
  20232. };
  20233. function resolveComponentType(node, context, ssr = false) {
  20234. let { tag } = node;
  20235. // 1. dynamic component
  20236. const isExplicitDynamic = isComponentTag(tag);
  20237. const isProp = findProp(node, 'is');
  20238. if (isProp) {
  20239. if (isExplicitDynamic ||
  20240. (false )) {
  20241. const exp = isProp.type === 6 /* NodeTypes.ATTRIBUTE */
  20242. ? isProp.value && createSimpleExpression(isProp.value.content, true)
  20243. : isProp.exp;
  20244. if (exp) {
  20245. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  20246. exp
  20247. ]);
  20248. }
  20249. }
  20250. else if (isProp.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  20251. isProp.value.content.startsWith('vue:')) {
  20252. // <button is="vue:xxx">
  20253. // if not <component>, only is value that starts with "vue:" will be
  20254. // treated as component by the parse phase and reach here, unless it's
  20255. // compat mode where all is values are considered components
  20256. tag = isProp.value.content.slice(4);
  20257. }
  20258. }
  20259. // 1.5 v-is (TODO: Deprecate)
  20260. const isDir = !isExplicitDynamic && findDir(node, 'is');
  20261. if (isDir && isDir.exp) {
  20262. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  20263. isDir.exp
  20264. ]);
  20265. }
  20266. // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
  20267. const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
  20268. if (builtIn) {
  20269. // built-ins are simply fallthroughs / have special handling during ssr
  20270. // so we don't need to import their runtime equivalents
  20271. if (!ssr)
  20272. context.helper(builtIn);
  20273. return builtIn;
  20274. }
  20275. // 3. user component (from setup bindings)
  20276. // this is skipped in browser build since browser builds do not perform
  20277. // binding analysis.
  20278. {
  20279. const fromSetup = resolveSetupReference(tag, context);
  20280. if (fromSetup) {
  20281. return fromSetup;
  20282. }
  20283. const dotIndex = tag.indexOf('.');
  20284. if (dotIndex > 0) {
  20285. const ns = resolveSetupReference(tag.slice(0, dotIndex), context);
  20286. if (ns) {
  20287. return ns + tag.slice(dotIndex);
  20288. }
  20289. }
  20290. }
  20291. // 4. Self referencing component (inferred from filename)
  20292. if (context.selfName &&
  20293. capitalize(camelize(tag)) === context.selfName) {
  20294. context.helper(RESOLVE_COMPONENT);
  20295. // codegen.ts has special check for __self postfix when generating
  20296. // component imports, which will pass additional `maybeSelfReference` flag
  20297. // to `resolveComponent`.
  20298. context.components.add(tag + `__self`);
  20299. return toValidAssetId(tag, `component`);
  20300. }
  20301. // 5. user component (resolve)
  20302. context.helper(RESOLVE_COMPONENT);
  20303. context.components.add(tag);
  20304. return toValidAssetId(tag, `component`);
  20305. }
  20306. function resolveSetupReference(name, context) {
  20307. const bindings = context.bindingMetadata;
  20308. if (!bindings || bindings.__isScriptSetup === false) {
  20309. return;
  20310. }
  20311. const camelName = camelize(name);
  20312. const PascalName = capitalize(camelName);
  20313. const checkType = (type) => {
  20314. if (bindings[name] === type) {
  20315. return name;
  20316. }
  20317. if (bindings[camelName] === type) {
  20318. return camelName;
  20319. }
  20320. if (bindings[PascalName] === type) {
  20321. return PascalName;
  20322. }
  20323. };
  20324. const fromConst = checkType("setup-const" /* BindingTypes.SETUP_CONST */) ||
  20325. checkType("setup-reactive-const" /* BindingTypes.SETUP_REACTIVE_CONST */);
  20326. if (fromConst) {
  20327. return context.inline
  20328. ? // in inline mode, const setup bindings (e.g. imports) can be used as-is
  20329. fromConst
  20330. : `$setup[${JSON.stringify(fromConst)}]`;
  20331. }
  20332. const fromMaybeRef = checkType("setup-let" /* BindingTypes.SETUP_LET */) ||
  20333. checkType("setup-ref" /* BindingTypes.SETUP_REF */) ||
  20334. checkType("setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */);
  20335. if (fromMaybeRef) {
  20336. return context.inline
  20337. ? // setup scope bindings that may be refs need to be unrefed
  20338. `${context.helperString(UNREF)}(${fromMaybeRef})`
  20339. : `$setup[${JSON.stringify(fromMaybeRef)}]`;
  20340. }
  20341. }
  20342. function buildProps(node, context, props = node.props, isComponent, isDynamicComponent, ssr = false) {
  20343. const { tag, loc: elementLoc, children } = node;
  20344. let properties = [];
  20345. const mergeArgs = [];
  20346. const runtimeDirectives = [];
  20347. const hasChildren = children.length > 0;
  20348. let shouldUseBlock = false;
  20349. // patchFlag analysis
  20350. let patchFlag = 0;
  20351. let hasRef = false;
  20352. let hasClassBinding = false;
  20353. let hasStyleBinding = false;
  20354. let hasHydrationEventBinding = false;
  20355. let hasDynamicKeys = false;
  20356. let hasVnodeHook = false;
  20357. const dynamicPropNames = [];
  20358. const pushMergeArg = (arg) => {
  20359. if (properties.length) {
  20360. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  20361. properties = [];
  20362. }
  20363. if (arg)
  20364. mergeArgs.push(arg);
  20365. };
  20366. const analyzePatchFlag = ({ key, value }) => {
  20367. if (isStaticExp(key)) {
  20368. const name = key.content;
  20369. const isEventHandler = isOn(name);
  20370. if (isEventHandler &&
  20371. (!isComponent || isDynamicComponent) &&
  20372. // omit the flag for click handlers because hydration gives click
  20373. // dedicated fast path.
  20374. name.toLowerCase() !== 'onclick' &&
  20375. // omit v-model handlers
  20376. name !== 'onUpdate:modelValue' &&
  20377. // omit onVnodeXXX hooks
  20378. !isReservedProp(name)) {
  20379. hasHydrationEventBinding = true;
  20380. }
  20381. if (isEventHandler && isReservedProp(name)) {
  20382. hasVnodeHook = true;
  20383. }
  20384. if (value.type === 20 /* NodeTypes.JS_CACHE_EXPRESSION */ ||
  20385. ((value.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
  20386. value.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) &&
  20387. getConstantType(value, context) > 0)) {
  20388. // skip if the prop is a cached handler or has constant value
  20389. return;
  20390. }
  20391. if (name === 'ref') {
  20392. hasRef = true;
  20393. }
  20394. else if (name === 'class') {
  20395. hasClassBinding = true;
  20396. }
  20397. else if (name === 'style') {
  20398. hasStyleBinding = true;
  20399. }
  20400. else if (name !== 'key' && !dynamicPropNames.includes(name)) {
  20401. dynamicPropNames.push(name);
  20402. }
  20403. // treat the dynamic class and style binding of the component as dynamic props
  20404. if (isComponent &&
  20405. (name === 'class' || name === 'style') &&
  20406. !dynamicPropNames.includes(name)) {
  20407. dynamicPropNames.push(name);
  20408. }
  20409. }
  20410. else {
  20411. hasDynamicKeys = true;
  20412. }
  20413. };
  20414. for (let i = 0; i < props.length; i++) {
  20415. // static attribute
  20416. const prop = props[i];
  20417. if (prop.type === 6 /* NodeTypes.ATTRIBUTE */) {
  20418. const { loc, name, value } = prop;
  20419. let isStatic = true;
  20420. if (name === 'ref') {
  20421. hasRef = true;
  20422. if (context.scopes.vFor > 0) {
  20423. properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
  20424. }
  20425. // in inline mode there is no setupState object, so we can't use string
  20426. // keys to set the ref. Instead, we need to transform it to pass the
  20427. // actual ref instead.
  20428. if (value && context.inline) {
  20429. const binding = context.bindingMetadata[value.content];
  20430. if (binding === "setup-let" /* BindingTypes.SETUP_LET */ ||
  20431. binding === "setup-ref" /* BindingTypes.SETUP_REF */ ||
  20432. binding === "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */) {
  20433. isStatic = false;
  20434. properties.push(createObjectProperty(createSimpleExpression('ref_key', true), createSimpleExpression(value.content, true, value.loc)));
  20435. }
  20436. }
  20437. }
  20438. // skip is on <component>, or is="vue:xxx"
  20439. if (name === 'is' &&
  20440. (isComponentTag(tag) ||
  20441. (value && value.content.startsWith('vue:')) ||
  20442. (false ))) {
  20443. continue;
  20444. }
  20445. properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', isStatic, value ? value.loc : loc)));
  20446. }
  20447. else {
  20448. // directives
  20449. const { name, arg, exp, loc } = prop;
  20450. const isVBind = name === 'bind';
  20451. const isVOn = name === 'on';
  20452. // skip v-slot - it is handled by its dedicated transform.
  20453. if (name === 'slot') {
  20454. if (!isComponent) {
  20455. context.onError(createCompilerError(40 /* ErrorCodes.X_V_SLOT_MISPLACED */, loc));
  20456. }
  20457. continue;
  20458. }
  20459. // skip v-once/v-memo - they are handled by dedicated transforms.
  20460. if (name === 'once' || name === 'memo') {
  20461. continue;
  20462. }
  20463. // skip v-is and :is on <component>
  20464. if (name === 'is' ||
  20465. (isVBind &&
  20466. isStaticArgOf(arg, 'is') &&
  20467. (isComponentTag(tag) ||
  20468. (false )))) {
  20469. continue;
  20470. }
  20471. // skip v-on in SSR compilation
  20472. if (isVOn && ssr) {
  20473. continue;
  20474. }
  20475. if (
  20476. // #938: elements with dynamic keys should be forced into blocks
  20477. (isVBind && isStaticArgOf(arg, 'key')) ||
  20478. // inline before-update hooks need to force block so that it is invoked
  20479. // before children
  20480. (isVOn && hasChildren && isStaticArgOf(arg, 'vue:before-update'))) {
  20481. shouldUseBlock = true;
  20482. }
  20483. if (isVBind && isStaticArgOf(arg, 'ref') && context.scopes.vFor > 0) {
  20484. properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
  20485. }
  20486. // special case for v-bind and v-on with no argument
  20487. if (!arg && (isVBind || isVOn)) {
  20488. hasDynamicKeys = true;
  20489. if (exp) {
  20490. if (isVBind) {
  20491. // have to merge early for compat build check
  20492. pushMergeArg();
  20493. mergeArgs.push(exp);
  20494. }
  20495. else {
  20496. // v-on="obj" -> toHandlers(obj)
  20497. pushMergeArg({
  20498. type: 14 /* NodeTypes.JS_CALL_EXPRESSION */,
  20499. loc,
  20500. callee: context.helper(TO_HANDLERS),
  20501. arguments: isComponent ? [exp] : [exp, `true`]
  20502. });
  20503. }
  20504. }
  20505. else {
  20506. context.onError(createCompilerError(isVBind
  20507. ? 34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */
  20508. : 35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */, loc));
  20509. }
  20510. continue;
  20511. }
  20512. const directiveTransform = context.directiveTransforms[name];
  20513. if (directiveTransform) {
  20514. // has built-in directive transform.
  20515. const { props, needRuntime } = directiveTransform(prop, node, context);
  20516. !ssr && props.forEach(analyzePatchFlag);
  20517. if (isVOn && arg && !isStaticExp(arg)) {
  20518. pushMergeArg(createObjectExpression(props, elementLoc));
  20519. }
  20520. else {
  20521. properties.push(...props);
  20522. }
  20523. if (needRuntime) {
  20524. runtimeDirectives.push(prop);
  20525. if (isSymbol(needRuntime)) {
  20526. directiveImportMap.set(prop, needRuntime);
  20527. }
  20528. }
  20529. }
  20530. else if (!isBuiltInDirective(name)) {
  20531. // no built-in transform, this is a user custom directive.
  20532. runtimeDirectives.push(prop);
  20533. // custom dirs may use beforeUpdate so they need to force blocks
  20534. // to ensure before-update gets called before children update
  20535. if (hasChildren) {
  20536. shouldUseBlock = true;
  20537. }
  20538. }
  20539. }
  20540. }
  20541. let propsExpression = undefined;
  20542. // has v-bind="object" or v-on="object", wrap with mergeProps
  20543. if (mergeArgs.length) {
  20544. // close up any not-yet-merged props
  20545. pushMergeArg();
  20546. if (mergeArgs.length > 1) {
  20547. propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
  20548. }
  20549. else {
  20550. // single v-bind with nothing else - no need for a mergeProps call
  20551. propsExpression = mergeArgs[0];
  20552. }
  20553. }
  20554. else if (properties.length) {
  20555. propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
  20556. }
  20557. // patchFlag analysis
  20558. if (hasDynamicKeys) {
  20559. patchFlag |= 16 /* PatchFlags.FULL_PROPS */;
  20560. }
  20561. else {
  20562. if (hasClassBinding && !isComponent) {
  20563. patchFlag |= 2 /* PatchFlags.CLASS */;
  20564. }
  20565. if (hasStyleBinding && !isComponent) {
  20566. patchFlag |= 4 /* PatchFlags.STYLE */;
  20567. }
  20568. if (dynamicPropNames.length) {
  20569. patchFlag |= 8 /* PatchFlags.PROPS */;
  20570. }
  20571. if (hasHydrationEventBinding) {
  20572. patchFlag |= 32 /* PatchFlags.HYDRATE_EVENTS */;
  20573. }
  20574. }
  20575. if (!shouldUseBlock &&
  20576. (patchFlag === 0 || patchFlag === 32 /* PatchFlags.HYDRATE_EVENTS */) &&
  20577. (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
  20578. patchFlag |= 512 /* PatchFlags.NEED_PATCH */;
  20579. }
  20580. // pre-normalize props, SSR is skipped for now
  20581. if (!context.inSSR && propsExpression) {
  20582. switch (propsExpression.type) {
  20583. case 15 /* NodeTypes.JS_OBJECT_EXPRESSION */:
  20584. // means that there is no v-bind,
  20585. // but still need to deal with dynamic key binding
  20586. let classKeyIndex = -1;
  20587. let styleKeyIndex = -1;
  20588. let hasDynamicKey = false;
  20589. for (let i = 0; i < propsExpression.properties.length; i++) {
  20590. const key = propsExpression.properties[i].key;
  20591. if (isStaticExp(key)) {
  20592. if (key.content === 'class') {
  20593. classKeyIndex = i;
  20594. }
  20595. else if (key.content === 'style') {
  20596. styleKeyIndex = i;
  20597. }
  20598. }
  20599. else if (!key.isHandlerKey) {
  20600. hasDynamicKey = true;
  20601. }
  20602. }
  20603. const classProp = propsExpression.properties[classKeyIndex];
  20604. const styleProp = propsExpression.properties[styleKeyIndex];
  20605. // no dynamic key
  20606. if (!hasDynamicKey) {
  20607. if (classProp && !isStaticExp(classProp.value)) {
  20608. classProp.value = createCallExpression(context.helper(NORMALIZE_CLASS), [classProp.value]);
  20609. }
  20610. if (styleProp &&
  20611. // the static style is compiled into an object,
  20612. // so use `hasStyleBinding` to ensure that it is a dynamic style binding
  20613. (hasStyleBinding ||
  20614. (styleProp.value.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  20615. styleProp.value.content.trim()[0] === `[`) ||
  20616. // v-bind:style and style both exist,
  20617. // v-bind:style with static literal object
  20618. styleProp.value.type === 17 /* NodeTypes.JS_ARRAY_EXPRESSION */)) {
  20619. styleProp.value = createCallExpression(context.helper(NORMALIZE_STYLE), [styleProp.value]);
  20620. }
  20621. }
  20622. else {
  20623. // dynamic key binding, wrap with `normalizeProps`
  20624. propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [propsExpression]);
  20625. }
  20626. break;
  20627. case 14 /* NodeTypes.JS_CALL_EXPRESSION */:
  20628. // mergeProps call, do nothing
  20629. break;
  20630. default:
  20631. // single v-bind
  20632. propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [
  20633. createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [
  20634. propsExpression
  20635. ])
  20636. ]);
  20637. break;
  20638. }
  20639. }
  20640. return {
  20641. props: propsExpression,
  20642. directives: runtimeDirectives,
  20643. patchFlag,
  20644. dynamicPropNames,
  20645. shouldUseBlock
  20646. };
  20647. }
  20648. // Dedupe props in an object literal.
  20649. // Literal duplicated attributes would have been warned during the parse phase,
  20650. // however, it's possible to encounter duplicated `onXXX` handlers with different
  20651. // modifiers. We also need to merge static and dynamic class / style attributes.
  20652. // - onXXX handlers / style: merge into array
  20653. // - class: merge into single expression with concatenation
  20654. function dedupeProperties(properties) {
  20655. const knownProps = new Map();
  20656. const deduped = [];
  20657. for (let i = 0; i < properties.length; i++) {
  20658. const prop = properties[i];
  20659. // dynamic keys are always allowed
  20660. if (prop.key.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
  20661. deduped.push(prop);
  20662. continue;
  20663. }
  20664. const name = prop.key.content;
  20665. const existing = knownProps.get(name);
  20666. if (existing) {
  20667. if (name === 'style' || name === 'class' || isOn(name)) {
  20668. mergeAsArray(existing, prop);
  20669. }
  20670. // unexpected duplicate, should have emitted error during parse
  20671. }
  20672. else {
  20673. knownProps.set(name, prop);
  20674. deduped.push(prop);
  20675. }
  20676. }
  20677. return deduped;
  20678. }
  20679. function mergeAsArray(existing, incoming) {
  20680. if (existing.value.type === 17 /* NodeTypes.JS_ARRAY_EXPRESSION */) {
  20681. existing.value.elements.push(incoming.value);
  20682. }
  20683. else {
  20684. existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
  20685. }
  20686. }
  20687. function buildDirectiveArgs(dir, context) {
  20688. const dirArgs = [];
  20689. const runtime = directiveImportMap.get(dir);
  20690. if (runtime) {
  20691. // built-in directive with runtime
  20692. dirArgs.push(context.helperString(runtime));
  20693. }
  20694. else {
  20695. // user directive.
  20696. // see if we have directives exposed via <script setup>
  20697. const fromSetup = resolveSetupReference('v-' + dir.name, context);
  20698. if (fromSetup) {
  20699. dirArgs.push(fromSetup);
  20700. }
  20701. else {
  20702. // inject statement for resolving directive
  20703. context.helper(RESOLVE_DIRECTIVE);
  20704. context.directives.add(dir.name);
  20705. dirArgs.push(toValidAssetId(dir.name, `directive`));
  20706. }
  20707. }
  20708. const { loc } = dir;
  20709. if (dir.exp)
  20710. dirArgs.push(dir.exp);
  20711. if (dir.arg) {
  20712. if (!dir.exp) {
  20713. dirArgs.push(`void 0`);
  20714. }
  20715. dirArgs.push(dir.arg);
  20716. }
  20717. if (Object.keys(dir.modifiers).length) {
  20718. if (!dir.arg) {
  20719. if (!dir.exp) {
  20720. dirArgs.push(`void 0`);
  20721. }
  20722. dirArgs.push(`void 0`);
  20723. }
  20724. const trueExpression = createSimpleExpression(`true`, false, loc);
  20725. dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
  20726. }
  20727. return createArrayExpression(dirArgs, dir.loc);
  20728. }
  20729. function stringifyDynamicPropNames(props) {
  20730. let propsNamesString = `[`;
  20731. for (let i = 0, l = props.length; i < l; i++) {
  20732. propsNamesString += JSON.stringify(props[i]);
  20733. if (i < l - 1)
  20734. propsNamesString += ', ';
  20735. }
  20736. return propsNamesString + `]`;
  20737. }
  20738. function isComponentTag(tag) {
  20739. return tag === 'component' || tag === 'Component';
  20740. }
  20741. const transformSlotOutlet = (node, context) => {
  20742. if (isSlotOutlet(node)) {
  20743. const { children, loc } = node;
  20744. const { slotName, slotProps } = processSlotOutlet(node, context);
  20745. const slotArgs = [
  20746. context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
  20747. slotName,
  20748. '{}',
  20749. 'undefined',
  20750. 'true'
  20751. ];
  20752. let expectedLen = 2;
  20753. if (slotProps) {
  20754. slotArgs[2] = slotProps;
  20755. expectedLen = 3;
  20756. }
  20757. if (children.length) {
  20758. slotArgs[3] = createFunctionExpression([], children, false, false, loc);
  20759. expectedLen = 4;
  20760. }
  20761. if (context.scopeId && !context.slotted) {
  20762. expectedLen = 5;
  20763. }
  20764. slotArgs.splice(expectedLen); // remove unused arguments
  20765. node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
  20766. }
  20767. };
  20768. function processSlotOutlet(node, context) {
  20769. let slotName = `"default"`;
  20770. let slotProps = undefined;
  20771. const nonNameProps = [];
  20772. for (let i = 0; i < node.props.length; i++) {
  20773. const p = node.props[i];
  20774. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  20775. if (p.value) {
  20776. if (p.name === 'name') {
  20777. slotName = JSON.stringify(p.value.content);
  20778. }
  20779. else {
  20780. p.name = camelize(p.name);
  20781. nonNameProps.push(p);
  20782. }
  20783. }
  20784. }
  20785. else {
  20786. if (p.name === 'bind' && isStaticArgOf(p.arg, 'name')) {
  20787. if (p.exp)
  20788. slotName = p.exp;
  20789. }
  20790. else {
  20791. if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
  20792. p.arg.content = camelize(p.arg.content);
  20793. }
  20794. nonNameProps.push(p);
  20795. }
  20796. }
  20797. }
  20798. if (nonNameProps.length > 0) {
  20799. const { props, directives } = buildProps(node, context, nonNameProps, false, false);
  20800. slotProps = props;
  20801. if (directives.length) {
  20802. context.onError(createCompilerError(36 /* ErrorCodes.X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
  20803. }
  20804. }
  20805. return {
  20806. slotName,
  20807. slotProps
  20808. };
  20809. }
  20810. const fnExpRE = /^\s*([\w$_]+|(async\s*)?\([^)]*?\))\s*(:[^=]+)?=>|^\s*(async\s+)?function(?:\s+[\w$]+)?\s*\(/;
  20811. const transformOn = (dir, node, context, augmentor) => {
  20812. const { loc, modifiers, arg } = dir;
  20813. if (!dir.exp && !modifiers.length) {
  20814. context.onError(createCompilerError(35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */, loc));
  20815. }
  20816. let eventName;
  20817. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  20818. if (arg.isStatic) {
  20819. let rawName = arg.content;
  20820. // TODO deprecate @vnodeXXX usage
  20821. if (rawName.startsWith('vue:')) {
  20822. rawName = `vnode-${rawName.slice(4)}`;
  20823. }
  20824. const eventString = node.tagType !== 0 /* ElementTypes.ELEMENT */ ||
  20825. rawName.startsWith('vnode') ||
  20826. !/[A-Z]/.test(rawName)
  20827. ? // for non-element and vnode lifecycle event listeners, auto convert
  20828. // it to camelCase. See issue #2249
  20829. toHandlerKey(camelize(rawName))
  20830. : // preserve case for plain element listeners that have uppercase
  20831. // letters, as these may be custom elements' custom events
  20832. `on:${rawName}`;
  20833. eventName = createSimpleExpression(eventString, true, arg.loc);
  20834. }
  20835. else {
  20836. // #2388
  20837. eventName = createCompoundExpression([
  20838. `${context.helperString(TO_HANDLER_KEY)}(`,
  20839. arg,
  20840. `)`
  20841. ]);
  20842. }
  20843. }
  20844. else {
  20845. // already a compound expression.
  20846. eventName = arg;
  20847. eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
  20848. eventName.children.push(`)`);
  20849. }
  20850. // handler processing
  20851. let exp = dir.exp;
  20852. if (exp && !exp.content.trim()) {
  20853. exp = undefined;
  20854. }
  20855. let shouldCache = context.cacheHandlers && !exp && !context.inVOnce;
  20856. if (exp) {
  20857. const isMemberExp = isMemberExpression(exp.content, context);
  20858. const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
  20859. const hasMultipleStatements = exp.content.includes(`;`);
  20860. // process the expression since it's been skipped
  20861. if (context.prefixIdentifiers) {
  20862. isInlineStatement && context.addIdentifiers(`$event`);
  20863. exp = dir.exp = processExpression(exp, context, false, hasMultipleStatements);
  20864. isInlineStatement && context.removeIdentifiers(`$event`);
  20865. // with scope analysis, the function is hoistable if it has no reference
  20866. // to scope variables.
  20867. shouldCache =
  20868. context.cacheHandlers &&
  20869. // unnecessary to cache inside v-once
  20870. !context.inVOnce &&
  20871. // runtime constants don't need to be cached
  20872. // (this is analyzed by compileScript in SFC <script setup>)
  20873. !(exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && exp.constType > 0) &&
  20874. // #1541 bail if this is a member exp handler passed to a component -
  20875. // we need to use the original function to preserve arity,
  20876. // e.g. <transition> relies on checking cb.length to determine
  20877. // transition end handling. Inline function is ok since its arity
  20878. // is preserved even when cached.
  20879. !(isMemberExp && node.tagType === 1 /* ElementTypes.COMPONENT */) &&
  20880. // bail if the function references closure variables (v-for, v-slot)
  20881. // it must be passed fresh to avoid stale values.
  20882. !hasScopeRef(exp, context.identifiers);
  20883. // If the expression is optimizable and is a member expression pointing
  20884. // to a function, turn it into invocation (and wrap in an arrow function
  20885. // below) so that it always accesses the latest value when called - thus
  20886. // avoiding the need to be patched.
  20887. if (shouldCache && isMemberExp) {
  20888. if (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  20889. exp.content = `${exp.content} && ${exp.content}(...args)`;
  20890. }
  20891. else {
  20892. exp.children = [...exp.children, ` && `, ...exp.children, `(...args)`];
  20893. }
  20894. }
  20895. }
  20896. if (isInlineStatement || (shouldCache && isMemberExp)) {
  20897. // wrap inline statement in a function expression
  20898. exp = createCompoundExpression([
  20899. `${isInlineStatement
  20900. ? context.isTS
  20901. ? `($event: any)`
  20902. : `$event`
  20903. : `${context.isTS ? `\n//@ts-ignore\n` : ``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
  20904. exp,
  20905. hasMultipleStatements ? `}` : `)`
  20906. ]);
  20907. }
  20908. }
  20909. let ret = {
  20910. props: [
  20911. createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
  20912. ]
  20913. };
  20914. // apply extended compiler augmentor
  20915. if (augmentor) {
  20916. ret = augmentor(ret);
  20917. }
  20918. if (shouldCache) {
  20919. // cache handlers so that it's always the same handler being passed down.
  20920. // this avoids unnecessary re-renders when users use inline handlers on
  20921. // components.
  20922. ret.props[0].value = context.cache(ret.props[0].value);
  20923. }
  20924. // mark the key as handler for props normalization check
  20925. ret.props.forEach(p => (p.key.isHandlerKey = true));
  20926. return ret;
  20927. };
  20928. // v-bind without arg is handled directly in ./transformElements.ts due to it affecting
  20929. // codegen for the entire props object. This transform here is only for v-bind
  20930. // *with* args.
  20931. const transformBind = (dir, _node, context) => {
  20932. const { exp, modifiers, loc } = dir;
  20933. const arg = dir.arg;
  20934. if (arg.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  20935. arg.children.unshift(`(`);
  20936. arg.children.push(`) || ""`);
  20937. }
  20938. else if (!arg.isStatic) {
  20939. arg.content = `${arg.content} || ""`;
  20940. }
  20941. // .sync is replaced by v-model:arg
  20942. if (modifiers.includes('camel')) {
  20943. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  20944. if (arg.isStatic) {
  20945. arg.content = camelize(arg.content);
  20946. }
  20947. else {
  20948. arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
  20949. }
  20950. }
  20951. else {
  20952. arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
  20953. arg.children.push(`)`);
  20954. }
  20955. }
  20956. if (!context.inSSR) {
  20957. if (modifiers.includes('prop')) {
  20958. injectPrefix(arg, '.');
  20959. }
  20960. if (modifiers.includes('attr')) {
  20961. injectPrefix(arg, '^');
  20962. }
  20963. }
  20964. if (!exp ||
  20965. (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && !exp.content.trim())) {
  20966. context.onError(createCompilerError(34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */, loc));
  20967. return {
  20968. props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
  20969. };
  20970. }
  20971. return {
  20972. props: [createObjectProperty(arg, exp)]
  20973. };
  20974. };
  20975. const injectPrefix = (arg, prefix) => {
  20976. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  20977. if (arg.isStatic) {
  20978. arg.content = prefix + arg.content;
  20979. }
  20980. else {
  20981. arg.content = `\`${prefix}\${${arg.content}}\``;
  20982. }
  20983. }
  20984. else {
  20985. arg.children.unshift(`'${prefix}' + (`);
  20986. arg.children.push(`)`);
  20987. }
  20988. };
  20989. // Merge adjacent text nodes and expressions into a single expression
  20990. // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
  20991. const transformText = (node, context) => {
  20992. if (node.type === 0 /* NodeTypes.ROOT */ ||
  20993. node.type === 1 /* NodeTypes.ELEMENT */ ||
  20994. node.type === 11 /* NodeTypes.FOR */ ||
  20995. node.type === 10 /* NodeTypes.IF_BRANCH */) {
  20996. // perform the transform on node exit so that all expressions have already
  20997. // been processed.
  20998. return () => {
  20999. const children = node.children;
  21000. let currentContainer = undefined;
  21001. let hasText = false;
  21002. for (let i = 0; i < children.length; i++) {
  21003. const child = children[i];
  21004. if (isText(child)) {
  21005. hasText = true;
  21006. for (let j = i + 1; j < children.length; j++) {
  21007. const next = children[j];
  21008. if (isText(next)) {
  21009. if (!currentContainer) {
  21010. currentContainer = children[i] = createCompoundExpression([child], child.loc);
  21011. }
  21012. // merge adjacent text node into current
  21013. currentContainer.children.push(` + `, next);
  21014. children.splice(j, 1);
  21015. j--;
  21016. }
  21017. else {
  21018. currentContainer = undefined;
  21019. break;
  21020. }
  21021. }
  21022. }
  21023. }
  21024. if (!hasText ||
  21025. // if this is a plain element with a single text child, leave it
  21026. // as-is since the runtime has dedicated fast path for this by directly
  21027. // setting textContent of the element.
  21028. // for component root it's always normalized anyway.
  21029. (children.length === 1 &&
  21030. (node.type === 0 /* NodeTypes.ROOT */ ||
  21031. (node.type === 1 /* NodeTypes.ELEMENT */ &&
  21032. node.tagType === 0 /* ElementTypes.ELEMENT */ &&
  21033. // #3756
  21034. // custom directives can potentially add DOM elements arbitrarily,
  21035. // we need to avoid setting textContent of the element at runtime
  21036. // to avoid accidentally overwriting the DOM elements added
  21037. // by the user through custom directives.
  21038. !node.props.find(p => p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  21039. !context.directiveTransforms[p.name]) &&
  21040. // in compat mode, <template> tags with no special directives
  21041. // will be rendered as a fragment so its children must be
  21042. // converted into vnodes.
  21043. !(false ))))) {
  21044. return;
  21045. }
  21046. // pre-convert text nodes into createTextVNode(text) calls to avoid
  21047. // runtime normalization.
  21048. for (let i = 0; i < children.length; i++) {
  21049. const child = children[i];
  21050. if (isText(child) || child.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) {
  21051. const callArgs = [];
  21052. // createTextVNode defaults to single whitespace, so if it is a
  21053. // single space the code could be an empty call to save bytes.
  21054. if (child.type !== 2 /* NodeTypes.TEXT */ || child.content !== ' ') {
  21055. callArgs.push(child);
  21056. }
  21057. // mark dynamic text with flag so it gets patched inside a block
  21058. if (!context.ssr &&
  21059. getConstantType(child, context) === 0 /* ConstantTypes.NOT_CONSTANT */) {
  21060. callArgs.push(1 /* PatchFlags.TEXT */ +
  21061. (` /* ${PatchFlagNames[1 /* PatchFlags.TEXT */]} */` ));
  21062. }
  21063. children[i] = {
  21064. type: 12 /* NodeTypes.TEXT_CALL */,
  21065. content: child,
  21066. loc: child.loc,
  21067. codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
  21068. };
  21069. }
  21070. }
  21071. };
  21072. }
  21073. };
  21074. const seen = new WeakSet();
  21075. const transformOnce = (node, context) => {
  21076. if (node.type === 1 /* NodeTypes.ELEMENT */ && findDir(node, 'once', true)) {
  21077. if (seen.has(node) || context.inVOnce) {
  21078. return;
  21079. }
  21080. seen.add(node);
  21081. context.inVOnce = true;
  21082. context.helper(SET_BLOCK_TRACKING);
  21083. return () => {
  21084. context.inVOnce = false;
  21085. const cur = context.currentNode;
  21086. if (cur.codegenNode) {
  21087. cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
  21088. }
  21089. };
  21090. }
  21091. };
  21092. const transformModel = (dir, node, context) => {
  21093. const { exp, arg } = dir;
  21094. if (!exp) {
  21095. context.onError(createCompilerError(41 /* ErrorCodes.X_V_MODEL_NO_EXPRESSION */, dir.loc));
  21096. return createTransformProps();
  21097. }
  21098. const rawExp = exp.loc.source;
  21099. const expString = exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ? exp.content : rawExp;
  21100. // im SFC <script setup> inline mode, the exp may have been transformed into
  21101. // _unref(exp)
  21102. const bindingType = context.bindingMetadata[rawExp];
  21103. // check props
  21104. if (bindingType === "props" /* BindingTypes.PROPS */ ||
  21105. bindingType === "props-aliased" /* BindingTypes.PROPS_ALIASED */) {
  21106. context.onError(createCompilerError(44 /* ErrorCodes.X_V_MODEL_ON_PROPS */, exp.loc));
  21107. return createTransformProps();
  21108. }
  21109. const maybeRef = context.inline &&
  21110. (bindingType === "setup-let" /* BindingTypes.SETUP_LET */ ||
  21111. bindingType === "setup-ref" /* BindingTypes.SETUP_REF */ ||
  21112. bindingType === "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */);
  21113. if (!expString.trim() ||
  21114. (!isMemberExpression(expString, context) && !maybeRef)) {
  21115. context.onError(createCompilerError(42 /* ErrorCodes.X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
  21116. return createTransformProps();
  21117. }
  21118. if (context.prefixIdentifiers &&
  21119. isSimpleIdentifier(expString) &&
  21120. context.identifiers[expString]) {
  21121. context.onError(createCompilerError(43 /* ErrorCodes.X_V_MODEL_ON_SCOPE_VARIABLE */, exp.loc));
  21122. return createTransformProps();
  21123. }
  21124. const propName = arg ? arg : createSimpleExpression('modelValue', true);
  21125. const eventName = arg
  21126. ? isStaticExp(arg)
  21127. ? `onUpdate:${arg.content}`
  21128. : createCompoundExpression(['"onUpdate:" + ', arg])
  21129. : `onUpdate:modelValue`;
  21130. let assignmentExp;
  21131. const eventArg = context.isTS ? `($event: any)` : `$event`;
  21132. if (maybeRef) {
  21133. if (bindingType === "setup-ref" /* BindingTypes.SETUP_REF */) {
  21134. // v-model used on known ref.
  21135. assignmentExp = createCompoundExpression([
  21136. `${eventArg} => ((`,
  21137. createSimpleExpression(rawExp, false, exp.loc),
  21138. `).value = $event)`
  21139. ]);
  21140. }
  21141. else {
  21142. // v-model used on a potentially ref binding in <script setup> inline mode.
  21143. // the assignment needs to check whether the binding is actually a ref.
  21144. const altAssignment = bindingType === "setup-let" /* BindingTypes.SETUP_LET */ ? `${rawExp} = $event` : `null`;
  21145. assignmentExp = createCompoundExpression([
  21146. `${eventArg} => (${context.helperString(IS_REF)}(${rawExp}) ? (`,
  21147. createSimpleExpression(rawExp, false, exp.loc),
  21148. `).value = $event : ${altAssignment})`
  21149. ]);
  21150. }
  21151. }
  21152. else {
  21153. assignmentExp = createCompoundExpression([
  21154. `${eventArg} => ((`,
  21155. exp,
  21156. `) = $event)`
  21157. ]);
  21158. }
  21159. const props = [
  21160. // modelValue: foo
  21161. createObjectProperty(propName, dir.exp),
  21162. // "onUpdate:modelValue": $event => (foo = $event)
  21163. createObjectProperty(eventName, assignmentExp)
  21164. ];
  21165. // cache v-model handler if applicable (when it doesn't refer any scope vars)
  21166. if (context.prefixIdentifiers &&
  21167. !context.inVOnce &&
  21168. context.cacheHandlers &&
  21169. !hasScopeRef(exp, context.identifiers)) {
  21170. props[1].value = context.cache(props[1].value);
  21171. }
  21172. // modelModifiers: { foo: true, "bar-baz": true }
  21173. if (dir.modifiers.length && node.tagType === 1 /* ElementTypes.COMPONENT */) {
  21174. const modifiers = dir.modifiers
  21175. .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
  21176. .join(`, `);
  21177. const modifiersKey = arg
  21178. ? isStaticExp(arg)
  21179. ? `${arg.content}Modifiers`
  21180. : createCompoundExpression([arg, ' + "Modifiers"'])
  21181. : `modelModifiers`;
  21182. props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* ConstantTypes.CAN_HOIST */)));
  21183. }
  21184. return createTransformProps(props);
  21185. };
  21186. function createTransformProps(props = []) {
  21187. return { props };
  21188. }
  21189. const seen$1 = new WeakSet();
  21190. const transformMemo = (node, context) => {
  21191. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  21192. const dir = findDir(node, 'memo');
  21193. if (!dir || seen$1.has(node)) {
  21194. return;
  21195. }
  21196. seen$1.add(node);
  21197. return () => {
  21198. const codegenNode = node.codegenNode ||
  21199. context.currentNode.codegenNode;
  21200. if (codegenNode && codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  21201. // non-component sub tree should be turned into a block
  21202. if (node.tagType !== 1 /* ElementTypes.COMPONENT */) {
  21203. makeBlock(codegenNode, context);
  21204. }
  21205. node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [
  21206. dir.exp,
  21207. createFunctionExpression(undefined, codegenNode),
  21208. `_cache`,
  21209. String(context.cached++)
  21210. ]);
  21211. }
  21212. };
  21213. }
  21214. };
  21215. function getBaseTransformPreset(prefixIdentifiers) {
  21216. return [
  21217. [
  21218. transformOnce,
  21219. transformIf,
  21220. transformMemo,
  21221. transformFor,
  21222. ...([]),
  21223. ...(prefixIdentifiers
  21224. ? [
  21225. // order is important
  21226. trackVForSlotScopes,
  21227. transformExpression
  21228. ]
  21229. : []),
  21230. transformSlotOutlet,
  21231. transformElement,
  21232. trackSlotScopes,
  21233. transformText
  21234. ],
  21235. {
  21236. on: transformOn,
  21237. bind: transformBind,
  21238. model: transformModel
  21239. }
  21240. ];
  21241. }
  21242. // we name it `baseCompile` so that higher order compilers like
  21243. // @vue/compiler-dom can export `compile` while re-exporting everything else.
  21244. function baseCompile(template, options = {}) {
  21245. const onError = options.onError || defaultOnError;
  21246. const isModuleMode = options.mode === 'module';
  21247. const prefixIdentifiers = (options.prefixIdentifiers === true || isModuleMode);
  21248. if (!prefixIdentifiers && options.cacheHandlers) {
  21249. onError(createCompilerError(49 /* ErrorCodes.X_CACHE_HANDLER_NOT_SUPPORTED */));
  21250. }
  21251. if (options.scopeId && !isModuleMode) {
  21252. onError(createCompilerError(50 /* ErrorCodes.X_SCOPE_ID_NOT_SUPPORTED */));
  21253. }
  21254. const ast = isString(template) ? baseParse(template, options) : template;
  21255. const [nodeTransforms, directiveTransforms] = getBaseTransformPreset(prefixIdentifiers);
  21256. if (options.isTS) {
  21257. const { expressionPlugins } = options;
  21258. if (!expressionPlugins || !expressionPlugins.includes('typescript')) {
  21259. options.expressionPlugins = [...(expressionPlugins || []), 'typescript'];
  21260. }
  21261. }
  21262. transform(ast, extend({}, options, {
  21263. prefixIdentifiers,
  21264. nodeTransforms: [
  21265. ...nodeTransforms,
  21266. ...(options.nodeTransforms || []) // user transforms
  21267. ],
  21268. directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
  21269. )
  21270. }));
  21271. return generate(ast, extend({}, options, {
  21272. prefixIdentifiers
  21273. }));
  21274. }
  21275. const noopDirectiveTransform = () => ({ props: [] });
  21276. const V_MODEL_RADIO = Symbol(`vModelRadio` );
  21277. const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` );
  21278. const V_MODEL_TEXT = Symbol(`vModelText` );
  21279. const V_MODEL_SELECT = Symbol(`vModelSelect` );
  21280. const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` );
  21281. const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` );
  21282. const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` );
  21283. const V_SHOW = Symbol(`vShow` );
  21284. const TRANSITION = Symbol(`Transition` );
  21285. const TRANSITION_GROUP = Symbol(`TransitionGroup` );
  21286. registerRuntimeHelpers({
  21287. [V_MODEL_RADIO]: `vModelRadio`,
  21288. [V_MODEL_CHECKBOX]: `vModelCheckbox`,
  21289. [V_MODEL_TEXT]: `vModelText`,
  21290. [V_MODEL_SELECT]: `vModelSelect`,
  21291. [V_MODEL_DYNAMIC]: `vModelDynamic`,
  21292. [V_ON_WITH_MODIFIERS]: `withModifiers`,
  21293. [V_ON_WITH_KEYS]: `withKeys`,
  21294. [V_SHOW]: `vShow`,
  21295. [TRANSITION]: `Transition`,
  21296. [TRANSITION_GROUP]: `TransitionGroup`
  21297. });
  21298. var namedCharacterReferences = {
  21299. GT: ">",
  21300. gt: ">",
  21301. LT: "<",
  21302. lt: "<",
  21303. "ac;": "∾",
  21304. "af;": "⁡",
  21305. AMP: "&",
  21306. amp: "&",
  21307. "ap;": "≈",
  21308. "DD;": "ⅅ",
  21309. "dd;": "ⅆ",
  21310. deg: "°",
  21311. "ee;": "ⅇ",
  21312. "eg;": "⪚",
  21313. "el;": "⪙",
  21314. ETH: "Ð",
  21315. eth: "ð",
  21316. "gE;": "≧",
  21317. "ge;": "≥",
  21318. "Gg;": "⋙",
  21319. "gg;": "≫",
  21320. "gl;": "≷",
  21321. "GT;": ">",
  21322. "Gt;": "≫",
  21323. "gt;": ">",
  21324. "ic;": "⁣",
  21325. "ii;": "ⅈ",
  21326. "Im;": "ℑ",
  21327. "in;": "∈",
  21328. "it;": "⁢",
  21329. "lE;": "≦",
  21330. "le;": "≤",
  21331. "lg;": "≶",
  21332. "Ll;": "⋘",
  21333. "ll;": "≪",
  21334. "LT;": "<",
  21335. "Lt;": "≪",
  21336. "lt;": "<",
  21337. "mp;": "∓",
  21338. "Mu;": "Μ",
  21339. "mu;": "μ",
  21340. "ne;": "≠",
  21341. "ni;": "∋",
  21342. not: "¬",
  21343. "Nu;": "Ν",
  21344. "nu;": "ν",
  21345. "Or;": "⩔",
  21346. "or;": "∨",
  21347. "oS;": "Ⓢ",
  21348. "Pi;": "Π",
  21349. "pi;": "π",
  21350. "pm;": "±",
  21351. "Pr;": "⪻",
  21352. "pr;": "≺",
  21353. "Re;": "ℜ",
  21354. REG: "®",
  21355. reg: "®",
  21356. "rx;": "℞",
  21357. "Sc;": "⪼",
  21358. "sc;": "≻",
  21359. shy: "­",
  21360. uml: "¨",
  21361. "wp;": "℘",
  21362. "wr;": "≀",
  21363. "Xi;": "Ξ",
  21364. "xi;": "ξ",
  21365. yen: "¥",
  21366. "acd;": "∿",
  21367. "acE;": "∾̳",
  21368. "Acy;": "А",
  21369. "acy;": "а",
  21370. "Afr;": "𝔄",
  21371. "afr;": "𝔞",
  21372. "AMP;": "&",
  21373. "amp;": "&",
  21374. "And;": "⩓",
  21375. "and;": "∧",
  21376. "ang;": "∠",
  21377. "apE;": "⩰",
  21378. "ape;": "≊",
  21379. "ast;": "*",
  21380. Auml: "Ä",
  21381. auml: "ä",
  21382. "Bcy;": "Б",
  21383. "bcy;": "б",
  21384. "Bfr;": "𝔅",
  21385. "bfr;": "𝔟",
  21386. "bne;": "=⃥",
  21387. "bot;": "⊥",
  21388. "Cap;": "⋒",
  21389. "cap;": "∩",
  21390. cent: "¢",
  21391. "Cfr;": "ℭ",
  21392. "cfr;": "𝔠",
  21393. "Chi;": "Χ",
  21394. "chi;": "χ",
  21395. "cir;": "○",
  21396. COPY: "©",
  21397. copy: "©",
  21398. "Cup;": "⋓",
  21399. "cup;": "∪",
  21400. "Dcy;": "Д",
  21401. "dcy;": "д",
  21402. "deg;": "°",
  21403. "Del;": "∇",
  21404. "Dfr;": "𝔇",
  21405. "dfr;": "𝔡",
  21406. "die;": "¨",
  21407. "div;": "÷",
  21408. "Dot;": "¨",
  21409. "dot;": "˙",
  21410. "Ecy;": "Э",
  21411. "ecy;": "э",
  21412. "Efr;": "𝔈",
  21413. "efr;": "𝔢",
  21414. "egs;": "⪖",
  21415. "ell;": "ℓ",
  21416. "els;": "⪕",
  21417. "ENG;": "Ŋ",
  21418. "eng;": "ŋ",
  21419. "Eta;": "Η",
  21420. "eta;": "η",
  21421. "ETH;": "Ð",
  21422. "eth;": "ð",
  21423. Euml: "Ë",
  21424. euml: "ë",
  21425. "Fcy;": "Ф",
  21426. "fcy;": "ф",
  21427. "Ffr;": "𝔉",
  21428. "ffr;": "𝔣",
  21429. "gap;": "⪆",
  21430. "Gcy;": "Г",
  21431. "gcy;": "г",
  21432. "gEl;": "⪌",
  21433. "gel;": "⋛",
  21434. "geq;": "≥",
  21435. "ges;": "⩾",
  21436. "Gfr;": "𝔊",
  21437. "gfr;": "𝔤",
  21438. "ggg;": "⋙",
  21439. "gla;": "⪥",
  21440. "glE;": "⪒",
  21441. "glj;": "⪤",
  21442. "gnE;": "≩",
  21443. "gne;": "⪈",
  21444. "Hat;": "^",
  21445. "Hfr;": "ℌ",
  21446. "hfr;": "𝔥",
  21447. "Icy;": "И",
  21448. "icy;": "и",
  21449. "iff;": "⇔",
  21450. "Ifr;": "ℑ",
  21451. "ifr;": "𝔦",
  21452. "Int;": "∬",
  21453. "int;": "∫",
  21454. Iuml: "Ï",
  21455. iuml: "ï",
  21456. "Jcy;": "Й",
  21457. "jcy;": "й",
  21458. "Jfr;": "𝔍",
  21459. "jfr;": "𝔧",
  21460. "Kcy;": "К",
  21461. "kcy;": "к",
  21462. "Kfr;": "𝔎",
  21463. "kfr;": "𝔨",
  21464. "lap;": "⪅",
  21465. "lat;": "⪫",
  21466. "Lcy;": "Л",
  21467. "lcy;": "л",
  21468. "lEg;": "⪋",
  21469. "leg;": "⋚",
  21470. "leq;": "≤",
  21471. "les;": "⩽",
  21472. "Lfr;": "𝔏",
  21473. "lfr;": "𝔩",
  21474. "lgE;": "⪑",
  21475. "lnE;": "≨",
  21476. "lne;": "⪇",
  21477. "loz;": "◊",
  21478. "lrm;": "‎",
  21479. "Lsh;": "↰",
  21480. "lsh;": "↰",
  21481. macr: "¯",
  21482. "Map;": "⤅",
  21483. "map;": "↦",
  21484. "Mcy;": "М",
  21485. "mcy;": "м",
  21486. "Mfr;": "𝔐",
  21487. "mfr;": "𝔪",
  21488. "mho;": "℧",
  21489. "mid;": "∣",
  21490. "nap;": "≉",
  21491. nbsp: " ",
  21492. "Ncy;": "Н",
  21493. "ncy;": "н",
  21494. "Nfr;": "𝔑",
  21495. "nfr;": "𝔫",
  21496. "ngE;": "≧̸",
  21497. "nge;": "≱",
  21498. "nGg;": "⋙̸",
  21499. "nGt;": "≫⃒",
  21500. "ngt;": "≯",
  21501. "nis;": "⋼",
  21502. "niv;": "∋",
  21503. "nlE;": "≦̸",
  21504. "nle;": "≰",
  21505. "nLl;": "⋘̸",
  21506. "nLt;": "≪⃒",
  21507. "nlt;": "≮",
  21508. "Not;": "⫬",
  21509. "not;": "¬",
  21510. "npr;": "⊀",
  21511. "nsc;": "⊁",
  21512. "num;": "#",
  21513. "Ocy;": "О",
  21514. "ocy;": "о",
  21515. "Ofr;": "𝔒",
  21516. "ofr;": "𝔬",
  21517. "ogt;": "⧁",
  21518. "ohm;": "Ω",
  21519. "olt;": "⧀",
  21520. "ord;": "⩝",
  21521. ordf: "ª",
  21522. ordm: "º",
  21523. "orv;": "⩛",
  21524. Ouml: "Ö",
  21525. ouml: "ö",
  21526. "par;": "∥",
  21527. para: "¶",
  21528. "Pcy;": "П",
  21529. "pcy;": "п",
  21530. "Pfr;": "𝔓",
  21531. "pfr;": "𝔭",
  21532. "Phi;": "Φ",
  21533. "phi;": "φ",
  21534. "piv;": "ϖ",
  21535. "prE;": "⪳",
  21536. "pre;": "⪯",
  21537. "Psi;": "Ψ",
  21538. "psi;": "ψ",
  21539. "Qfr;": "𝔔",
  21540. "qfr;": "𝔮",
  21541. QUOT: "\"",
  21542. quot: "\"",
  21543. "Rcy;": "Р",
  21544. "rcy;": "р",
  21545. "REG;": "®",
  21546. "reg;": "®",
  21547. "Rfr;": "ℜ",
  21548. "rfr;": "𝔯",
  21549. "Rho;": "Ρ",
  21550. "rho;": "ρ",
  21551. "rlm;": "‏",
  21552. "Rsh;": "↱",
  21553. "rsh;": "↱",
  21554. "scE;": "⪴",
  21555. "sce;": "⪰",
  21556. "Scy;": "С",
  21557. "scy;": "с",
  21558. sect: "§",
  21559. "Sfr;": "𝔖",
  21560. "sfr;": "𝔰",
  21561. "shy;": "­",
  21562. "sim;": "∼",
  21563. "smt;": "⪪",
  21564. "sol;": "/",
  21565. "squ;": "□",
  21566. "Sub;": "⋐",
  21567. "sub;": "⊂",
  21568. "Sum;": "∑",
  21569. "sum;": "∑",
  21570. "Sup;": "⋑",
  21571. "sup;": "⊃",
  21572. sup1: "¹",
  21573. sup2: "²",
  21574. sup3: "³",
  21575. "Tab;": "\t",
  21576. "Tau;": "Τ",
  21577. "tau;": "τ",
  21578. "Tcy;": "Т",
  21579. "tcy;": "т",
  21580. "Tfr;": "𝔗",
  21581. "tfr;": "𝔱",
  21582. "top;": "⊤",
  21583. "Ucy;": "У",
  21584. "ucy;": "у",
  21585. "Ufr;": "𝔘",
  21586. "ufr;": "𝔲",
  21587. "uml;": "¨",
  21588. Uuml: "Ü",
  21589. uuml: "ü",
  21590. "Vcy;": "В",
  21591. "vcy;": "в",
  21592. "Vee;": "⋁",
  21593. "vee;": "∨",
  21594. "Vfr;": "𝔙",
  21595. "vfr;": "𝔳",
  21596. "Wfr;": "𝔚",
  21597. "wfr;": "𝔴",
  21598. "Xfr;": "𝔛",
  21599. "xfr;": "𝔵",
  21600. "Ycy;": "Ы",
  21601. "ycy;": "ы",
  21602. "yen;": "¥",
  21603. "Yfr;": "𝔜",
  21604. "yfr;": "𝔶",
  21605. yuml: "ÿ",
  21606. "Zcy;": "З",
  21607. "zcy;": "з",
  21608. "Zfr;": "ℨ",
  21609. "zfr;": "𝔷",
  21610. "zwj;": "‍",
  21611. Acirc: "Â",
  21612. acirc: "â",
  21613. acute: "´",
  21614. AElig: "Æ",
  21615. aelig: "æ",
  21616. "andd;": "⩜",
  21617. "andv;": "⩚",
  21618. "ange;": "⦤",
  21619. "Aopf;": "𝔸",
  21620. "aopf;": "𝕒",
  21621. "apid;": "≋",
  21622. "apos;": "'",
  21623. Aring: "Å",
  21624. aring: "å",
  21625. "Ascr;": "𝒜",
  21626. "ascr;": "𝒶",
  21627. "Auml;": "Ä",
  21628. "auml;": "ä",
  21629. "Barv;": "⫧",
  21630. "bbrk;": "⎵",
  21631. "Beta;": "Β",
  21632. "beta;": "β",
  21633. "beth;": "ℶ",
  21634. "bNot;": "⫭",
  21635. "bnot;": "⌐",
  21636. "Bopf;": "𝔹",
  21637. "bopf;": "𝕓",
  21638. "boxH;": "═",
  21639. "boxh;": "─",
  21640. "boxV;": "║",
  21641. "boxv;": "│",
  21642. "Bscr;": "ℬ",
  21643. "bscr;": "𝒷",
  21644. "bsim;": "∽",
  21645. "bsol;": "\\",
  21646. "bull;": "•",
  21647. "bump;": "≎",
  21648. "caps;": "∩︀",
  21649. "Cdot;": "Ċ",
  21650. "cdot;": "ċ",
  21651. cedil: "¸",
  21652. "cent;": "¢",
  21653. "CHcy;": "Ч",
  21654. "chcy;": "ч",
  21655. "circ;": "ˆ",
  21656. "cirE;": "⧃",
  21657. "cire;": "≗",
  21658. "comp;": "∁",
  21659. "cong;": "≅",
  21660. "Copf;": "ℂ",
  21661. "copf;": "𝕔",
  21662. "COPY;": "©",
  21663. "copy;": "©",
  21664. "Cscr;": "𝒞",
  21665. "cscr;": "𝒸",
  21666. "csub;": "⫏",
  21667. "csup;": "⫐",
  21668. "cups;": "∪︀",
  21669. "Darr;": "↡",
  21670. "dArr;": "⇓",
  21671. "darr;": "↓",
  21672. "dash;": "‐",
  21673. "dHar;": "⥥",
  21674. "diam;": "⋄",
  21675. "DJcy;": "Ђ",
  21676. "djcy;": "ђ",
  21677. "Dopf;": "𝔻",
  21678. "dopf;": "𝕕",
  21679. "Dscr;": "𝒟",
  21680. "dscr;": "𝒹",
  21681. "DScy;": "Ѕ",
  21682. "dscy;": "ѕ",
  21683. "dsol;": "⧶",
  21684. "dtri;": "▿",
  21685. "DZcy;": "Џ",
  21686. "dzcy;": "џ",
  21687. "ecir;": "≖",
  21688. Ecirc: "Ê",
  21689. ecirc: "ê",
  21690. "Edot;": "Ė",
  21691. "eDot;": "≑",
  21692. "edot;": "ė",
  21693. "emsp;": " ",
  21694. "ensp;": " ",
  21695. "Eopf;": "𝔼",
  21696. "eopf;": "𝕖",
  21697. "epar;": "⋕",
  21698. "epsi;": "ε",
  21699. "Escr;": "ℰ",
  21700. "escr;": "ℯ",
  21701. "Esim;": "⩳",
  21702. "esim;": "≂",
  21703. "Euml;": "Ë",
  21704. "euml;": "ë",
  21705. "euro;": "€",
  21706. "excl;": "!",
  21707. "flat;": "♭",
  21708. "fnof;": "ƒ",
  21709. "Fopf;": "𝔽",
  21710. "fopf;": "𝕗",
  21711. "fork;": "⋔",
  21712. "Fscr;": "ℱ",
  21713. "fscr;": "𝒻",
  21714. "Gdot;": "Ġ",
  21715. "gdot;": "ġ",
  21716. "geqq;": "≧",
  21717. "gesl;": "⋛︀",
  21718. "GJcy;": "Ѓ",
  21719. "gjcy;": "ѓ",
  21720. "gnap;": "⪊",
  21721. "gneq;": "⪈",
  21722. "Gopf;": "𝔾",
  21723. "gopf;": "𝕘",
  21724. "Gscr;": "𝒢",
  21725. "gscr;": "ℊ",
  21726. "gsim;": "≳",
  21727. "gtcc;": "⪧",
  21728. "gvnE;": "≩︀",
  21729. "half;": "½",
  21730. "hArr;": "⇔",
  21731. "harr;": "↔",
  21732. "hbar;": "ℏ",
  21733. "Hopf;": "ℍ",
  21734. "hopf;": "𝕙",
  21735. "Hscr;": "ℋ",
  21736. "hscr;": "𝒽",
  21737. Icirc: "Î",
  21738. icirc: "î",
  21739. "Idot;": "İ",
  21740. "IEcy;": "Е",
  21741. "iecy;": "е",
  21742. iexcl: "¡",
  21743. "imof;": "⊷",
  21744. "IOcy;": "Ё",
  21745. "iocy;": "ё",
  21746. "Iopf;": "𝕀",
  21747. "iopf;": "𝕚",
  21748. "Iota;": "Ι",
  21749. "iota;": "ι",
  21750. "Iscr;": "ℐ",
  21751. "iscr;": "𝒾",
  21752. "isin;": "∈",
  21753. "Iuml;": "Ï",
  21754. "iuml;": "ï",
  21755. "Jopf;": "𝕁",
  21756. "jopf;": "𝕛",
  21757. "Jscr;": "𝒥",
  21758. "jscr;": "𝒿",
  21759. "KHcy;": "Х",
  21760. "khcy;": "х",
  21761. "KJcy;": "Ќ",
  21762. "kjcy;": "ќ",
  21763. "Kopf;": "𝕂",
  21764. "kopf;": "𝕜",
  21765. "Kscr;": "𝒦",
  21766. "kscr;": "𝓀",
  21767. "Lang;": "⟪",
  21768. "lang;": "⟨",
  21769. laquo: "«",
  21770. "Larr;": "↞",
  21771. "lArr;": "⇐",
  21772. "larr;": "←",
  21773. "late;": "⪭",
  21774. "lcub;": "{",
  21775. "ldca;": "⤶",
  21776. "ldsh;": "↲",
  21777. "leqq;": "≦",
  21778. "lesg;": "⋚︀",
  21779. "lHar;": "⥢",
  21780. "LJcy;": "Љ",
  21781. "ljcy;": "љ",
  21782. "lnap;": "⪉",
  21783. "lneq;": "⪇",
  21784. "Lopf;": "𝕃",
  21785. "lopf;": "𝕝",
  21786. "lozf;": "⧫",
  21787. "lpar;": "(",
  21788. "Lscr;": "ℒ",
  21789. "lscr;": "𝓁",
  21790. "lsim;": "≲",
  21791. "lsqb;": "[",
  21792. "ltcc;": "⪦",
  21793. "ltri;": "◃",
  21794. "lvnE;": "≨︀",
  21795. "macr;": "¯",
  21796. "male;": "♂",
  21797. "malt;": "✠",
  21798. micro: "µ",
  21799. "mlcp;": "⫛",
  21800. "mldr;": "…",
  21801. "Mopf;": "𝕄",
  21802. "mopf;": "𝕞",
  21803. "Mscr;": "ℳ",
  21804. "mscr;": "𝓂",
  21805. "nang;": "∠⃒",
  21806. "napE;": "⩰̸",
  21807. "nbsp;": " ",
  21808. "ncap;": "⩃",
  21809. "ncup;": "⩂",
  21810. "ngeq;": "≱",
  21811. "nges;": "⩾̸",
  21812. "ngtr;": "≯",
  21813. "nGtv;": "≫̸",
  21814. "nisd;": "⋺",
  21815. "NJcy;": "Њ",
  21816. "njcy;": "њ",
  21817. "nldr;": "‥",
  21818. "nleq;": "≰",
  21819. "nles;": "⩽̸",
  21820. "nLtv;": "≪̸",
  21821. "nmid;": "∤",
  21822. "Nopf;": "ℕ",
  21823. "nopf;": "𝕟",
  21824. "npar;": "∦",
  21825. "npre;": "⪯̸",
  21826. "nsce;": "⪰̸",
  21827. "Nscr;": "𝒩",
  21828. "nscr;": "𝓃",
  21829. "nsim;": "≁",
  21830. "nsub;": "⊄",
  21831. "nsup;": "⊅",
  21832. "ntgl;": "≹",
  21833. "ntlg;": "≸",
  21834. "nvap;": "≍⃒",
  21835. "nvge;": "≥⃒",
  21836. "nvgt;": ">⃒",
  21837. "nvle;": "≤⃒",
  21838. "nvlt;": "<⃒",
  21839. "oast;": "⊛",
  21840. "ocir;": "⊚",
  21841. Ocirc: "Ô",
  21842. ocirc: "ô",
  21843. "odiv;": "⨸",
  21844. "odot;": "⊙",
  21845. "ogon;": "˛",
  21846. "oint;": "∮",
  21847. "omid;": "⦶",
  21848. "Oopf;": "𝕆",
  21849. "oopf;": "𝕠",
  21850. "opar;": "⦷",
  21851. "ordf;": "ª",
  21852. "ordm;": "º",
  21853. "oror;": "⩖",
  21854. "Oscr;": "𝒪",
  21855. "oscr;": "ℴ",
  21856. "osol;": "⊘",
  21857. "Ouml;": "Ö",
  21858. "ouml;": "ö",
  21859. "para;": "¶",
  21860. "part;": "∂",
  21861. "perp;": "⊥",
  21862. "phiv;": "ϕ",
  21863. "plus;": "+",
  21864. "Popf;": "ℙ",
  21865. "popf;": "𝕡",
  21866. pound: "£",
  21867. "prap;": "⪷",
  21868. "prec;": "≺",
  21869. "prnE;": "⪵",
  21870. "prod;": "∏",
  21871. "prop;": "∝",
  21872. "Pscr;": "𝒫",
  21873. "pscr;": "𝓅",
  21874. "qint;": "⨌",
  21875. "Qopf;": "ℚ",
  21876. "qopf;": "𝕢",
  21877. "Qscr;": "𝒬",
  21878. "qscr;": "𝓆",
  21879. "QUOT;": "\"",
  21880. "quot;": "\"",
  21881. "race;": "∽̱",
  21882. "Rang;": "⟫",
  21883. "rang;": "⟩",
  21884. raquo: "»",
  21885. "Rarr;": "↠",
  21886. "rArr;": "⇒",
  21887. "rarr;": "→",
  21888. "rcub;": "}",
  21889. "rdca;": "⤷",
  21890. "rdsh;": "↳",
  21891. "real;": "ℜ",
  21892. "rect;": "▭",
  21893. "rHar;": "⥤",
  21894. "rhov;": "ϱ",
  21895. "ring;": "˚",
  21896. "Ropf;": "ℝ",
  21897. "ropf;": "𝕣",
  21898. "rpar;": ")",
  21899. "Rscr;": "ℛ",
  21900. "rscr;": "𝓇",
  21901. "rsqb;": "]",
  21902. "rtri;": "▹",
  21903. "scap;": "⪸",
  21904. "scnE;": "⪶",
  21905. "sdot;": "⋅",
  21906. "sect;": "§",
  21907. "semi;": ";",
  21908. "sext;": "✶",
  21909. "SHcy;": "Ш",
  21910. "shcy;": "ш",
  21911. "sime;": "≃",
  21912. "simg;": "⪞",
  21913. "siml;": "⪝",
  21914. "smid;": "∣",
  21915. "smte;": "⪬",
  21916. "solb;": "⧄",
  21917. "Sopf;": "𝕊",
  21918. "sopf;": "𝕤",
  21919. "spar;": "∥",
  21920. "Sqrt;": "√",
  21921. "squf;": "▪",
  21922. "Sscr;": "𝒮",
  21923. "sscr;": "𝓈",
  21924. "Star;": "⋆",
  21925. "star;": "☆",
  21926. "subE;": "⫅",
  21927. "sube;": "⊆",
  21928. "succ;": "≻",
  21929. "sung;": "♪",
  21930. "sup1;": "¹",
  21931. "sup2;": "²",
  21932. "sup3;": "³",
  21933. "supE;": "⫆",
  21934. "supe;": "⊇",
  21935. szlig: "ß",
  21936. "tbrk;": "⎴",
  21937. "tdot;": "⃛",
  21938. THORN: "Þ",
  21939. thorn: "þ",
  21940. times: "×",
  21941. "tint;": "∭",
  21942. "toea;": "⤨",
  21943. "Topf;": "𝕋",
  21944. "topf;": "𝕥",
  21945. "tosa;": "⤩",
  21946. "trie;": "≜",
  21947. "Tscr;": "𝒯",
  21948. "tscr;": "𝓉",
  21949. "TScy;": "Ц",
  21950. "tscy;": "ц",
  21951. "Uarr;": "↟",
  21952. "uArr;": "⇑",
  21953. "uarr;": "↑",
  21954. Ucirc: "Û",
  21955. ucirc: "û",
  21956. "uHar;": "⥣",
  21957. "Uopf;": "𝕌",
  21958. "uopf;": "𝕦",
  21959. "Upsi;": "ϒ",
  21960. "upsi;": "υ",
  21961. "Uscr;": "𝒰",
  21962. "uscr;": "𝓊",
  21963. "utri;": "▵",
  21964. "Uuml;": "Ü",
  21965. "uuml;": "ü",
  21966. "vArr;": "⇕",
  21967. "varr;": "↕",
  21968. "Vbar;": "⫫",
  21969. "vBar;": "⫨",
  21970. "Vert;": "‖",
  21971. "vert;": "|",
  21972. "Vopf;": "𝕍",
  21973. "vopf;": "𝕧",
  21974. "Vscr;": "𝒱",
  21975. "vscr;": "𝓋",
  21976. "Wopf;": "𝕎",
  21977. "wopf;": "𝕨",
  21978. "Wscr;": "𝒲",
  21979. "wscr;": "𝓌",
  21980. "xcap;": "⋂",
  21981. "xcup;": "⋃",
  21982. "xmap;": "⟼",
  21983. "xnis;": "⋻",
  21984. "Xopf;": "𝕏",
  21985. "xopf;": "𝕩",
  21986. "Xscr;": "𝒳",
  21987. "xscr;": "𝓍",
  21988. "xvee;": "⋁",
  21989. "YAcy;": "Я",
  21990. "yacy;": "я",
  21991. "YIcy;": "Ї",
  21992. "yicy;": "ї",
  21993. "Yopf;": "𝕐",
  21994. "yopf;": "𝕪",
  21995. "Yscr;": "𝒴",
  21996. "yscr;": "𝓎",
  21997. "YUcy;": "Ю",
  21998. "yucy;": "ю",
  21999. "Yuml;": "Ÿ",
  22000. "yuml;": "ÿ",
  22001. "Zdot;": "Ż",
  22002. "zdot;": "ż",
  22003. "Zeta;": "Ζ",
  22004. "zeta;": "ζ",
  22005. "ZHcy;": "Ж",
  22006. "zhcy;": "ж",
  22007. "Zopf;": "ℤ",
  22008. "zopf;": "𝕫",
  22009. "Zscr;": "𝒵",
  22010. "zscr;": "𝓏",
  22011. "zwnj;": "‌",
  22012. Aacute: "Á",
  22013. aacute: "á",
  22014. "Acirc;": "Â",
  22015. "acirc;": "â",
  22016. "acute;": "´",
  22017. "AElig;": "Æ",
  22018. "aelig;": "æ",
  22019. Agrave: "À",
  22020. agrave: "à",
  22021. "aleph;": "ℵ",
  22022. "Alpha;": "Α",
  22023. "alpha;": "α",
  22024. "Amacr;": "Ā",
  22025. "amacr;": "ā",
  22026. "amalg;": "⨿",
  22027. "angle;": "∠",
  22028. "angrt;": "∟",
  22029. "angst;": "Å",
  22030. "Aogon;": "Ą",
  22031. "aogon;": "ą",
  22032. "Aring;": "Å",
  22033. "aring;": "å",
  22034. "asymp;": "≈",
  22035. Atilde: "Ã",
  22036. atilde: "ã",
  22037. "awint;": "⨑",
  22038. "bcong;": "≌",
  22039. "bdquo;": "„",
  22040. "bepsi;": "϶",
  22041. "blank;": "␣",
  22042. "blk12;": "▒",
  22043. "blk14;": "░",
  22044. "blk34;": "▓",
  22045. "block;": "█",
  22046. "boxDL;": "╗",
  22047. "boxDl;": "╖",
  22048. "boxdL;": "╕",
  22049. "boxdl;": "┐",
  22050. "boxDR;": "╔",
  22051. "boxDr;": "╓",
  22052. "boxdR;": "╒",
  22053. "boxdr;": "┌",
  22054. "boxHD;": "╦",
  22055. "boxHd;": "╤",
  22056. "boxhD;": "╥",
  22057. "boxhd;": "┬",
  22058. "boxHU;": "╩",
  22059. "boxHu;": "╧",
  22060. "boxhU;": "╨",
  22061. "boxhu;": "┴",
  22062. "boxUL;": "╝",
  22063. "boxUl;": "╜",
  22064. "boxuL;": "╛",
  22065. "boxul;": "┘",
  22066. "boxUR;": "╚",
  22067. "boxUr;": "╙",
  22068. "boxuR;": "╘",
  22069. "boxur;": "└",
  22070. "boxVH;": "╬",
  22071. "boxVh;": "╫",
  22072. "boxvH;": "╪",
  22073. "boxvh;": "┼",
  22074. "boxVL;": "╣",
  22075. "boxVl;": "╢",
  22076. "boxvL;": "╡",
  22077. "boxvl;": "┤",
  22078. "boxVR;": "╠",
  22079. "boxVr;": "╟",
  22080. "boxvR;": "╞",
  22081. "boxvr;": "├",
  22082. "Breve;": "˘",
  22083. "breve;": "˘",
  22084. brvbar: "¦",
  22085. "bsemi;": "⁏",
  22086. "bsime;": "⋍",
  22087. "bsolb;": "⧅",
  22088. "bumpE;": "⪮",
  22089. "bumpe;": "≏",
  22090. "caret;": "⁁",
  22091. "caron;": "ˇ",
  22092. "ccaps;": "⩍",
  22093. Ccedil: "Ç",
  22094. ccedil: "ç",
  22095. "Ccirc;": "Ĉ",
  22096. "ccirc;": "ĉ",
  22097. "ccups;": "⩌",
  22098. "cedil;": "¸",
  22099. "check;": "✓",
  22100. "clubs;": "♣",
  22101. "Colon;": "∷",
  22102. "colon;": ":",
  22103. "comma;": ",",
  22104. "crarr;": "↵",
  22105. "Cross;": "⨯",
  22106. "cross;": "✗",
  22107. "csube;": "⫑",
  22108. "csupe;": "⫒",
  22109. "ctdot;": "⋯",
  22110. "cuepr;": "⋞",
  22111. "cuesc;": "⋟",
  22112. "cupor;": "⩅",
  22113. curren: "¤",
  22114. "cuvee;": "⋎",
  22115. "cuwed;": "⋏",
  22116. "cwint;": "∱",
  22117. "Dashv;": "⫤",
  22118. "dashv;": "⊣",
  22119. "dblac;": "˝",
  22120. "ddarr;": "⇊",
  22121. "Delta;": "Δ",
  22122. "delta;": "δ",
  22123. "dharl;": "⇃",
  22124. "dharr;": "⇂",
  22125. "diams;": "♦",
  22126. "disin;": "⋲",
  22127. divide: "÷",
  22128. "doteq;": "≐",
  22129. "dtdot;": "⋱",
  22130. "dtrif;": "▾",
  22131. "duarr;": "⇵",
  22132. "duhar;": "⥯",
  22133. Eacute: "É",
  22134. eacute: "é",
  22135. "Ecirc;": "Ê",
  22136. "ecirc;": "ê",
  22137. "eDDot;": "⩷",
  22138. "efDot;": "≒",
  22139. Egrave: "È",
  22140. egrave: "è",
  22141. "Emacr;": "Ē",
  22142. "emacr;": "ē",
  22143. "empty;": "∅",
  22144. "Eogon;": "Ę",
  22145. "eogon;": "ę",
  22146. "eplus;": "⩱",
  22147. "epsiv;": "ϵ",
  22148. "eqsim;": "≂",
  22149. "Equal;": "⩵",
  22150. "equiv;": "≡",
  22151. "erarr;": "⥱",
  22152. "erDot;": "≓",
  22153. "esdot;": "≐",
  22154. "exist;": "∃",
  22155. "fflig;": "ff",
  22156. "filig;": "fi",
  22157. "fjlig;": "fj",
  22158. "fllig;": "fl",
  22159. "fltns;": "▱",
  22160. "forkv;": "⫙",
  22161. frac12: "½",
  22162. frac14: "¼",
  22163. frac34: "¾",
  22164. "frasl;": "⁄",
  22165. "frown;": "⌢",
  22166. "Gamma;": "Γ",
  22167. "gamma;": "γ",
  22168. "Gcirc;": "Ĝ",
  22169. "gcirc;": "ĝ",
  22170. "gescc;": "⪩",
  22171. "gimel;": "ℷ",
  22172. "gneqq;": "≩",
  22173. "gnsim;": "⋧",
  22174. "grave;": "`",
  22175. "gsime;": "⪎",
  22176. "gsiml;": "⪐",
  22177. "gtcir;": "⩺",
  22178. "gtdot;": "⋗",
  22179. "Hacek;": "ˇ",
  22180. "harrw;": "↭",
  22181. "Hcirc;": "Ĥ",
  22182. "hcirc;": "ĥ",
  22183. "hoarr;": "⇿",
  22184. Iacute: "Í",
  22185. iacute: "í",
  22186. "Icirc;": "Î",
  22187. "icirc;": "î",
  22188. "iexcl;": "¡",
  22189. Igrave: "Ì",
  22190. igrave: "ì",
  22191. "iiint;": "∭",
  22192. "iiota;": "℩",
  22193. "IJlig;": "IJ",
  22194. "ijlig;": "ij",
  22195. "Imacr;": "Ī",
  22196. "imacr;": "ī",
  22197. "image;": "ℑ",
  22198. "imath;": "ı",
  22199. "imped;": "Ƶ",
  22200. "infin;": "∞",
  22201. "Iogon;": "Į",
  22202. "iogon;": "į",
  22203. "iprod;": "⨼",
  22204. iquest: "¿",
  22205. "isinE;": "⋹",
  22206. "isins;": "⋴",
  22207. "isinv;": "∈",
  22208. "Iukcy;": "І",
  22209. "iukcy;": "і",
  22210. "Jcirc;": "Ĵ",
  22211. "jcirc;": "ĵ",
  22212. "jmath;": "ȷ",
  22213. "Jukcy;": "Є",
  22214. "jukcy;": "є",
  22215. "Kappa;": "Κ",
  22216. "kappa;": "κ",
  22217. "lAarr;": "⇚",
  22218. "langd;": "⦑",
  22219. "laquo;": "«",
  22220. "larrb;": "⇤",
  22221. "lates;": "⪭︀",
  22222. "lBarr;": "⤎",
  22223. "lbarr;": "⤌",
  22224. "lbbrk;": "❲",
  22225. "lbrke;": "⦋",
  22226. "lceil;": "⌈",
  22227. "ldquo;": "“",
  22228. "lescc;": "⪨",
  22229. "lhard;": "↽",
  22230. "lharu;": "↼",
  22231. "lhblk;": "▄",
  22232. "llarr;": "⇇",
  22233. "lltri;": "◺",
  22234. "lneqq;": "≨",
  22235. "lnsim;": "⋦",
  22236. "loang;": "⟬",
  22237. "loarr;": "⇽",
  22238. "lobrk;": "⟦",
  22239. "lopar;": "⦅",
  22240. "lrarr;": "⇆",
  22241. "lrhar;": "⇋",
  22242. "lrtri;": "⊿",
  22243. "lsime;": "⪍",
  22244. "lsimg;": "⪏",
  22245. "lsquo;": "‘",
  22246. "ltcir;": "⩹",
  22247. "ltdot;": "⋖",
  22248. "ltrie;": "⊴",
  22249. "ltrif;": "◂",
  22250. "mdash;": "—",
  22251. "mDDot;": "∺",
  22252. "micro;": "µ",
  22253. middot: "·",
  22254. "minus;": "−",
  22255. "mumap;": "⊸",
  22256. "nabla;": "∇",
  22257. "napid;": "≋̸",
  22258. "napos;": "ʼn",
  22259. "natur;": "♮",
  22260. "nbump;": "≎̸",
  22261. "ncong;": "≇",
  22262. "ndash;": "–",
  22263. "neArr;": "⇗",
  22264. "nearr;": "↗",
  22265. "nedot;": "≐̸",
  22266. "nesim;": "≂̸",
  22267. "ngeqq;": "≧̸",
  22268. "ngsim;": "≵",
  22269. "nhArr;": "⇎",
  22270. "nharr;": "↮",
  22271. "nhpar;": "⫲",
  22272. "nlArr;": "⇍",
  22273. "nlarr;": "↚",
  22274. "nleqq;": "≦̸",
  22275. "nless;": "≮",
  22276. "nlsim;": "≴",
  22277. "nltri;": "⋪",
  22278. "notin;": "∉",
  22279. "notni;": "∌",
  22280. "npart;": "∂̸",
  22281. "nprec;": "⊀",
  22282. "nrArr;": "⇏",
  22283. "nrarr;": "↛",
  22284. "nrtri;": "⋫",
  22285. "nsime;": "≄",
  22286. "nsmid;": "∤",
  22287. "nspar;": "∦",
  22288. "nsubE;": "⫅̸",
  22289. "nsube;": "⊈",
  22290. "nsucc;": "⊁",
  22291. "nsupE;": "⫆̸",
  22292. "nsupe;": "⊉",
  22293. Ntilde: "Ñ",
  22294. ntilde: "ñ",
  22295. "numsp;": " ",
  22296. "nvsim;": "∼⃒",
  22297. "nwArr;": "⇖",
  22298. "nwarr;": "↖",
  22299. Oacute: "Ó",
  22300. oacute: "ó",
  22301. "Ocirc;": "Ô",
  22302. "ocirc;": "ô",
  22303. "odash;": "⊝",
  22304. "OElig;": "Œ",
  22305. "oelig;": "œ",
  22306. "ofcir;": "⦿",
  22307. Ograve: "Ò",
  22308. ograve: "ò",
  22309. "ohbar;": "⦵",
  22310. "olarr;": "↺",
  22311. "olcir;": "⦾",
  22312. "oline;": "‾",
  22313. "Omacr;": "Ō",
  22314. "omacr;": "ō",
  22315. "Omega;": "Ω",
  22316. "omega;": "ω",
  22317. "operp;": "⦹",
  22318. "oplus;": "⊕",
  22319. "orarr;": "↻",
  22320. "order;": "ℴ",
  22321. Oslash: "Ø",
  22322. oslash: "ø",
  22323. Otilde: "Õ",
  22324. otilde: "õ",
  22325. "ovbar;": "⌽",
  22326. "parsl;": "⫽",
  22327. "phone;": "☎",
  22328. "plusb;": "⊞",
  22329. "pluse;": "⩲",
  22330. plusmn: "±",
  22331. "pound;": "£",
  22332. "prcue;": "≼",
  22333. "Prime;": "″",
  22334. "prime;": "′",
  22335. "prnap;": "⪹",
  22336. "prsim;": "≾",
  22337. "quest;": "?",
  22338. "rAarr;": "⇛",
  22339. "radic;": "√",
  22340. "rangd;": "⦒",
  22341. "range;": "⦥",
  22342. "raquo;": "»",
  22343. "rarrb;": "⇥",
  22344. "rarrc;": "⤳",
  22345. "rarrw;": "↝",
  22346. "ratio;": "∶",
  22347. "RBarr;": "⤐",
  22348. "rBarr;": "⤏",
  22349. "rbarr;": "⤍",
  22350. "rbbrk;": "❳",
  22351. "rbrke;": "⦌",
  22352. "rceil;": "⌉",
  22353. "rdquo;": "”",
  22354. "reals;": "ℝ",
  22355. "rhard;": "⇁",
  22356. "rharu;": "⇀",
  22357. "rlarr;": "⇄",
  22358. "rlhar;": "⇌",
  22359. "rnmid;": "⫮",
  22360. "roang;": "⟭",
  22361. "roarr;": "⇾",
  22362. "robrk;": "⟧",
  22363. "ropar;": "⦆",
  22364. "rrarr;": "⇉",
  22365. "rsquo;": "’",
  22366. "rtrie;": "⊵",
  22367. "rtrif;": "▸",
  22368. "sbquo;": "‚",
  22369. "sccue;": "≽",
  22370. "Scirc;": "Ŝ",
  22371. "scirc;": "ŝ",
  22372. "scnap;": "⪺",
  22373. "scsim;": "≿",
  22374. "sdotb;": "⊡",
  22375. "sdote;": "⩦",
  22376. "seArr;": "⇘",
  22377. "searr;": "↘",
  22378. "setmn;": "∖",
  22379. "sharp;": "♯",
  22380. "Sigma;": "Σ",
  22381. "sigma;": "σ",
  22382. "simeq;": "≃",
  22383. "simgE;": "⪠",
  22384. "simlE;": "⪟",
  22385. "simne;": "≆",
  22386. "slarr;": "←",
  22387. "smile;": "⌣",
  22388. "smtes;": "⪬︀",
  22389. "sqcap;": "⊓",
  22390. "sqcup;": "⊔",
  22391. "sqsub;": "⊏",
  22392. "sqsup;": "⊐",
  22393. "srarr;": "→",
  22394. "starf;": "★",
  22395. "strns;": "¯",
  22396. "subnE;": "⫋",
  22397. "subne;": "⊊",
  22398. "supnE;": "⫌",
  22399. "supne;": "⊋",
  22400. "swArr;": "⇙",
  22401. "swarr;": "↙",
  22402. "szlig;": "ß",
  22403. "Theta;": "Θ",
  22404. "theta;": "θ",
  22405. "thkap;": "≈",
  22406. "THORN;": "Þ",
  22407. "thorn;": "þ",
  22408. "Tilde;": "∼",
  22409. "tilde;": "˜",
  22410. "times;": "×",
  22411. "TRADE;": "™",
  22412. "trade;": "™",
  22413. "trisb;": "⧍",
  22414. "TSHcy;": "Ћ",
  22415. "tshcy;": "ћ",
  22416. "twixt;": "≬",
  22417. Uacute: "Ú",
  22418. uacute: "ú",
  22419. "Ubrcy;": "Ў",
  22420. "ubrcy;": "ў",
  22421. "Ucirc;": "Û",
  22422. "ucirc;": "û",
  22423. "udarr;": "⇅",
  22424. "udhar;": "⥮",
  22425. Ugrave: "Ù",
  22426. ugrave: "ù",
  22427. "uharl;": "↿",
  22428. "uharr;": "↾",
  22429. "uhblk;": "▀",
  22430. "ultri;": "◸",
  22431. "Umacr;": "Ū",
  22432. "umacr;": "ū",
  22433. "Union;": "⋃",
  22434. "Uogon;": "Ų",
  22435. "uogon;": "ų",
  22436. "uplus;": "⊎",
  22437. "upsih;": "ϒ",
  22438. "UpTee;": "⊥",
  22439. "Uring;": "Ů",
  22440. "uring;": "ů",
  22441. "urtri;": "◹",
  22442. "utdot;": "⋰",
  22443. "utrif;": "▴",
  22444. "uuarr;": "⇈",
  22445. "varpi;": "ϖ",
  22446. "vBarv;": "⫩",
  22447. "VDash;": "⊫",
  22448. "Vdash;": "⊩",
  22449. "vDash;": "⊨",
  22450. "vdash;": "⊢",
  22451. "veeeq;": "≚",
  22452. "vltri;": "⊲",
  22453. "vnsub;": "⊂⃒",
  22454. "vnsup;": "⊃⃒",
  22455. "vprop;": "∝",
  22456. "vrtri;": "⊳",
  22457. "Wcirc;": "Ŵ",
  22458. "wcirc;": "ŵ",
  22459. "Wedge;": "⋀",
  22460. "wedge;": "∧",
  22461. "xcirc;": "◯",
  22462. "xdtri;": "▽",
  22463. "xhArr;": "⟺",
  22464. "xharr;": "⟷",
  22465. "xlArr;": "⟸",
  22466. "xlarr;": "⟵",
  22467. "xodot;": "⨀",
  22468. "xrArr;": "⟹",
  22469. "xrarr;": "⟶",
  22470. "xutri;": "△",
  22471. Yacute: "Ý",
  22472. yacute: "ý",
  22473. "Ycirc;": "Ŷ",
  22474. "ycirc;": "ŷ",
  22475. "Aacute;": "Á",
  22476. "aacute;": "á",
  22477. "Abreve;": "Ă",
  22478. "abreve;": "ă",
  22479. "Agrave;": "À",
  22480. "agrave;": "à",
  22481. "andand;": "⩕",
  22482. "angmsd;": "∡",
  22483. "angsph;": "∢",
  22484. "apacir;": "⩯",
  22485. "approx;": "≈",
  22486. "Assign;": "≔",
  22487. "Atilde;": "Ã",
  22488. "atilde;": "ã",
  22489. "barvee;": "⊽",
  22490. "Barwed;": "⌆",
  22491. "barwed;": "⌅",
  22492. "becaus;": "∵",
  22493. "bernou;": "ℬ",
  22494. "bigcap;": "⋂",
  22495. "bigcup;": "⋃",
  22496. "bigvee;": "⋁",
  22497. "bkarow;": "⤍",
  22498. "bottom;": "⊥",
  22499. "bowtie;": "⋈",
  22500. "boxbox;": "⧉",
  22501. "bprime;": "‵",
  22502. "brvbar;": "¦",
  22503. "bullet;": "•",
  22504. "Bumpeq;": "≎",
  22505. "bumpeq;": "≏",
  22506. "Cacute;": "Ć",
  22507. "cacute;": "ć",
  22508. "capand;": "⩄",
  22509. "capcap;": "⩋",
  22510. "capcup;": "⩇",
  22511. "capdot;": "⩀",
  22512. "Ccaron;": "Č",
  22513. "ccaron;": "č",
  22514. "Ccedil;": "Ç",
  22515. "ccedil;": "ç",
  22516. "circeq;": "≗",
  22517. "cirmid;": "⫯",
  22518. "Colone;": "⩴",
  22519. "colone;": "≔",
  22520. "commat;": "@",
  22521. "compfn;": "∘",
  22522. "Conint;": "∯",
  22523. "conint;": "∮",
  22524. "coprod;": "∐",
  22525. "copysr;": "℗",
  22526. "cularr;": "↶",
  22527. "CupCap;": "≍",
  22528. "cupcap;": "⩆",
  22529. "cupcup;": "⩊",
  22530. "cupdot;": "⊍",
  22531. "curarr;": "↷",
  22532. "curren;": "¤",
  22533. "cylcty;": "⌭",
  22534. "Dagger;": "‡",
  22535. "dagger;": "†",
  22536. "daleth;": "ℸ",
  22537. "Dcaron;": "Ď",
  22538. "dcaron;": "ď",
  22539. "dfisht;": "⥿",
  22540. "divide;": "÷",
  22541. "divonx;": "⋇",
  22542. "dlcorn;": "⌞",
  22543. "dlcrop;": "⌍",
  22544. "dollar;": "$",
  22545. "DotDot;": "⃜",
  22546. "drcorn;": "⌟",
  22547. "drcrop;": "⌌",
  22548. "Dstrok;": "Đ",
  22549. "dstrok;": "đ",
  22550. "Eacute;": "É",
  22551. "eacute;": "é",
  22552. "easter;": "⩮",
  22553. "Ecaron;": "Ě",
  22554. "ecaron;": "ě",
  22555. "ecolon;": "≕",
  22556. "Egrave;": "È",
  22557. "egrave;": "è",
  22558. "egsdot;": "⪘",
  22559. "elsdot;": "⪗",
  22560. "emptyv;": "∅",
  22561. "emsp13;": " ",
  22562. "emsp14;": " ",
  22563. "eparsl;": "⧣",
  22564. "eqcirc;": "≖",
  22565. "equals;": "=",
  22566. "equest;": "≟",
  22567. "Exists;": "∃",
  22568. "female;": "♀",
  22569. "ffilig;": "ffi",
  22570. "ffllig;": "ffl",
  22571. "ForAll;": "∀",
  22572. "forall;": "∀",
  22573. "frac12;": "½",
  22574. "frac13;": "⅓",
  22575. "frac14;": "¼",
  22576. "frac15;": "⅕",
  22577. "frac16;": "⅙",
  22578. "frac18;": "⅛",
  22579. "frac23;": "⅔",
  22580. "frac25;": "⅖",
  22581. "frac34;": "¾",
  22582. "frac35;": "⅗",
  22583. "frac38;": "⅜",
  22584. "frac45;": "⅘",
  22585. "frac56;": "⅚",
  22586. "frac58;": "⅝",
  22587. "frac78;": "⅞",
  22588. "gacute;": "ǵ",
  22589. "Gammad;": "Ϝ",
  22590. "gammad;": "ϝ",
  22591. "Gbreve;": "Ğ",
  22592. "gbreve;": "ğ",
  22593. "Gcedil;": "Ģ",
  22594. "gesdot;": "⪀",
  22595. "gesles;": "⪔",
  22596. "gtlPar;": "⦕",
  22597. "gtrarr;": "⥸",
  22598. "gtrdot;": "⋗",
  22599. "gtrsim;": "≳",
  22600. "hairsp;": " ",
  22601. "hamilt;": "ℋ",
  22602. "HARDcy;": "Ъ",
  22603. "hardcy;": "ъ",
  22604. "hearts;": "♥",
  22605. "hellip;": "…",
  22606. "hercon;": "⊹",
  22607. "homtht;": "∻",
  22608. "horbar;": "―",
  22609. "hslash;": "ℏ",
  22610. "Hstrok;": "Ħ",
  22611. "hstrok;": "ħ",
  22612. "hybull;": "⁃",
  22613. "hyphen;": "‐",
  22614. "Iacute;": "Í",
  22615. "iacute;": "í",
  22616. "Igrave;": "Ì",
  22617. "igrave;": "ì",
  22618. "iiiint;": "⨌",
  22619. "iinfin;": "⧜",
  22620. "incare;": "℅",
  22621. "inodot;": "ı",
  22622. "intcal;": "⊺",
  22623. "iquest;": "¿",
  22624. "isinsv;": "⋳",
  22625. "Itilde;": "Ĩ",
  22626. "itilde;": "ĩ",
  22627. "Jsercy;": "Ј",
  22628. "jsercy;": "ј",
  22629. "kappav;": "ϰ",
  22630. "Kcedil;": "Ķ",
  22631. "kcedil;": "ķ",
  22632. "kgreen;": "ĸ",
  22633. "Lacute;": "Ĺ",
  22634. "lacute;": "ĺ",
  22635. "lagran;": "ℒ",
  22636. "Lambda;": "Λ",
  22637. "lambda;": "λ",
  22638. "langle;": "⟨",
  22639. "larrfs;": "⤝",
  22640. "larrhk;": "↩",
  22641. "larrlp;": "↫",
  22642. "larrpl;": "⤹",
  22643. "larrtl;": "↢",
  22644. "lAtail;": "⤛",
  22645. "latail;": "⤙",
  22646. "lbrace;": "{",
  22647. "lbrack;": "[",
  22648. "Lcaron;": "Ľ",
  22649. "lcaron;": "ľ",
  22650. "Lcedil;": "Ļ",
  22651. "lcedil;": "ļ",
  22652. "ldquor;": "„",
  22653. "lesdot;": "⩿",
  22654. "lesges;": "⪓",
  22655. "lfisht;": "⥼",
  22656. "lfloor;": "⌊",
  22657. "lharul;": "⥪",
  22658. "llhard;": "⥫",
  22659. "Lmidot;": "Ŀ",
  22660. "lmidot;": "ŀ",
  22661. "lmoust;": "⎰",
  22662. "loplus;": "⨭",
  22663. "lowast;": "∗",
  22664. "lowbar;": "_",
  22665. "lparlt;": "⦓",
  22666. "lrhard;": "⥭",
  22667. "lsaquo;": "‹",
  22668. "lsquor;": "‚",
  22669. "Lstrok;": "Ł",
  22670. "lstrok;": "ł",
  22671. "lthree;": "⋋",
  22672. "ltimes;": "⋉",
  22673. "ltlarr;": "⥶",
  22674. "ltrPar;": "⦖",
  22675. "mapsto;": "↦",
  22676. "marker;": "▮",
  22677. "mcomma;": "⨩",
  22678. "midast;": "*",
  22679. "midcir;": "⫰",
  22680. "middot;": "·",
  22681. "minusb;": "⊟",
  22682. "minusd;": "∸",
  22683. "mnplus;": "∓",
  22684. "models;": "⊧",
  22685. "mstpos;": "∾",
  22686. "Nacute;": "Ń",
  22687. "nacute;": "ń",
  22688. "nbumpe;": "≏̸",
  22689. "Ncaron;": "Ň",
  22690. "ncaron;": "ň",
  22691. "Ncedil;": "Ņ",
  22692. "ncedil;": "ņ",
  22693. "nearhk;": "⤤",
  22694. "nequiv;": "≢",
  22695. "nesear;": "⤨",
  22696. "nexist;": "∄",
  22697. "nltrie;": "⋬",
  22698. "notinE;": "⋹̸",
  22699. "nparsl;": "⫽⃥",
  22700. "nprcue;": "⋠",
  22701. "nrarrc;": "⤳̸",
  22702. "nrarrw;": "↝̸",
  22703. "nrtrie;": "⋭",
  22704. "nsccue;": "⋡",
  22705. "nsimeq;": "≄",
  22706. "Ntilde;": "Ñ",
  22707. "ntilde;": "ñ",
  22708. "numero;": "№",
  22709. "nVDash;": "⊯",
  22710. "nVdash;": "⊮",
  22711. "nvDash;": "⊭",
  22712. "nvdash;": "⊬",
  22713. "nvHarr;": "⤄",
  22714. "nvlArr;": "⤂",
  22715. "nvrArr;": "⤃",
  22716. "nwarhk;": "⤣",
  22717. "nwnear;": "⤧",
  22718. "Oacute;": "Ó",
  22719. "oacute;": "ó",
  22720. "Odblac;": "Ő",
  22721. "odblac;": "ő",
  22722. "odsold;": "⦼",
  22723. "Ograve;": "Ò",
  22724. "ograve;": "ò",
  22725. "ominus;": "⊖",
  22726. "origof;": "⊶",
  22727. "Oslash;": "Ø",
  22728. "oslash;": "ø",
  22729. "Otilde;": "Õ",
  22730. "otilde;": "õ",
  22731. "Otimes;": "⨷",
  22732. "otimes;": "⊗",
  22733. "parsim;": "⫳",
  22734. "percnt;": "%",
  22735. "period;": ".",
  22736. "permil;": "‰",
  22737. "phmmat;": "ℳ",
  22738. "planck;": "ℏ",
  22739. "plankv;": "ℏ",
  22740. "plusdo;": "∔",
  22741. "plusdu;": "⨥",
  22742. "plusmn;": "±",
  22743. "preceq;": "⪯",
  22744. "primes;": "ℙ",
  22745. "prnsim;": "⋨",
  22746. "propto;": "∝",
  22747. "prurel;": "⊰",
  22748. "puncsp;": " ",
  22749. "qprime;": "⁗",
  22750. "Racute;": "Ŕ",
  22751. "racute;": "ŕ",
  22752. "rangle;": "⟩",
  22753. "rarrap;": "⥵",
  22754. "rarrfs;": "⤞",
  22755. "rarrhk;": "↪",
  22756. "rarrlp;": "↬",
  22757. "rarrpl;": "⥅",
  22758. "Rarrtl;": "⤖",
  22759. "rarrtl;": "↣",
  22760. "rAtail;": "⤜",
  22761. "ratail;": "⤚",
  22762. "rbrace;": "}",
  22763. "rbrack;": "]",
  22764. "Rcaron;": "Ř",
  22765. "rcaron;": "ř",
  22766. "Rcedil;": "Ŗ",
  22767. "rcedil;": "ŗ",
  22768. "rdquor;": "”",
  22769. "rfisht;": "⥽",
  22770. "rfloor;": "⌋",
  22771. "rharul;": "⥬",
  22772. "rmoust;": "⎱",
  22773. "roplus;": "⨮",
  22774. "rpargt;": "⦔",
  22775. "rsaquo;": "›",
  22776. "rsquor;": "’",
  22777. "rthree;": "⋌",
  22778. "rtimes;": "⋊",
  22779. "Sacute;": "Ś",
  22780. "sacute;": "ś",
  22781. "Scaron;": "Š",
  22782. "scaron;": "š",
  22783. "Scedil;": "Ş",
  22784. "scedil;": "ş",
  22785. "scnsim;": "⋩",
  22786. "searhk;": "⤥",
  22787. "seswar;": "⤩",
  22788. "sfrown;": "⌢",
  22789. "SHCHcy;": "Щ",
  22790. "shchcy;": "щ",
  22791. "sigmaf;": "ς",
  22792. "sigmav;": "ς",
  22793. "simdot;": "⩪",
  22794. "smashp;": "⨳",
  22795. "SOFTcy;": "Ь",
  22796. "softcy;": "ь",
  22797. "solbar;": "⌿",
  22798. "spades;": "♠",
  22799. "sqcaps;": "⊓︀",
  22800. "sqcups;": "⊔︀",
  22801. "sqsube;": "⊑",
  22802. "sqsupe;": "⊒",
  22803. "Square;": "□",
  22804. "square;": "□",
  22805. "squarf;": "▪",
  22806. "ssetmn;": "∖",
  22807. "ssmile;": "⌣",
  22808. "sstarf;": "⋆",
  22809. "subdot;": "⪽",
  22810. "Subset;": "⋐",
  22811. "subset;": "⊂",
  22812. "subsim;": "⫇",
  22813. "subsub;": "⫕",
  22814. "subsup;": "⫓",
  22815. "succeq;": "⪰",
  22816. "supdot;": "⪾",
  22817. "Supset;": "⋑",
  22818. "supset;": "⊃",
  22819. "supsim;": "⫈",
  22820. "supsub;": "⫔",
  22821. "supsup;": "⫖",
  22822. "swarhk;": "⤦",
  22823. "swnwar;": "⤪",
  22824. "target;": "⌖",
  22825. "Tcaron;": "Ť",
  22826. "tcaron;": "ť",
  22827. "Tcedil;": "Ţ",
  22828. "tcedil;": "ţ",
  22829. "telrec;": "⌕",
  22830. "there4;": "∴",
  22831. "thetav;": "ϑ",
  22832. "thinsp;": " ",
  22833. "thksim;": "∼",
  22834. "timesb;": "⊠",
  22835. "timesd;": "⨰",
  22836. "topbot;": "⌶",
  22837. "topcir;": "⫱",
  22838. "tprime;": "‴",
  22839. "tridot;": "◬",
  22840. "Tstrok;": "Ŧ",
  22841. "tstrok;": "ŧ",
  22842. "Uacute;": "Ú",
  22843. "uacute;": "ú",
  22844. "Ubreve;": "Ŭ",
  22845. "ubreve;": "ŭ",
  22846. "Udblac;": "Ű",
  22847. "udblac;": "ű",
  22848. "ufisht;": "⥾",
  22849. "Ugrave;": "Ù",
  22850. "ugrave;": "ù",
  22851. "ulcorn;": "⌜",
  22852. "ulcrop;": "⌏",
  22853. "urcorn;": "⌝",
  22854. "urcrop;": "⌎",
  22855. "Utilde;": "Ũ",
  22856. "utilde;": "ũ",
  22857. "vangrt;": "⦜",
  22858. "varphi;": "ϕ",
  22859. "varrho;": "ϱ",
  22860. "Vdashl;": "⫦",
  22861. "veebar;": "⊻",
  22862. "vellip;": "⋮",
  22863. "Verbar;": "‖",
  22864. "verbar;": "|",
  22865. "vsubnE;": "⫋︀",
  22866. "vsubne;": "⊊︀",
  22867. "vsupnE;": "⫌︀",
  22868. "vsupne;": "⊋︀",
  22869. "Vvdash;": "⊪",
  22870. "wedbar;": "⩟",
  22871. "wedgeq;": "≙",
  22872. "weierp;": "℘",
  22873. "wreath;": "≀",
  22874. "xoplus;": "⨁",
  22875. "xotime;": "⨂",
  22876. "xsqcup;": "⨆",
  22877. "xuplus;": "⨄",
  22878. "xwedge;": "⋀",
  22879. "Yacute;": "Ý",
  22880. "yacute;": "ý",
  22881. "Zacute;": "Ź",
  22882. "zacute;": "ź",
  22883. "Zcaron;": "Ž",
  22884. "zcaron;": "ž",
  22885. "zeetrf;": "ℨ",
  22886. "alefsym;": "ℵ",
  22887. "angrtvb;": "⊾",
  22888. "angzarr;": "⍼",
  22889. "asympeq;": "≍",
  22890. "backsim;": "∽",
  22891. "Because;": "∵",
  22892. "because;": "∵",
  22893. "bemptyv;": "⦰",
  22894. "between;": "≬",
  22895. "bigcirc;": "◯",
  22896. "bigodot;": "⨀",
  22897. "bigstar;": "★",
  22898. "bnequiv;": "≡⃥",
  22899. "boxplus;": "⊞",
  22900. "Cayleys;": "ℭ",
  22901. "Cconint;": "∰",
  22902. "ccupssm;": "⩐",
  22903. "Cedilla;": "¸",
  22904. "cemptyv;": "⦲",
  22905. "cirscir;": "⧂",
  22906. "coloneq;": "≔",
  22907. "congdot;": "⩭",
  22908. "cudarrl;": "⤸",
  22909. "cudarrr;": "⤵",
  22910. "cularrp;": "⤽",
  22911. "curarrm;": "⤼",
  22912. "dbkarow;": "⤏",
  22913. "ddagger;": "‡",
  22914. "ddotseq;": "⩷",
  22915. "demptyv;": "⦱",
  22916. "Diamond;": "⋄",
  22917. "diamond;": "⋄",
  22918. "digamma;": "ϝ",
  22919. "dotplus;": "∔",
  22920. "DownTee;": "⊤",
  22921. "dwangle;": "⦦",
  22922. "Element;": "∈",
  22923. "Epsilon;": "Ε",
  22924. "epsilon;": "ε",
  22925. "eqcolon;": "≕",
  22926. "equivDD;": "⩸",
  22927. "gesdoto;": "⪂",
  22928. "gtquest;": "⩼",
  22929. "gtrless;": "≷",
  22930. "harrcir;": "⥈",
  22931. "Implies;": "⇒",
  22932. "intprod;": "⨼",
  22933. "isindot;": "⋵",
  22934. "larrbfs;": "⤟",
  22935. "larrsim;": "⥳",
  22936. "lbrksld;": "⦏",
  22937. "lbrkslu;": "⦍",
  22938. "ldrdhar;": "⥧",
  22939. "LeftTee;": "⊣",
  22940. "lesdoto;": "⪁",
  22941. "lessdot;": "⋖",
  22942. "lessgtr;": "≶",
  22943. "lesssim;": "≲",
  22944. "lotimes;": "⨴",
  22945. "lozenge;": "◊",
  22946. "ltquest;": "⩻",
  22947. "luruhar;": "⥦",
  22948. "maltese;": "✠",
  22949. "minusdu;": "⨪",
  22950. "napprox;": "≉",
  22951. "natural;": "♮",
  22952. "nearrow;": "↗",
  22953. "NewLine;": "\n",
  22954. "nexists;": "∄",
  22955. "NoBreak;": "⁠",
  22956. "notinva;": "∉",
  22957. "notinvb;": "⋷",
  22958. "notinvc;": "⋶",
  22959. "NotLess;": "≮",
  22960. "notniva;": "∌",
  22961. "notnivb;": "⋾",
  22962. "notnivc;": "⋽",
  22963. "npolint;": "⨔",
  22964. "npreceq;": "⪯̸",
  22965. "nsqsube;": "⋢",
  22966. "nsqsupe;": "⋣",
  22967. "nsubset;": "⊂⃒",
  22968. "nsucceq;": "⪰̸",
  22969. "nsupset;": "⊃⃒",
  22970. "nvinfin;": "⧞",
  22971. "nvltrie;": "⊴⃒",
  22972. "nvrtrie;": "⊵⃒",
  22973. "nwarrow;": "↖",
  22974. "olcross;": "⦻",
  22975. "Omicron;": "Ο",
  22976. "omicron;": "ο",
  22977. "orderof;": "ℴ",
  22978. "orslope;": "⩗",
  22979. "OverBar;": "‾",
  22980. "pertenk;": "‱",
  22981. "planckh;": "ℎ",
  22982. "pluscir;": "⨢",
  22983. "plussim;": "⨦",
  22984. "plustwo;": "⨧",
  22985. "precsim;": "≾",
  22986. "Product;": "∏",
  22987. "quatint;": "⨖",
  22988. "questeq;": "≟",
  22989. "rarrbfs;": "⤠",
  22990. "rarrsim;": "⥴",
  22991. "rbrksld;": "⦎",
  22992. "rbrkslu;": "⦐",
  22993. "rdldhar;": "⥩",
  22994. "realine;": "ℛ",
  22995. "rotimes;": "⨵",
  22996. "ruluhar;": "⥨",
  22997. "searrow;": "↘",
  22998. "simplus;": "⨤",
  22999. "simrarr;": "⥲",
  23000. "subedot;": "⫃",
  23001. "submult;": "⫁",
  23002. "subplus;": "⪿",
  23003. "subrarr;": "⥹",
  23004. "succsim;": "≿",
  23005. "supdsub;": "⫘",
  23006. "supedot;": "⫄",
  23007. "suphsol;": "⟉",
  23008. "suphsub;": "⫗",
  23009. "suplarr;": "⥻",
  23010. "supmult;": "⫂",
  23011. "supplus;": "⫀",
  23012. "swarrow;": "↙",
  23013. "topfork;": "⫚",
  23014. "triplus;": "⨹",
  23015. "tritime;": "⨻",
  23016. "UpArrow;": "↑",
  23017. "Uparrow;": "⇑",
  23018. "uparrow;": "↑",
  23019. "Upsilon;": "Υ",
  23020. "upsilon;": "υ",
  23021. "uwangle;": "⦧",
  23022. "vzigzag;": "⦚",
  23023. "zigrarr;": "⇝",
  23024. "andslope;": "⩘",
  23025. "angmsdaa;": "⦨",
  23026. "angmsdab;": "⦩",
  23027. "angmsdac;": "⦪",
  23028. "angmsdad;": "⦫",
  23029. "angmsdae;": "⦬",
  23030. "angmsdaf;": "⦭",
  23031. "angmsdag;": "⦮",
  23032. "angmsdah;": "⦯",
  23033. "angrtvbd;": "⦝",
  23034. "approxeq;": "≊",
  23035. "awconint;": "∳",
  23036. "backcong;": "≌",
  23037. "barwedge;": "⌅",
  23038. "bbrktbrk;": "⎶",
  23039. "bigoplus;": "⨁",
  23040. "bigsqcup;": "⨆",
  23041. "biguplus;": "⨄",
  23042. "bigwedge;": "⋀",
  23043. "boxminus;": "⊟",
  23044. "boxtimes;": "⊠",
  23045. "bsolhsub;": "⟈",
  23046. "capbrcup;": "⩉",
  23047. "circledR;": "®",
  23048. "circledS;": "Ⓢ",
  23049. "cirfnint;": "⨐",
  23050. "clubsuit;": "♣",
  23051. "cupbrcap;": "⩈",
  23052. "curlyvee;": "⋎",
  23053. "cwconint;": "∲",
  23054. "DDotrahd;": "⤑",
  23055. "doteqdot;": "≑",
  23056. "DotEqual;": "≐",
  23057. "dotminus;": "∸",
  23058. "drbkarow;": "⤐",
  23059. "dzigrarr;": "⟿",
  23060. "elinters;": "⏧",
  23061. "emptyset;": "∅",
  23062. "eqvparsl;": "⧥",
  23063. "fpartint;": "⨍",
  23064. "geqslant;": "⩾",
  23065. "gesdotol;": "⪄",
  23066. "gnapprox;": "⪊",
  23067. "hksearow;": "⤥",
  23068. "hkswarow;": "⤦",
  23069. "imagline;": "ℐ",
  23070. "imagpart;": "ℑ",
  23071. "infintie;": "⧝",
  23072. "integers;": "ℤ",
  23073. "Integral;": "∫",
  23074. "intercal;": "⊺",
  23075. "intlarhk;": "⨗",
  23076. "laemptyv;": "⦴",
  23077. "ldrushar;": "⥋",
  23078. "leqslant;": "⩽",
  23079. "lesdotor;": "⪃",
  23080. "LessLess;": "⪡",
  23081. "llcorner;": "⌞",
  23082. "lnapprox;": "⪉",
  23083. "lrcorner;": "⌟",
  23084. "lurdshar;": "⥊",
  23085. "mapstoup;": "↥",
  23086. "multimap;": "⊸",
  23087. "naturals;": "ℕ",
  23088. "ncongdot;": "⩭̸",
  23089. "NotEqual;": "≠",
  23090. "notindot;": "⋵̸",
  23091. "NotTilde;": "≁",
  23092. "otimesas;": "⨶",
  23093. "parallel;": "∥",
  23094. "PartialD;": "∂",
  23095. "plusacir;": "⨣",
  23096. "pointint;": "⨕",
  23097. "Precedes;": "≺",
  23098. "precneqq;": "⪵",
  23099. "precnsim;": "⋨",
  23100. "profalar;": "⌮",
  23101. "profline;": "⌒",
  23102. "profsurf;": "⌓",
  23103. "raemptyv;": "⦳",
  23104. "realpart;": "ℜ",
  23105. "RightTee;": "⊢",
  23106. "rppolint;": "⨒",
  23107. "rtriltri;": "⧎",
  23108. "scpolint;": "⨓",
  23109. "setminus;": "∖",
  23110. "shortmid;": "∣",
  23111. "smeparsl;": "⧤",
  23112. "sqsubset;": "⊏",
  23113. "sqsupset;": "⊐",
  23114. "subseteq;": "⊆",
  23115. "Succeeds;": "≻",
  23116. "succneqq;": "⪶",
  23117. "succnsim;": "⋩",
  23118. "SuchThat;": "∋",
  23119. "Superset;": "⊃",
  23120. "supseteq;": "⊇",
  23121. "thetasym;": "ϑ",
  23122. "thicksim;": "∼",
  23123. "timesbar;": "⨱",
  23124. "triangle;": "▵",
  23125. "triminus;": "⨺",
  23126. "trpezium;": "⏢",
  23127. "Uarrocir;": "⥉",
  23128. "ulcorner;": "⌜",
  23129. "UnderBar;": "_",
  23130. "urcorner;": "⌝",
  23131. "varkappa;": "ϰ",
  23132. "varsigma;": "ς",
  23133. "vartheta;": "ϑ",
  23134. "backprime;": "‵",
  23135. "backsimeq;": "⋍",
  23136. "Backslash;": "∖",
  23137. "bigotimes;": "⨂",
  23138. "CenterDot;": "·",
  23139. "centerdot;": "·",
  23140. "checkmark;": "✓",
  23141. "CircleDot;": "⊙",
  23142. "complexes;": "ℂ",
  23143. "Congruent;": "≡",
  23144. "Coproduct;": "∐",
  23145. "dotsquare;": "⊡",
  23146. "DoubleDot;": "¨",
  23147. "DownArrow;": "↓",
  23148. "Downarrow;": "⇓",
  23149. "downarrow;": "↓",
  23150. "DownBreve;": "̑",
  23151. "gtrapprox;": "⪆",
  23152. "gtreqless;": "⋛",
  23153. "gvertneqq;": "≩︀",
  23154. "heartsuit;": "♥",
  23155. "HumpEqual;": "≏",
  23156. "LeftArrow;": "←",
  23157. "Leftarrow;": "⇐",
  23158. "leftarrow;": "←",
  23159. "LeftFloor;": "⌊",
  23160. "lesseqgtr;": "⋚",
  23161. "LessTilde;": "≲",
  23162. "lvertneqq;": "≨︀",
  23163. "Mellintrf;": "ℳ",
  23164. "MinusPlus;": "∓",
  23165. "ngeqslant;": "⩾̸",
  23166. "nleqslant;": "⩽̸",
  23167. "NotCupCap;": "≭",
  23168. "NotExists;": "∄",
  23169. "NotSubset;": "⊂⃒",
  23170. "nparallel;": "∦",
  23171. "nshortmid;": "∤",
  23172. "nsubseteq;": "⊈",
  23173. "nsupseteq;": "⊉",
  23174. "OverBrace;": "⏞",
  23175. "pitchfork;": "⋔",
  23176. "PlusMinus;": "±",
  23177. "rationals;": "ℚ",
  23178. "spadesuit;": "♠",
  23179. "subseteqq;": "⫅",
  23180. "subsetneq;": "⊊",
  23181. "supseteqq;": "⫆",
  23182. "supsetneq;": "⊋",
  23183. "Therefore;": "∴",
  23184. "therefore;": "∴",
  23185. "ThinSpace;": " ",
  23186. "triangleq;": "≜",
  23187. "TripleDot;": "⃛",
  23188. "UnionPlus;": "⊎",
  23189. "varpropto;": "∝",
  23190. "Bernoullis;": "ℬ",
  23191. "circledast;": "⊛",
  23192. "CirclePlus;": "⊕",
  23193. "complement;": "∁",
  23194. "curlywedge;": "⋏",
  23195. "eqslantgtr;": "⪖",
  23196. "EqualTilde;": "≂",
  23197. "Fouriertrf;": "ℱ",
  23198. "gtreqqless;": "⪌",
  23199. "ImaginaryI;": "ⅈ",
  23200. "Laplacetrf;": "ℒ",
  23201. "LeftVector;": "↼",
  23202. "lessapprox;": "⪅",
  23203. "lesseqqgtr;": "⪋",
  23204. "Lleftarrow;": "⇚",
  23205. "lmoustache;": "⎰",
  23206. "longmapsto;": "⟼",
  23207. "mapstodown;": "↧",
  23208. "mapstoleft;": "↤",
  23209. "nLeftarrow;": "⇍",
  23210. "nleftarrow;": "↚",
  23211. "NotElement;": "∉",
  23212. "NotGreater;": "≯",
  23213. "nsubseteqq;": "⫅̸",
  23214. "nsupseteqq;": "⫆̸",
  23215. "precapprox;": "⪷",
  23216. "Proportion;": "∷",
  23217. "RightArrow;": "→",
  23218. "Rightarrow;": "⇒",
  23219. "rightarrow;": "→",
  23220. "RightFloor;": "⌋",
  23221. "rmoustache;": "⎱",
  23222. "sqsubseteq;": "⊑",
  23223. "sqsupseteq;": "⊒",
  23224. "subsetneqq;": "⫋",
  23225. "succapprox;": "⪸",
  23226. "supsetneqq;": "⫌",
  23227. "ThickSpace;": "  ",
  23228. "TildeEqual;": "≃",
  23229. "TildeTilde;": "≈",
  23230. "UnderBrace;": "⏟",
  23231. "UpArrowBar;": "⤒",
  23232. "UpTeeArrow;": "↥",
  23233. "upuparrows;": "⇈",
  23234. "varepsilon;": "ϵ",
  23235. "varnothing;": "∅",
  23236. "backepsilon;": "϶",
  23237. "blacksquare;": "▪",
  23238. "circledcirc;": "⊚",
  23239. "circleddash;": "⊝",
  23240. "CircleMinus;": "⊖",
  23241. "CircleTimes;": "⊗",
  23242. "curlyeqprec;": "⋞",
  23243. "curlyeqsucc;": "⋟",
  23244. "diamondsuit;": "♦",
  23245. "eqslantless;": "⪕",
  23246. "Equilibrium;": "⇌",
  23247. "expectation;": "ℰ",
  23248. "GreaterLess;": "≷",
  23249. "LeftCeiling;": "⌈",
  23250. "LessGreater;": "≶",
  23251. "MediumSpace;": " ",
  23252. "NotLessLess;": "≪̸",
  23253. "NotPrecedes;": "⊀",
  23254. "NotSucceeds;": "⊁",
  23255. "NotSuperset;": "⊃⃒",
  23256. "nRightarrow;": "⇏",
  23257. "nrightarrow;": "↛",
  23258. "OverBracket;": "⎴",
  23259. "preccurlyeq;": "≼",
  23260. "precnapprox;": "⪹",
  23261. "quaternions;": "ℍ",
  23262. "RightVector;": "⇀",
  23263. "Rrightarrow;": "⇛",
  23264. "RuleDelayed;": "⧴",
  23265. "SmallCircle;": "∘",
  23266. "SquareUnion;": "⊔",
  23267. "straightphi;": "ϕ",
  23268. "SubsetEqual;": "⊆",
  23269. "succcurlyeq;": "≽",
  23270. "succnapprox;": "⪺",
  23271. "thickapprox;": "≈",
  23272. "UpDownArrow;": "↕",
  23273. "Updownarrow;": "⇕",
  23274. "updownarrow;": "↕",
  23275. "VerticalBar;": "∣",
  23276. "blacklozenge;": "⧫",
  23277. "DownArrowBar;": "⤓",
  23278. "DownTeeArrow;": "↧",
  23279. "ExponentialE;": "ⅇ",
  23280. "exponentiale;": "ⅇ",
  23281. "GreaterEqual;": "≥",
  23282. "GreaterTilde;": "≳",
  23283. "HilbertSpace;": "ℋ",
  23284. "HumpDownHump;": "≎",
  23285. "Intersection;": "⋂",
  23286. "LeftArrowBar;": "⇤",
  23287. "LeftTeeArrow;": "↤",
  23288. "LeftTriangle;": "⊲",
  23289. "LeftUpVector;": "↿",
  23290. "NotCongruent;": "≢",
  23291. "NotHumpEqual;": "≏̸",
  23292. "NotLessEqual;": "≰",
  23293. "NotLessTilde;": "≴",
  23294. "Proportional;": "∝",
  23295. "RightCeiling;": "⌉",
  23296. "risingdotseq;": "≓",
  23297. "RoundImplies;": "⥰",
  23298. "ShortUpArrow;": "↑",
  23299. "SquareSubset;": "⊏",
  23300. "triangledown;": "▿",
  23301. "triangleleft;": "◃",
  23302. "UnderBracket;": "⎵",
  23303. "varsubsetneq;": "⊊︀",
  23304. "varsupsetneq;": "⊋︀",
  23305. "VerticalLine;": "|",
  23306. "ApplyFunction;": "⁡",
  23307. "bigtriangleup;": "△",
  23308. "blacktriangle;": "▴",
  23309. "DifferentialD;": "ⅆ",
  23310. "divideontimes;": "⋇",
  23311. "DoubleLeftTee;": "⫤",
  23312. "DoubleUpArrow;": "⇑",
  23313. "fallingdotseq;": "≒",
  23314. "hookleftarrow;": "↩",
  23315. "leftarrowtail;": "↢",
  23316. "leftharpoonup;": "↼",
  23317. "LeftTeeVector;": "⥚",
  23318. "LeftVectorBar;": "⥒",
  23319. "LessFullEqual;": "≦",
  23320. "LongLeftArrow;": "⟵",
  23321. "Longleftarrow;": "⟸",
  23322. "longleftarrow;": "⟵",
  23323. "looparrowleft;": "↫",
  23324. "measuredangle;": "∡",
  23325. "NotEqualTilde;": "≂̸",
  23326. "NotTildeEqual;": "≄",
  23327. "NotTildeTilde;": "≉",
  23328. "ntriangleleft;": "⋪",
  23329. "Poincareplane;": "ℌ",
  23330. "PrecedesEqual;": "⪯",
  23331. "PrecedesTilde;": "≾",
  23332. "RightArrowBar;": "⇥",
  23333. "RightTeeArrow;": "↦",
  23334. "RightTriangle;": "⊳",
  23335. "RightUpVector;": "↾",
  23336. "shortparallel;": "∥",
  23337. "smallsetminus;": "∖",
  23338. "SucceedsEqual;": "⪰",
  23339. "SucceedsTilde;": "≿",
  23340. "SupersetEqual;": "⊇",
  23341. "triangleright;": "▹",
  23342. "UpEquilibrium;": "⥮",
  23343. "upharpoonleft;": "↿",
  23344. "varsubsetneqq;": "⫋︀",
  23345. "varsupsetneqq;": "⫌︀",
  23346. "VerticalTilde;": "≀",
  23347. "VeryThinSpace;": " ",
  23348. "curvearrowleft;": "↶",
  23349. "DiacriticalDot;": "˙",
  23350. "doublebarwedge;": "⌆",
  23351. "DoubleRightTee;": "⊨",
  23352. "downdownarrows;": "⇊",
  23353. "DownLeftVector;": "↽",
  23354. "GreaterGreater;": "⪢",
  23355. "hookrightarrow;": "↪",
  23356. "HorizontalLine;": "─",
  23357. "InvisibleComma;": "⁣",
  23358. "InvisibleTimes;": "⁢",
  23359. "LeftDownVector;": "⇃",
  23360. "leftleftarrows;": "⇇",
  23361. "LeftRightArrow;": "↔",
  23362. "Leftrightarrow;": "⇔",
  23363. "leftrightarrow;": "↔",
  23364. "leftthreetimes;": "⋋",
  23365. "LessSlantEqual;": "⩽",
  23366. "LongRightArrow;": "⟶",
  23367. "Longrightarrow;": "⟹",
  23368. "longrightarrow;": "⟶",
  23369. "looparrowright;": "↬",
  23370. "LowerLeftArrow;": "↙",
  23371. "NestedLessLess;": "≪",
  23372. "NotGreaterLess;": "≹",
  23373. "NotLessGreater;": "≸",
  23374. "NotSubsetEqual;": "⊈",
  23375. "NotVerticalBar;": "∤",
  23376. "nshortparallel;": "∦",
  23377. "ntriangleright;": "⋫",
  23378. "OpenCurlyQuote;": "‘",
  23379. "ReverseElement;": "∋",
  23380. "rightarrowtail;": "↣",
  23381. "rightharpoonup;": "⇀",
  23382. "RightTeeVector;": "⥛",
  23383. "RightVectorBar;": "⥓",
  23384. "ShortDownArrow;": "↓",
  23385. "ShortLeftArrow;": "←",
  23386. "SquareSuperset;": "⊐",
  23387. "TildeFullEqual;": "≅",
  23388. "trianglelefteq;": "⊴",
  23389. "upharpoonright;": "↾",
  23390. "UpperLeftArrow;": "↖",
  23391. "ZeroWidthSpace;": "​",
  23392. "bigtriangledown;": "▽",
  23393. "circlearrowleft;": "↺",
  23394. "CloseCurlyQuote;": "’",
  23395. "ContourIntegral;": "∮",
  23396. "curvearrowright;": "↷",
  23397. "DoubleDownArrow;": "⇓",
  23398. "DoubleLeftArrow;": "⇐",
  23399. "downharpoonleft;": "⇃",
  23400. "DownRightVector;": "⇁",
  23401. "leftharpoondown;": "↽",
  23402. "leftrightarrows;": "⇆",
  23403. "LeftRightVector;": "⥎",
  23404. "LeftTriangleBar;": "⧏",
  23405. "LeftUpTeeVector;": "⥠",
  23406. "LeftUpVectorBar;": "⥘",
  23407. "LowerRightArrow;": "↘",
  23408. "nLeftrightarrow;": "⇎",
  23409. "nleftrightarrow;": "↮",
  23410. "NotGreaterEqual;": "≱",
  23411. "NotGreaterTilde;": "≵",
  23412. "NotHumpDownHump;": "≎̸",
  23413. "NotLeftTriangle;": "⋪",
  23414. "NotSquareSubset;": "⊏̸",
  23415. "ntrianglelefteq;": "⋬",
  23416. "OverParenthesis;": "⏜",
  23417. "RightDownVector;": "⇂",
  23418. "rightleftarrows;": "⇄",
  23419. "rightsquigarrow;": "↝",
  23420. "rightthreetimes;": "⋌",
  23421. "ShortRightArrow;": "→",
  23422. "straightepsilon;": "ϵ",
  23423. "trianglerighteq;": "⊵",
  23424. "UpperRightArrow;": "↗",
  23425. "vartriangleleft;": "⊲",
  23426. "circlearrowright;": "↻",
  23427. "DiacriticalAcute;": "´",
  23428. "DiacriticalGrave;": "`",
  23429. "DiacriticalTilde;": "˜",
  23430. "DoubleRightArrow;": "⇒",
  23431. "DownArrowUpArrow;": "⇵",
  23432. "downharpoonright;": "⇂",
  23433. "EmptySmallSquare;": "◻",
  23434. "GreaterEqualLess;": "⋛",
  23435. "GreaterFullEqual;": "≧",
  23436. "LeftAngleBracket;": "⟨",
  23437. "LeftUpDownVector;": "⥑",
  23438. "LessEqualGreater;": "⋚",
  23439. "NonBreakingSpace;": " ",
  23440. "NotPrecedesEqual;": "⪯̸",
  23441. "NotRightTriangle;": "⋫",
  23442. "NotSucceedsEqual;": "⪰̸",
  23443. "NotSucceedsTilde;": "≿̸",
  23444. "NotSupersetEqual;": "⊉",
  23445. "ntrianglerighteq;": "⋭",
  23446. "rightharpoondown;": "⇁",
  23447. "rightrightarrows;": "⇉",
  23448. "RightTriangleBar;": "⧐",
  23449. "RightUpTeeVector;": "⥜",
  23450. "RightUpVectorBar;": "⥔",
  23451. "twoheadleftarrow;": "↞",
  23452. "UnderParenthesis;": "⏝",
  23453. "UpArrowDownArrow;": "⇅",
  23454. "vartriangleright;": "⊳",
  23455. "blacktriangledown;": "▾",
  23456. "blacktriangleleft;": "◂",
  23457. "DoubleUpDownArrow;": "⇕",
  23458. "DoubleVerticalBar;": "∥",
  23459. "DownLeftTeeVector;": "⥞",
  23460. "DownLeftVectorBar;": "⥖",
  23461. "FilledSmallSquare;": "◼",
  23462. "GreaterSlantEqual;": "⩾",
  23463. "LeftDoubleBracket;": "⟦",
  23464. "LeftDownTeeVector;": "⥡",
  23465. "LeftDownVectorBar;": "⥙",
  23466. "leftrightharpoons;": "⇋",
  23467. "LeftTriangleEqual;": "⊴",
  23468. "NegativeThinSpace;": "​",
  23469. "NotGreaterGreater;": "≫̸",
  23470. "NotLessSlantEqual;": "⩽̸",
  23471. "NotNestedLessLess;": "⪡̸",
  23472. "NotReverseElement;": "∌",
  23473. "NotSquareSuperset;": "⊐̸",
  23474. "NotTildeFullEqual;": "≇",
  23475. "RightAngleBracket;": "⟩",
  23476. "rightleftharpoons;": "⇌",
  23477. "RightUpDownVector;": "⥏",
  23478. "SquareSubsetEqual;": "⊑",
  23479. "twoheadrightarrow;": "↠",
  23480. "VerticalSeparator;": "❘",
  23481. "blacktriangleright;": "▸",
  23482. "DownRightTeeVector;": "⥟",
  23483. "DownRightVectorBar;": "⥗",
  23484. "LongLeftRightArrow;": "⟷",
  23485. "Longleftrightarrow;": "⟺",
  23486. "longleftrightarrow;": "⟷",
  23487. "NegativeThickSpace;": "​",
  23488. "NotLeftTriangleBar;": "⧏̸",
  23489. "PrecedesSlantEqual;": "≼",
  23490. "ReverseEquilibrium;": "⇋",
  23491. "RightDoubleBracket;": "⟧",
  23492. "RightDownTeeVector;": "⥝",
  23493. "RightDownVectorBar;": "⥕",
  23494. "RightTriangleEqual;": "⊵",
  23495. "SquareIntersection;": "⊓",
  23496. "SucceedsSlantEqual;": "≽",
  23497. "DoubleLongLeftArrow;": "⟸",
  23498. "DownLeftRightVector;": "⥐",
  23499. "LeftArrowRightArrow;": "⇆",
  23500. "leftrightsquigarrow;": "↭",
  23501. "NegativeMediumSpace;": "​",
  23502. "NotGreaterFullEqual;": "≧̸",
  23503. "NotRightTriangleBar;": "⧐̸",
  23504. "RightArrowLeftArrow;": "⇄",
  23505. "SquareSupersetEqual;": "⊒",
  23506. "CapitalDifferentialD;": "ⅅ",
  23507. "DoubleLeftRightArrow;": "⇔",
  23508. "DoubleLongRightArrow;": "⟹",
  23509. "EmptyVerySmallSquare;": "▫",
  23510. "NestedGreaterGreater;": "≫",
  23511. "NotDoubleVerticalBar;": "∦",
  23512. "NotGreaterSlantEqual;": "⩾̸",
  23513. "NotLeftTriangleEqual;": "⋬",
  23514. "NotSquareSubsetEqual;": "⋢",
  23515. "OpenCurlyDoubleQuote;": "“",
  23516. "ReverseUpEquilibrium;": "⥯",
  23517. "CloseCurlyDoubleQuote;": "”",
  23518. "DoubleContourIntegral;": "∯",
  23519. "FilledVerySmallSquare;": "▪",
  23520. "NegativeVeryThinSpace;": "​",
  23521. "NotPrecedesSlantEqual;": "⋠",
  23522. "NotRightTriangleEqual;": "⋭",
  23523. "NotSucceedsSlantEqual;": "⋡",
  23524. "DiacriticalDoubleAcute;": "˝",
  23525. "NotSquareSupersetEqual;": "⋣",
  23526. "NotNestedGreaterGreater;": "⪢̸",
  23527. "ClockwiseContourIntegral;": "∲",
  23528. "DoubleLongLeftRightArrow;": "⟺",
  23529. "CounterClockwiseContourIntegral;": "∳"
  23530. };
  23531. // lazy compute this to make this file tree-shakable for browser
  23532. let maxCRNameLength;
  23533. const decodeHtml = (rawText, asAttr) => {
  23534. let offset = 0;
  23535. const end = rawText.length;
  23536. let decodedText = '';
  23537. function advance(length) {
  23538. offset += length;
  23539. rawText = rawText.slice(length);
  23540. }
  23541. while (offset < end) {
  23542. const head = /&(?:#x?)?/i.exec(rawText);
  23543. if (!head || offset + head.index >= end) {
  23544. const remaining = end - offset;
  23545. decodedText += rawText.slice(0, remaining);
  23546. advance(remaining);
  23547. break;
  23548. }
  23549. // Advance to the "&".
  23550. decodedText += rawText.slice(0, head.index);
  23551. advance(head.index);
  23552. if (head[0] === '&') {
  23553. // Named character reference.
  23554. let name = '';
  23555. let value = undefined;
  23556. if (/[0-9a-z]/i.test(rawText[1])) {
  23557. if (!maxCRNameLength) {
  23558. maxCRNameLength = Object.keys(namedCharacterReferences).reduce((max, name) => Math.max(max, name.length), 0);
  23559. }
  23560. for (let length = maxCRNameLength; !value && length > 0; --length) {
  23561. name = rawText.slice(1, 1 + length);
  23562. value = namedCharacterReferences[name];
  23563. }
  23564. if (value) {
  23565. const semi = name.endsWith(';');
  23566. if (asAttr &&
  23567. !semi &&
  23568. /[=a-z0-9]/i.test(rawText[name.length + 1] || '')) {
  23569. decodedText += '&' + name;
  23570. advance(1 + name.length);
  23571. }
  23572. else {
  23573. decodedText += value;
  23574. advance(1 + name.length);
  23575. }
  23576. }
  23577. else {
  23578. decodedText += '&' + name;
  23579. advance(1 + name.length);
  23580. }
  23581. }
  23582. else {
  23583. decodedText += '&';
  23584. advance(1);
  23585. }
  23586. }
  23587. else {
  23588. // Numeric character reference.
  23589. const hex = head[0] === '&#x';
  23590. const pattern = hex ? /^&#x([0-9a-f]+);?/i : /^&#([0-9]+);?/;
  23591. const body = pattern.exec(rawText);
  23592. if (!body) {
  23593. decodedText += head[0];
  23594. advance(head[0].length);
  23595. }
  23596. else {
  23597. // https://html.spec.whatwg.org/multipage/parsing.html#numeric-character-reference-end-state
  23598. let cp = Number.parseInt(body[1], hex ? 16 : 10);
  23599. if (cp === 0) {
  23600. cp = 0xfffd;
  23601. }
  23602. else if (cp > 0x10ffff) {
  23603. cp = 0xfffd;
  23604. }
  23605. else if (cp >= 0xd800 && cp <= 0xdfff) {
  23606. cp = 0xfffd;
  23607. }
  23608. else if ((cp >= 0xfdd0 && cp <= 0xfdef) || (cp & 0xfffe) === 0xfffe) ;
  23609. else if ((cp >= 0x01 && cp <= 0x08) ||
  23610. cp === 0x0b ||
  23611. (cp >= 0x0d && cp <= 0x1f) ||
  23612. (cp >= 0x7f && cp <= 0x9f)) {
  23613. cp = CCR_REPLACEMENTS[cp] || cp;
  23614. }
  23615. decodedText += String.fromCodePoint(cp);
  23616. advance(body[0].length);
  23617. }
  23618. }
  23619. }
  23620. return decodedText;
  23621. };
  23622. // https://html.spec.whatwg.org/multipage/parsing.html#numeric-character-reference-end-state
  23623. const CCR_REPLACEMENTS = {
  23624. 0x80: 0x20ac,
  23625. 0x82: 0x201a,
  23626. 0x83: 0x0192,
  23627. 0x84: 0x201e,
  23628. 0x85: 0x2026,
  23629. 0x86: 0x2020,
  23630. 0x87: 0x2021,
  23631. 0x88: 0x02c6,
  23632. 0x89: 0x2030,
  23633. 0x8a: 0x0160,
  23634. 0x8b: 0x2039,
  23635. 0x8c: 0x0152,
  23636. 0x8e: 0x017d,
  23637. 0x91: 0x2018,
  23638. 0x92: 0x2019,
  23639. 0x93: 0x201c,
  23640. 0x94: 0x201d,
  23641. 0x95: 0x2022,
  23642. 0x96: 0x2013,
  23643. 0x97: 0x2014,
  23644. 0x98: 0x02dc,
  23645. 0x99: 0x2122,
  23646. 0x9a: 0x0161,
  23647. 0x9b: 0x203a,
  23648. 0x9c: 0x0153,
  23649. 0x9e: 0x017e,
  23650. 0x9f: 0x0178
  23651. };
  23652. const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
  23653. const parserOptions = {
  23654. isVoidTag,
  23655. isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
  23656. isPreTag: tag => tag === 'pre',
  23657. decodeEntities: decodeHtml,
  23658. isBuiltInComponent: (tag) => {
  23659. if (isBuiltInType(tag, `Transition`)) {
  23660. return TRANSITION;
  23661. }
  23662. else if (isBuiltInType(tag, `TransitionGroup`)) {
  23663. return TRANSITION_GROUP;
  23664. }
  23665. },
  23666. // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
  23667. getNamespace(tag, parent) {
  23668. let ns = parent ? parent.ns : 0 /* DOMNamespaces.HTML */;
  23669. if (parent && ns === 2 /* DOMNamespaces.MATH_ML */) {
  23670. if (parent.tag === 'annotation-xml') {
  23671. if (tag === 'svg') {
  23672. return 1 /* DOMNamespaces.SVG */;
  23673. }
  23674. if (parent.props.some(a => a.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  23675. a.name === 'encoding' &&
  23676. a.value != null &&
  23677. (a.value.content === 'text/html' ||
  23678. a.value.content === 'application/xhtml+xml'))) {
  23679. ns = 0 /* DOMNamespaces.HTML */;
  23680. }
  23681. }
  23682. else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
  23683. tag !== 'mglyph' &&
  23684. tag !== 'malignmark') {
  23685. ns = 0 /* DOMNamespaces.HTML */;
  23686. }
  23687. }
  23688. else if (parent && ns === 1 /* DOMNamespaces.SVG */) {
  23689. if (parent.tag === 'foreignObject' ||
  23690. parent.tag === 'desc' ||
  23691. parent.tag === 'title') {
  23692. ns = 0 /* DOMNamespaces.HTML */;
  23693. }
  23694. }
  23695. if (ns === 0 /* DOMNamespaces.HTML */) {
  23696. if (tag === 'svg') {
  23697. return 1 /* DOMNamespaces.SVG */;
  23698. }
  23699. if (tag === 'math') {
  23700. return 2 /* DOMNamespaces.MATH_ML */;
  23701. }
  23702. }
  23703. return ns;
  23704. },
  23705. // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
  23706. getTextMode({ tag, ns }) {
  23707. if (ns === 0 /* DOMNamespaces.HTML */) {
  23708. if (tag === 'textarea' || tag === 'title') {
  23709. return 1 /* TextModes.RCDATA */;
  23710. }
  23711. if (isRawTextContainer(tag)) {
  23712. return 2 /* TextModes.RAWTEXT */;
  23713. }
  23714. }
  23715. return 0 /* TextModes.DATA */;
  23716. }
  23717. };
  23718. // Parse inline CSS strings for static style attributes into an object.
  23719. // This is a NodeTransform since it works on the static `style` attribute and
  23720. // converts it into a dynamic equivalent:
  23721. // style="color: red" -> :style='{ "color": "red" }'
  23722. // It is then processed by `transformElement` and included in the generated
  23723. // props.
  23724. const transformStyle = node => {
  23725. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  23726. node.props.forEach((p, i) => {
  23727. if (p.type === 6 /* NodeTypes.ATTRIBUTE */ && p.name === 'style' && p.value) {
  23728. // replace p with an expression node
  23729. node.props[i] = {
  23730. type: 7 /* NodeTypes.DIRECTIVE */,
  23731. name: `bind`,
  23732. arg: createSimpleExpression(`style`, true, p.loc),
  23733. exp: parseInlineCSS(p.value.content, p.loc),
  23734. modifiers: [],
  23735. loc: p.loc
  23736. };
  23737. }
  23738. });
  23739. }
  23740. };
  23741. const parseInlineCSS = (cssText, loc) => {
  23742. const normalized = parseStringStyle(cssText);
  23743. return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  23744. };
  23745. function createDOMCompilerError(code, loc) {
  23746. return createCompilerError(code, loc, DOMErrorMessages );
  23747. }
  23748. const DOMErrorMessages = {
  23749. [51 /* DOMErrorCodes.X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
  23750. [52 /* DOMErrorCodes.X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
  23751. [53 /* DOMErrorCodes.X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
  23752. [54 /* DOMErrorCodes.X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
  23753. [55 /* DOMErrorCodes.X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
  23754. [56 /* DOMErrorCodes.X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
  23755. [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.`,
  23756. [58 /* DOMErrorCodes.X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
  23757. [59 /* DOMErrorCodes.X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
  23758. [60 /* DOMErrorCodes.X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
  23759. [61 /* DOMErrorCodes.X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
  23760. };
  23761. const transformVHtml = (dir, node, context) => {
  23762. const { exp, loc } = dir;
  23763. if (!exp) {
  23764. context.onError(createDOMCompilerError(51 /* DOMErrorCodes.X_V_HTML_NO_EXPRESSION */, loc));
  23765. }
  23766. if (node.children.length) {
  23767. context.onError(createDOMCompilerError(52 /* DOMErrorCodes.X_V_HTML_WITH_CHILDREN */, loc));
  23768. node.children.length = 0;
  23769. }
  23770. return {
  23771. props: [
  23772. createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
  23773. ]
  23774. };
  23775. };
  23776. const transformVText = (dir, node, context) => {
  23777. const { exp, loc } = dir;
  23778. if (!exp) {
  23779. context.onError(createDOMCompilerError(53 /* DOMErrorCodes.X_V_TEXT_NO_EXPRESSION */, loc));
  23780. }
  23781. if (node.children.length) {
  23782. context.onError(createDOMCompilerError(54 /* DOMErrorCodes.X_V_TEXT_WITH_CHILDREN */, loc));
  23783. node.children.length = 0;
  23784. }
  23785. return {
  23786. props: [
  23787. createObjectProperty(createSimpleExpression(`textContent`, true), exp
  23788. ? getConstantType(exp, context) > 0
  23789. ? exp
  23790. : createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
  23791. : createSimpleExpression('', true))
  23792. ]
  23793. };
  23794. };
  23795. const transformModel$1 = (dir, node, context) => {
  23796. const baseResult = transformModel(dir, node, context);
  23797. // base transform has errors OR component v-model (only need props)
  23798. if (!baseResult.props.length || node.tagType === 1 /* ElementTypes.COMPONENT */) {
  23799. return baseResult;
  23800. }
  23801. if (dir.arg) {
  23802. context.onError(createDOMCompilerError(56 /* DOMErrorCodes.X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
  23803. }
  23804. function checkDuplicatedValue() {
  23805. const value = findProp(node, 'value');
  23806. if (value) {
  23807. context.onError(createDOMCompilerError(58 /* DOMErrorCodes.X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
  23808. }
  23809. }
  23810. const { tag } = node;
  23811. const isCustomElement = context.isCustomElement(tag);
  23812. if (tag === 'input' ||
  23813. tag === 'textarea' ||
  23814. tag === 'select' ||
  23815. isCustomElement) {
  23816. let directiveToUse = V_MODEL_TEXT;
  23817. let isInvalidType = false;
  23818. if (tag === 'input' || isCustomElement) {
  23819. const type = findProp(node, `type`);
  23820. if (type) {
  23821. if (type.type === 7 /* NodeTypes.DIRECTIVE */) {
  23822. // :type="foo"
  23823. directiveToUse = V_MODEL_DYNAMIC;
  23824. }
  23825. else if (type.value) {
  23826. switch (type.value.content) {
  23827. case 'radio':
  23828. directiveToUse = V_MODEL_RADIO;
  23829. break;
  23830. case 'checkbox':
  23831. directiveToUse = V_MODEL_CHECKBOX;
  23832. break;
  23833. case 'file':
  23834. isInvalidType = true;
  23835. context.onError(createDOMCompilerError(57 /* DOMErrorCodes.X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
  23836. break;
  23837. default:
  23838. // text type
  23839. checkDuplicatedValue();
  23840. break;
  23841. }
  23842. }
  23843. }
  23844. else if (hasDynamicKeyVBind(node)) {
  23845. // element has bindings with dynamic keys, which can possibly contain
  23846. // "type".
  23847. directiveToUse = V_MODEL_DYNAMIC;
  23848. }
  23849. else {
  23850. // text type
  23851. checkDuplicatedValue();
  23852. }
  23853. }
  23854. else if (tag === 'select') {
  23855. directiveToUse = V_MODEL_SELECT;
  23856. }
  23857. else {
  23858. // textarea
  23859. checkDuplicatedValue();
  23860. }
  23861. // inject runtime directive
  23862. // by returning the helper symbol via needRuntime
  23863. // the import will replaced a resolveDirective call.
  23864. if (!isInvalidType) {
  23865. baseResult.needRuntime = context.helper(directiveToUse);
  23866. }
  23867. }
  23868. else {
  23869. context.onError(createDOMCompilerError(55 /* DOMErrorCodes.X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
  23870. }
  23871. // native vmodel doesn't need the `modelValue` props since they are also
  23872. // passed to the runtime as `binding.value`. removing it reduces code size.
  23873. baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  23874. p.key.content === 'modelValue'));
  23875. return baseResult;
  23876. };
  23877. const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
  23878. const isNonKeyModifier = /*#__PURE__*/ makeMap(
  23879. // event propagation management
  23880. `stop,prevent,self,` +
  23881. // system modifiers + exact
  23882. `ctrl,shift,alt,meta,exact,` +
  23883. // mouse
  23884. `middle`);
  23885. // left & right could be mouse or key modifiers based on event type
  23886. const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
  23887. const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
  23888. const resolveModifiers = (key, modifiers, context, loc) => {
  23889. const keyModifiers = [];
  23890. const nonKeyModifiers = [];
  23891. const eventOptionModifiers = [];
  23892. for (let i = 0; i < modifiers.length; i++) {
  23893. const modifier = modifiers[i];
  23894. if (isEventOptionModifier(modifier)) {
  23895. // eventOptionModifiers: modifiers for addEventListener() options,
  23896. // e.g. .passive & .capture
  23897. eventOptionModifiers.push(modifier);
  23898. }
  23899. else {
  23900. // runtimeModifiers: modifiers that needs runtime guards
  23901. if (maybeKeyModifier(modifier)) {
  23902. if (isStaticExp(key)) {
  23903. if (isKeyboardEvent(key.content)) {
  23904. keyModifiers.push(modifier);
  23905. }
  23906. else {
  23907. nonKeyModifiers.push(modifier);
  23908. }
  23909. }
  23910. else {
  23911. keyModifiers.push(modifier);
  23912. nonKeyModifiers.push(modifier);
  23913. }
  23914. }
  23915. else {
  23916. if (isNonKeyModifier(modifier)) {
  23917. nonKeyModifiers.push(modifier);
  23918. }
  23919. else {
  23920. keyModifiers.push(modifier);
  23921. }
  23922. }
  23923. }
  23924. }
  23925. return {
  23926. keyModifiers,
  23927. nonKeyModifiers,
  23928. eventOptionModifiers
  23929. };
  23930. };
  23931. const transformClick = (key, event) => {
  23932. const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
  23933. return isStaticClick
  23934. ? createSimpleExpression(event, true)
  23935. : key.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */
  23936. ? createCompoundExpression([
  23937. `(`,
  23938. key,
  23939. `) === "onClick" ? "${event}" : (`,
  23940. key,
  23941. `)`
  23942. ])
  23943. : key;
  23944. };
  23945. const transformOn$1 = (dir, node, context) => {
  23946. return transformOn(dir, node, context, baseResult => {
  23947. const { modifiers } = dir;
  23948. if (!modifiers.length)
  23949. return baseResult;
  23950. let { key, value: handlerExp } = baseResult.props[0];
  23951. const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
  23952. // normalize click.right and click.middle since they don't actually fire
  23953. if (nonKeyModifiers.includes('right')) {
  23954. key = transformClick(key, `onContextmenu`);
  23955. }
  23956. if (nonKeyModifiers.includes('middle')) {
  23957. key = transformClick(key, `onMouseup`);
  23958. }
  23959. if (nonKeyModifiers.length) {
  23960. handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
  23961. handlerExp,
  23962. JSON.stringify(nonKeyModifiers)
  23963. ]);
  23964. }
  23965. if (keyModifiers.length &&
  23966. // if event name is dynamic, always wrap with keys guard
  23967. (!isStaticExp(key) || isKeyboardEvent(key.content))) {
  23968. handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
  23969. handlerExp,
  23970. JSON.stringify(keyModifiers)
  23971. ]);
  23972. }
  23973. if (eventOptionModifiers.length) {
  23974. const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
  23975. key = isStaticExp(key)
  23976. ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
  23977. : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
  23978. }
  23979. return {
  23980. props: [createObjectProperty(key, handlerExp)]
  23981. };
  23982. });
  23983. };
  23984. const transformShow = (dir, node, context) => {
  23985. const { exp, loc } = dir;
  23986. if (!exp) {
  23987. context.onError(createDOMCompilerError(59 /* DOMErrorCodes.X_V_SHOW_NO_EXPRESSION */, loc));
  23988. }
  23989. return {
  23990. props: [],
  23991. needRuntime: context.helper(V_SHOW)
  23992. };
  23993. };
  23994. const transformTransition = (node, context) => {
  23995. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  23996. node.tagType === 1 /* ElementTypes.COMPONENT */) {
  23997. const component = context.isBuiltInComponent(node.tag);
  23998. if (component === TRANSITION) {
  23999. return () => {
  24000. if (!node.children.length) {
  24001. return;
  24002. }
  24003. // warn multiple transition children
  24004. if (hasMultipleChildren(node)) {
  24005. context.onError(createDOMCompilerError(60 /* DOMErrorCodes.X_TRANSITION_INVALID_CHILDREN */, {
  24006. start: node.children[0].loc.start,
  24007. end: node.children[node.children.length - 1].loc.end,
  24008. source: ''
  24009. }));
  24010. }
  24011. // check if it's s single child w/ v-show
  24012. // if yes, inject "persisted: true" to the transition props
  24013. const child = node.children[0];
  24014. if (child.type === 1 /* NodeTypes.ELEMENT */) {
  24015. for (const p of child.props) {
  24016. if (p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'show') {
  24017. node.props.push({
  24018. type: 6 /* NodeTypes.ATTRIBUTE */,
  24019. name: 'persisted',
  24020. value: undefined,
  24021. loc: node.loc
  24022. });
  24023. }
  24024. }
  24025. }
  24026. };
  24027. }
  24028. }
  24029. };
  24030. function hasMultipleChildren(node) {
  24031. // #1352 filter out potential comment nodes.
  24032. const children = (node.children = node.children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */ &&
  24033. !(c.type === 2 /* NodeTypes.TEXT */ && !c.content.trim())));
  24034. const child = children[0];
  24035. return (children.length !== 1 ||
  24036. child.type === 11 /* NodeTypes.FOR */ ||
  24037. (child.type === 9 /* NodeTypes.IF */ && child.branches.some(hasMultipleChildren)));
  24038. }
  24039. /**
  24040. * This module is Node-only.
  24041. */
  24042. /**
  24043. * Regex for replacing placeholders for embedded constant variables
  24044. * (e.g. import URL string constants generated by compiler-sfc)
  24045. */
  24046. const expReplaceRE = /__VUE_EXP_START__(.*?)__VUE_EXP_END__/g;
  24047. /**
  24048. * Turn eligible hoisted static trees into stringified static nodes, e.g.
  24049. *
  24050. * ```js
  24051. * const _hoisted_1 = createStaticVNode(`<div class="foo">bar</div>`)
  24052. * ```
  24053. *
  24054. * A single static vnode can contain stringified content for **multiple**
  24055. * consecutive nodes (element and plain text), called a "chunk".
  24056. * `@vue/runtime-dom` will create the content via innerHTML in a hidden
  24057. * container element and insert all the nodes in place. The call must also
  24058. * provide the number of nodes contained in the chunk so that during hydration
  24059. * we can know how many nodes the static vnode should adopt.
  24060. *
  24061. * The optimization scans a children list that contains hoisted nodes, and
  24062. * tries to find the largest chunk of consecutive hoisted nodes before running
  24063. * into a non-hoisted node or the end of the list. A chunk is then converted
  24064. * into a single static vnode and replaces the hoisted expression of the first
  24065. * node in the chunk. Other nodes in the chunk are considered "merged" and
  24066. * therefore removed from both the hoist list and the children array.
  24067. *
  24068. * This optimization is only performed in Node.js.
  24069. */
  24070. const stringifyStatic = (children, context, parent) => {
  24071. // bail stringification for slot content
  24072. if (context.scopes.vSlot > 0) {
  24073. return;
  24074. }
  24075. let nc = 0; // current node count
  24076. let ec = 0; // current element with binding count
  24077. const currentChunk = [];
  24078. const stringifyCurrentChunk = (currentIndex) => {
  24079. if (nc >= 20 /* StringifyThresholds.NODE_COUNT */ ||
  24080. ec >= 5 /* StringifyThresholds.ELEMENT_WITH_BINDING_COUNT */) {
  24081. // combine all currently eligible nodes into a single static vnode call
  24082. const staticCall = createCallExpression(context.helper(CREATE_STATIC), [
  24083. JSON.stringify(currentChunk.map(node => stringifyNode(node, context)).join('')).replace(expReplaceRE, `" + $1 + "`),
  24084. // the 2nd argument indicates the number of DOM nodes this static vnode
  24085. // will insert / hydrate
  24086. String(currentChunk.length)
  24087. ]);
  24088. // replace the first node's hoisted expression with the static vnode call
  24089. replaceHoist(currentChunk[0], staticCall, context);
  24090. if (currentChunk.length > 1) {
  24091. for (let i = 1; i < currentChunk.length; i++) {
  24092. // for the merged nodes, set their hoisted expression to null
  24093. replaceHoist(currentChunk[i], null, context);
  24094. }
  24095. // also remove merged nodes from children
  24096. const deleteCount = currentChunk.length - 1;
  24097. children.splice(currentIndex - currentChunk.length + 1, deleteCount);
  24098. return deleteCount;
  24099. }
  24100. }
  24101. return 0;
  24102. };
  24103. let i = 0;
  24104. for (; i < children.length; i++) {
  24105. const child = children[i];
  24106. const hoisted = getHoistedNode(child);
  24107. if (hoisted) {
  24108. // presence of hoisted means child must be a stringifiable node
  24109. const node = child;
  24110. const result = analyzeNode(node);
  24111. if (result) {
  24112. // node is stringifiable, record state
  24113. nc += result[0];
  24114. ec += result[1];
  24115. currentChunk.push(node);
  24116. continue;
  24117. }
  24118. }
  24119. // we only reach here if we ran into a node that is not stringifiable
  24120. // check if currently analyzed nodes meet criteria for stringification.
  24121. // adjust iteration index
  24122. i -= stringifyCurrentChunk(i);
  24123. // reset state
  24124. nc = 0;
  24125. ec = 0;
  24126. currentChunk.length = 0;
  24127. }
  24128. // in case the last node was also stringifiable
  24129. stringifyCurrentChunk(i);
  24130. };
  24131. const getHoistedNode = (node) => ((node.type === 1 /* NodeTypes.ELEMENT */ && node.tagType === 0 /* ElementTypes.ELEMENT */) ||
  24132. node.type == 12 /* NodeTypes.TEXT_CALL */) &&
  24133. node.codegenNode &&
  24134. node.codegenNode.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  24135. node.codegenNode.hoisted;
  24136. const dataAriaRE = /^(data|aria)-/;
  24137. const isStringifiableAttr = (name, ns) => {
  24138. return ((ns === 0 /* DOMNamespaces.HTML */
  24139. ? isKnownHtmlAttr(name)
  24140. : ns === 1 /* DOMNamespaces.SVG */
  24141. ? isKnownSvgAttr(name)
  24142. : false) || dataAriaRE.test(name));
  24143. };
  24144. const replaceHoist = (node, replacement, context) => {
  24145. const hoistToReplace = node.codegenNode.hoisted;
  24146. context.hoists[context.hoists.indexOf(hoistToReplace)] = replacement;
  24147. };
  24148. const isNonStringifiable = /*#__PURE__*/ makeMap(`caption,thead,tr,th,tbody,td,tfoot,colgroup,col`);
  24149. /**
  24150. * for a hoisted node, analyze it and return:
  24151. * - false: bailed (contains non-stringifiable props or runtime constant)
  24152. * - [nc, ec] where
  24153. * - nc is the number of nodes inside
  24154. * - ec is the number of element with bindings inside
  24155. */
  24156. function analyzeNode(node) {
  24157. if (node.type === 1 /* NodeTypes.ELEMENT */ && isNonStringifiable(node.tag)) {
  24158. return false;
  24159. }
  24160. if (node.type === 12 /* NodeTypes.TEXT_CALL */) {
  24161. return [1, 0];
  24162. }
  24163. let nc = 1; // node count
  24164. let ec = node.props.length > 0 ? 1 : 0; // element w/ binding count
  24165. let bailed = false;
  24166. const bail = () => {
  24167. bailed = true;
  24168. return false;
  24169. };
  24170. // TODO: check for cases where using innerHTML will result in different
  24171. // output compared to imperative node insertions.
  24172. // probably only need to check for most common case
  24173. // i.e. non-phrasing-content tags inside `<p>`
  24174. function walk(node) {
  24175. for (let i = 0; i < node.props.length; i++) {
  24176. const p = node.props[i];
  24177. // bail on non-attr bindings
  24178. if (p.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  24179. !isStringifiableAttr(p.name, node.ns)) {
  24180. return bail();
  24181. }
  24182. if (p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'bind') {
  24183. // bail on non-attr bindings
  24184. if (p.arg &&
  24185. (p.arg.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */ ||
  24186. (p.arg.isStatic && !isStringifiableAttr(p.arg.content, node.ns)))) {
  24187. return bail();
  24188. }
  24189. if (p.exp &&
  24190. (p.exp.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */ ||
  24191. p.exp.constType < 3 /* ConstantTypes.CAN_STRINGIFY */)) {
  24192. return bail();
  24193. }
  24194. }
  24195. }
  24196. for (let i = 0; i < node.children.length; i++) {
  24197. nc++;
  24198. const child = node.children[i];
  24199. if (child.type === 1 /* NodeTypes.ELEMENT */) {
  24200. if (child.props.length > 0) {
  24201. ec++;
  24202. }
  24203. walk(child);
  24204. if (bailed) {
  24205. return false;
  24206. }
  24207. }
  24208. }
  24209. return true;
  24210. }
  24211. return walk(node) ? [nc, ec] : false;
  24212. }
  24213. function stringifyNode(node, context) {
  24214. if (isString(node)) {
  24215. return node;
  24216. }
  24217. if (isSymbol(node)) {
  24218. return ``;
  24219. }
  24220. switch (node.type) {
  24221. case 1 /* NodeTypes.ELEMENT */:
  24222. return stringifyElement(node, context);
  24223. case 2 /* NodeTypes.TEXT */:
  24224. return escapeHtml(node.content);
  24225. case 3 /* NodeTypes.COMMENT */:
  24226. return `<!--${escapeHtml(node.content)}-->`;
  24227. case 5 /* NodeTypes.INTERPOLATION */:
  24228. return escapeHtml(toDisplayString(evaluateConstant(node.content)));
  24229. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  24230. return escapeHtml(evaluateConstant(node));
  24231. case 12 /* NodeTypes.TEXT_CALL */:
  24232. return stringifyNode(node.content, context);
  24233. default:
  24234. // static trees will not contain if/for nodes
  24235. return '';
  24236. }
  24237. }
  24238. function stringifyElement(node, context) {
  24239. let res = `<${node.tag}`;
  24240. let innerHTML = '';
  24241. for (let i = 0; i < node.props.length; i++) {
  24242. const p = node.props[i];
  24243. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  24244. res += ` ${p.name}`;
  24245. if (p.value) {
  24246. res += `="${escapeHtml(p.value.content)}"`;
  24247. }
  24248. }
  24249. else if (p.type === 7 /* NodeTypes.DIRECTIVE */) {
  24250. if (p.name === 'bind') {
  24251. const exp = p.exp;
  24252. if (exp.content[0] === '_') {
  24253. // internally generated string constant references
  24254. // e.g. imported URL strings via compiler-sfc transformAssetUrl plugin
  24255. res += ` ${p.arg.content}="__VUE_EXP_START__${exp.content}__VUE_EXP_END__"`;
  24256. continue;
  24257. }
  24258. // #6568
  24259. if (isBooleanAttr(p.arg.content) &&
  24260. exp.content === 'false') {
  24261. continue;
  24262. }
  24263. // constant v-bind, e.g. :foo="1"
  24264. let evaluated = evaluateConstant(exp);
  24265. if (evaluated != null) {
  24266. const arg = p.arg && p.arg.content;
  24267. if (arg === 'class') {
  24268. evaluated = normalizeClass(evaluated);
  24269. }
  24270. else if (arg === 'style') {
  24271. evaluated = stringifyStyle(normalizeStyle(evaluated));
  24272. }
  24273. res += ` ${p.arg.content}="${escapeHtml(evaluated)}"`;
  24274. }
  24275. }
  24276. else if (p.name === 'html') {
  24277. // #5439 v-html with constant value
  24278. // not sure why would anyone do this but it can happen
  24279. innerHTML = evaluateConstant(p.exp);
  24280. }
  24281. else if (p.name === 'text') {
  24282. innerHTML = escapeHtml(toDisplayString(evaluateConstant(p.exp)));
  24283. }
  24284. }
  24285. }
  24286. if (context.scopeId) {
  24287. res += ` ${context.scopeId}`;
  24288. }
  24289. res += `>`;
  24290. if (innerHTML) {
  24291. res += innerHTML;
  24292. }
  24293. else {
  24294. for (let i = 0; i < node.children.length; i++) {
  24295. res += stringifyNode(node.children[i], context);
  24296. }
  24297. }
  24298. if (!isVoidTag(node.tag)) {
  24299. res += `</${node.tag}>`;
  24300. }
  24301. return res;
  24302. }
  24303. // __UNSAFE__
  24304. // Reason: eval.
  24305. // It's technically safe to eval because only constant expressions are possible
  24306. // here, e.g. `{{ 1 }}` or `{{ 'foo' }}`
  24307. // in addition, constant exps bail on presence of parens so you can't even
  24308. // run JSFuck in here. But we mark it unsafe for security review purposes.
  24309. // (see compiler-core/src/transforms/transformExpression)
  24310. function evaluateConstant(exp) {
  24311. if (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  24312. return new Function(`return ${exp.content}`)();
  24313. }
  24314. else {
  24315. // compound
  24316. let res = ``;
  24317. exp.children.forEach(c => {
  24318. if (isString(c) || isSymbol(c)) {
  24319. return;
  24320. }
  24321. if (c.type === 2 /* NodeTypes.TEXT */) {
  24322. res += c.content;
  24323. }
  24324. else if (c.type === 5 /* NodeTypes.INTERPOLATION */) {
  24325. res += toDisplayString(evaluateConstant(c.content));
  24326. }
  24327. else {
  24328. res += evaluateConstant(c);
  24329. }
  24330. });
  24331. return res;
  24332. }
  24333. }
  24334. const ignoreSideEffectTags = (node, context) => {
  24335. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  24336. node.tagType === 0 /* ElementTypes.ELEMENT */ &&
  24337. (node.tag === 'script' || node.tag === 'style')) {
  24338. context.onError(createDOMCompilerError(61 /* DOMErrorCodes.X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
  24339. context.removeNode();
  24340. }
  24341. };
  24342. const DOMNodeTransforms = [
  24343. transformStyle,
  24344. ...([transformTransition] )
  24345. ];
  24346. const DOMDirectiveTransforms = {
  24347. cloak: noopDirectiveTransform,
  24348. html: transformVHtml,
  24349. text: transformVText,
  24350. model: transformModel$1,
  24351. on: transformOn$1,
  24352. show: transformShow
  24353. };
  24354. function compile(template, options = {}) {
  24355. return baseCompile(template, extend({}, parserOptions, options, {
  24356. nodeTransforms: [
  24357. // ignore <script> and <tag>
  24358. // this is not put inside DOMNodeTransforms because that list is used
  24359. // by compiler-ssr to generate vnode fallback branches
  24360. ignoreSideEffectTags,
  24361. ...DOMNodeTransforms,
  24362. ...(options.nodeTransforms || [])
  24363. ],
  24364. directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
  24365. transformHoist: stringifyStatic
  24366. }));
  24367. }
  24368. function parse$1(template, options = {}) {
  24369. return baseParse(template, extend({}, parserOptions, options));
  24370. }
  24371. var CompilerDOM = /*#__PURE__*/Object.freeze({
  24372. __proto__: null,
  24373. parserOptions: parserOptions,
  24374. DOMNodeTransforms: DOMNodeTransforms,
  24375. DOMDirectiveTransforms: DOMDirectiveTransforms,
  24376. compile: compile,
  24377. parse: parse$1,
  24378. transformStyle: transformStyle,
  24379. createDOMCompilerError: createDOMCompilerError,
  24380. V_MODEL_RADIO: V_MODEL_RADIO,
  24381. V_MODEL_CHECKBOX: V_MODEL_CHECKBOX,
  24382. V_MODEL_TEXT: V_MODEL_TEXT,
  24383. V_MODEL_SELECT: V_MODEL_SELECT,
  24384. V_MODEL_DYNAMIC: V_MODEL_DYNAMIC,
  24385. V_ON_WITH_MODIFIERS: V_ON_WITH_MODIFIERS,
  24386. V_ON_WITH_KEYS: V_ON_WITH_KEYS,
  24387. V_SHOW: V_SHOW,
  24388. TRANSITION: TRANSITION,
  24389. TRANSITION_GROUP: TRANSITION_GROUP,
  24390. baseCompile: baseCompile,
  24391. baseParse: baseParse,
  24392. transform: transform,
  24393. createTransformContext: createTransformContext,
  24394. traverseNode: traverseNode,
  24395. createStructuralDirectiveTransform: createStructuralDirectiveTransform,
  24396. generate: generate,
  24397. createCompilerError: createCompilerError,
  24398. getBaseTransformPreset: getBaseTransformPreset,
  24399. transformModel: transformModel,
  24400. transformOn: transformOn,
  24401. transformBind: transformBind,
  24402. noopDirectiveTransform: noopDirectiveTransform,
  24403. processIf: processIf,
  24404. processFor: processFor,
  24405. createForLoopParams: createForLoopParams,
  24406. transformExpression: transformExpression,
  24407. processExpression: processExpression,
  24408. stringifyExpression: stringifyExpression,
  24409. buildSlots: buildSlots,
  24410. trackVForSlotScopes: trackVForSlotScopes,
  24411. trackSlotScopes: trackSlotScopes,
  24412. transformElement: transformElement,
  24413. resolveComponentType: resolveComponentType,
  24414. buildProps: buildProps,
  24415. buildDirectiveArgs: buildDirectiveArgs,
  24416. processSlotOutlet: processSlotOutlet,
  24417. getConstantType: getConstantType,
  24418. generateCodeFrame: generateCodeFrame,
  24419. checkCompatEnabled: checkCompatEnabled,
  24420. warnDeprecation: warnDeprecation,
  24421. locStub: locStub,
  24422. createRoot: createRoot,
  24423. createVNodeCall: createVNodeCall,
  24424. createArrayExpression: createArrayExpression,
  24425. createObjectExpression: createObjectExpression,
  24426. createObjectProperty: createObjectProperty,
  24427. createSimpleExpression: createSimpleExpression,
  24428. createInterpolation: createInterpolation,
  24429. createCompoundExpression: createCompoundExpression,
  24430. createCallExpression: createCallExpression,
  24431. createFunctionExpression: createFunctionExpression,
  24432. createConditionalExpression: createConditionalExpression,
  24433. createCacheExpression: createCacheExpression,
  24434. createBlockStatement: createBlockStatement,
  24435. createTemplateLiteral: createTemplateLiteral,
  24436. createIfStatement: createIfStatement,
  24437. createAssignmentExpression: createAssignmentExpression,
  24438. createSequenceExpression: createSequenceExpression,
  24439. createReturnStatement: createReturnStatement,
  24440. isStaticExp: isStaticExp,
  24441. isBuiltInType: isBuiltInType,
  24442. isCoreComponent: isCoreComponent,
  24443. isSimpleIdentifier: isSimpleIdentifier,
  24444. isMemberExpressionBrowser: isMemberExpressionBrowser,
  24445. isMemberExpressionNode: isMemberExpressionNode,
  24446. isMemberExpression: isMemberExpression,
  24447. getInnerRange: getInnerRange,
  24448. advancePositionWithClone: advancePositionWithClone,
  24449. advancePositionWithMutation: advancePositionWithMutation,
  24450. assert: assert$1,
  24451. findDir: findDir,
  24452. findProp: findProp,
  24453. isStaticArgOf: isStaticArgOf,
  24454. hasDynamicKeyVBind: hasDynamicKeyVBind,
  24455. isText: isText,
  24456. isVSlot: isVSlot,
  24457. isTemplateNode: isTemplateNode,
  24458. isSlotOutlet: isSlotOutlet,
  24459. getVNodeHelper: getVNodeHelper,
  24460. getVNodeBlockHelper: getVNodeBlockHelper,
  24461. injectProp: injectProp,
  24462. toValidAssetId: toValidAssetId,
  24463. hasScopeRef: hasScopeRef,
  24464. getMemoedVNodeCall: getMemoedVNodeCall,
  24465. makeBlock: makeBlock,
  24466. walkIdentifiers: walkIdentifiers,
  24467. isReferencedIdentifier: isReferencedIdentifier,
  24468. isInDestructureAssignment: isInDestructureAssignment,
  24469. walkFunctionParams: walkFunctionParams,
  24470. walkBlockDeclarations: walkBlockDeclarations,
  24471. extractIdentifiers: extractIdentifiers,
  24472. isFunctionType: isFunctionType,
  24473. isStaticProperty: isStaticProperty,
  24474. isStaticPropertyKey: isStaticPropertyKey,
  24475. FRAGMENT: FRAGMENT,
  24476. TELEPORT: TELEPORT,
  24477. SUSPENSE: SUSPENSE,
  24478. KEEP_ALIVE: KEEP_ALIVE,
  24479. BASE_TRANSITION: BASE_TRANSITION,
  24480. OPEN_BLOCK: OPEN_BLOCK,
  24481. CREATE_BLOCK: CREATE_BLOCK,
  24482. CREATE_ELEMENT_BLOCK: CREATE_ELEMENT_BLOCK,
  24483. CREATE_VNODE: CREATE_VNODE,
  24484. CREATE_ELEMENT_VNODE: CREATE_ELEMENT_VNODE,
  24485. CREATE_COMMENT: CREATE_COMMENT,
  24486. CREATE_TEXT: CREATE_TEXT,
  24487. CREATE_STATIC: CREATE_STATIC,
  24488. RESOLVE_COMPONENT: RESOLVE_COMPONENT,
  24489. RESOLVE_DYNAMIC_COMPONENT: RESOLVE_DYNAMIC_COMPONENT,
  24490. RESOLVE_DIRECTIVE: RESOLVE_DIRECTIVE,
  24491. RESOLVE_FILTER: RESOLVE_FILTER,
  24492. WITH_DIRECTIVES: WITH_DIRECTIVES,
  24493. RENDER_LIST: RENDER_LIST,
  24494. RENDER_SLOT: RENDER_SLOT,
  24495. CREATE_SLOTS: CREATE_SLOTS,
  24496. TO_DISPLAY_STRING: TO_DISPLAY_STRING,
  24497. MERGE_PROPS: MERGE_PROPS,
  24498. NORMALIZE_CLASS: NORMALIZE_CLASS,
  24499. NORMALIZE_STYLE: NORMALIZE_STYLE,
  24500. NORMALIZE_PROPS: NORMALIZE_PROPS,
  24501. GUARD_REACTIVE_PROPS: GUARD_REACTIVE_PROPS,
  24502. TO_HANDLERS: TO_HANDLERS,
  24503. CAMELIZE: CAMELIZE,
  24504. CAPITALIZE: CAPITALIZE,
  24505. TO_HANDLER_KEY: TO_HANDLER_KEY,
  24506. SET_BLOCK_TRACKING: SET_BLOCK_TRACKING,
  24507. PUSH_SCOPE_ID: PUSH_SCOPE_ID,
  24508. POP_SCOPE_ID: POP_SCOPE_ID,
  24509. WITH_CTX: WITH_CTX,
  24510. UNREF: UNREF,
  24511. IS_REF: IS_REF,
  24512. WITH_MEMO: WITH_MEMO,
  24513. IS_MEMO_SAME: IS_MEMO_SAME,
  24514. helperNameMap: helperNameMap,
  24515. registerRuntimeHelpers: registerRuntimeHelpers
  24516. });
  24517. function pad (hash, len) {
  24518. while (hash.length < len) {
  24519. hash = '0' + hash;
  24520. }
  24521. return hash;
  24522. }
  24523. function fold (hash, text) {
  24524. var i;
  24525. var chr;
  24526. var len;
  24527. if (text.length === 0) {
  24528. return hash;
  24529. }
  24530. for (i = 0, len = text.length; i < len; i++) {
  24531. chr = text.charCodeAt(i);
  24532. hash = ((hash << 5) - hash) + chr;
  24533. hash |= 0;
  24534. }
  24535. return hash < 0 ? hash * -2 : hash;
  24536. }
  24537. function foldObject (hash, o, seen) {
  24538. return Object.keys(o).sort().reduce(foldKey, hash);
  24539. function foldKey (hash, key) {
  24540. return foldValue(hash, o[key], key, seen);
  24541. }
  24542. }
  24543. function foldValue (input, value, key, seen) {
  24544. var hash = fold(fold(fold(input, key), toString(value)), typeof value);
  24545. if (value === null) {
  24546. return fold(hash, 'null');
  24547. }
  24548. if (value === undefined) {
  24549. return fold(hash, 'undefined');
  24550. }
  24551. if (typeof value === 'object' || typeof value === 'function') {
  24552. if (seen.indexOf(value) !== -1) {
  24553. return fold(hash, '[Circular]' + key);
  24554. }
  24555. seen.push(value);
  24556. var objHash = foldObject(hash, value, seen);
  24557. if (!('valueOf' in value) || typeof value.valueOf !== 'function') {
  24558. return objHash;
  24559. }
  24560. try {
  24561. return fold(objHash, String(value.valueOf()))
  24562. } catch (err) {
  24563. return fold(objHash, '[valueOf exception]' + (err.stack || err.message))
  24564. }
  24565. }
  24566. return fold(hash, value.toString());
  24567. }
  24568. function toString (o) {
  24569. return Object.prototype.toString.call(o);
  24570. }
  24571. function sum (o) {
  24572. return pad(foldValue(0, o, '', []).toString(16), 8);
  24573. }
  24574. var hashSum = sum;
  24575. const CSS_VARS_HELPER = `useCssVars`;
  24576. function genCssVarsFromList(vars, id, isProd, isSSR = false) {
  24577. return `{\n ${vars
  24578. .map(key => `"${isSSR ? `--` : ``}${genVarName(id, key, isProd)}": (${key})`)
  24579. .join(',\n ')}\n}`;
  24580. }
  24581. function genVarName(id, raw, isProd) {
  24582. if (isProd) {
  24583. return hashSum(id + raw);
  24584. }
  24585. else {
  24586. // escape ASCII Punctuation & Symbols
  24587. return `${id}-${raw.replace(/[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/g, s => `\\${s}`)}`;
  24588. }
  24589. }
  24590. function normalizeExpression(exp) {
  24591. exp = exp.trim();
  24592. if ((exp[0] === `'` && exp[exp.length - 1] === `'`) ||
  24593. (exp[0] === `"` && exp[exp.length - 1] === `"`)) {
  24594. return exp.slice(1, -1);
  24595. }
  24596. return exp;
  24597. }
  24598. const vBindRE = /v-bind\s*\(/g;
  24599. function parseCssVars(sfc) {
  24600. const vars = [];
  24601. sfc.styles.forEach(style => {
  24602. let match;
  24603. // ignore v-bind() in comments /* ... */
  24604. const content = style.content.replace(/\/\*([\s\S]*?)\*\//g, '');
  24605. while ((match = vBindRE.exec(content))) {
  24606. const start = match.index + match[0].length;
  24607. const end = lexBinding(content, start);
  24608. if (end !== null) {
  24609. const variable = normalizeExpression(content.slice(start, end));
  24610. if (!vars.includes(variable)) {
  24611. vars.push(variable);
  24612. }
  24613. }
  24614. }
  24615. });
  24616. return vars;
  24617. }
  24618. function lexBinding(content, start) {
  24619. let state = 0 /* LexerState.inParens */;
  24620. let parenDepth = 0;
  24621. for (let i = start; i < content.length; i++) {
  24622. const char = content.charAt(i);
  24623. switch (state) {
  24624. case 0 /* LexerState.inParens */:
  24625. if (char === `'`) {
  24626. state = 1 /* LexerState.inSingleQuoteString */;
  24627. }
  24628. else if (char === `"`) {
  24629. state = 2 /* LexerState.inDoubleQuoteString */;
  24630. }
  24631. else if (char === `(`) {
  24632. parenDepth++;
  24633. }
  24634. else if (char === `)`) {
  24635. if (parenDepth > 0) {
  24636. parenDepth--;
  24637. }
  24638. else {
  24639. return i;
  24640. }
  24641. }
  24642. break;
  24643. case 1 /* LexerState.inSingleQuoteString */:
  24644. if (char === `'`) {
  24645. state = 0 /* LexerState.inParens */;
  24646. }
  24647. break;
  24648. case 2 /* LexerState.inDoubleQuoteString */:
  24649. if (char === `"`) {
  24650. state = 0 /* LexerState.inParens */;
  24651. }
  24652. break;
  24653. }
  24654. }
  24655. return null;
  24656. }
  24657. const cssVarsPlugin = opts => {
  24658. const { id, isProd } = opts;
  24659. return {
  24660. postcssPlugin: 'vue-sfc-vars',
  24661. Declaration(decl) {
  24662. // rewrite CSS variables
  24663. const value = decl.value;
  24664. if (vBindRE.test(value)) {
  24665. vBindRE.lastIndex = 0;
  24666. let transformed = '';
  24667. let lastIndex = 0;
  24668. let match;
  24669. while ((match = vBindRE.exec(value))) {
  24670. const start = match.index + match[0].length;
  24671. const end = lexBinding(value, start);
  24672. if (end !== null) {
  24673. const variable = normalizeExpression(value.slice(start, end));
  24674. transformed +=
  24675. value.slice(lastIndex, match.index) +
  24676. `var(--${genVarName(id, variable, isProd)})`;
  24677. lastIndex = end + 1;
  24678. }
  24679. }
  24680. decl.value = transformed + value.slice(lastIndex);
  24681. }
  24682. }
  24683. };
  24684. };
  24685. cssVarsPlugin.postcss = true;
  24686. function genCssVarsCode(vars, bindings, id, isProd) {
  24687. const varsExp = genCssVarsFromList(vars, id, isProd);
  24688. const exp = createSimpleExpression(varsExp, false);
  24689. const context = createTransformContext(createRoot([]), {
  24690. prefixIdentifiers: true,
  24691. inline: true,
  24692. bindingMetadata: bindings.__isScriptSetup === false ? undefined : bindings
  24693. });
  24694. const transformed = processExpression(exp, context);
  24695. const transformedString = transformed.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */
  24696. ? transformed.content
  24697. : transformed.children
  24698. .map(c => {
  24699. return typeof c === 'string'
  24700. ? c
  24701. : c.content;
  24702. })
  24703. .join('');
  24704. return `_${CSS_VARS_HELPER}(_ctx => (${transformedString}))`;
  24705. }
  24706. // <script setup> already gets the calls injected as part of the transform
  24707. // this is only for single normal <script>
  24708. function genNormalScriptCssVarsCode(cssVars, bindings, id, isProd) {
  24709. return (`\nimport { ${CSS_VARS_HELPER} as _${CSS_VARS_HELPER} } from 'vue'\n` +
  24710. `const __injectCSSVars__ = () => {\n${genCssVarsCode(cssVars, bindings, id, isProd)}}\n` +
  24711. `const __setup__ = __default__.setup\n` +
  24712. `__default__.setup = __setup__\n` +
  24713. ` ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) }\n` +
  24714. ` : __injectCSSVars__\n`);
  24715. }
  24716. function createCache(size = 500) {
  24717. return new Map()
  24718. ;
  24719. }
  24720. var global = (typeof global !== "undefined" ? global :
  24721. typeof self !== "undefined" ? self :
  24722. typeof window !== "undefined" ? window : {});
  24723. var lookup = [];
  24724. var revLookup = [];
  24725. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
  24726. var inited = false;
  24727. function init () {
  24728. inited = true;
  24729. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  24730. for (var i = 0, len = code.length; i < len; ++i) {
  24731. lookup[i] = code[i];
  24732. revLookup[code.charCodeAt(i)] = i;
  24733. }
  24734. revLookup['-'.charCodeAt(0)] = 62;
  24735. revLookup['_'.charCodeAt(0)] = 63;
  24736. }
  24737. function toByteArray (b64) {
  24738. if (!inited) {
  24739. init();
  24740. }
  24741. var i, j, l, tmp, placeHolders, arr;
  24742. var len = b64.length;
  24743. if (len % 4 > 0) {
  24744. throw new Error('Invalid string. Length must be a multiple of 4')
  24745. }
  24746. // the number of equal signs (place holders)
  24747. // if there are two placeholders, than the two characters before it
  24748. // represent one byte
  24749. // if there is only one, then the three characters before it represent 2 bytes
  24750. // this is just a cheap hack to not do indexOf twice
  24751. placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;
  24752. // base64 is 4/3 + up to two characters of the original data
  24753. arr = new Arr(len * 3 / 4 - placeHolders);
  24754. // if there are placeholders, only get up to the last complete 4 chars
  24755. l = placeHolders > 0 ? len - 4 : len;
  24756. var L = 0;
  24757. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  24758. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)];
  24759. arr[L++] = (tmp >> 16) & 0xFF;
  24760. arr[L++] = (tmp >> 8) & 0xFF;
  24761. arr[L++] = tmp & 0xFF;
  24762. }
  24763. if (placeHolders === 2) {
  24764. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);
  24765. arr[L++] = tmp & 0xFF;
  24766. } else if (placeHolders === 1) {
  24767. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2);
  24768. arr[L++] = (tmp >> 8) & 0xFF;
  24769. arr[L++] = tmp & 0xFF;
  24770. }
  24771. return arr
  24772. }
  24773. function tripletToBase64 (num) {
  24774. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  24775. }
  24776. function encodeChunk (uint8, start, end) {
  24777. var tmp;
  24778. var output = [];
  24779. for (var i = start; i < end; i += 3) {
  24780. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
  24781. output.push(tripletToBase64(tmp));
  24782. }
  24783. return output.join('')
  24784. }
  24785. function fromByteArray (uint8) {
  24786. if (!inited) {
  24787. init();
  24788. }
  24789. var tmp;
  24790. var len = uint8.length;
  24791. var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
  24792. var output = '';
  24793. var parts = [];
  24794. var maxChunkLength = 16383; // must be multiple of 3
  24795. // go through the array every three bytes, we'll deal with trailing stuff later
  24796. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  24797. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));
  24798. }
  24799. // pad the end with zeros, but make sure to not forget the extra bytes
  24800. if (extraBytes === 1) {
  24801. tmp = uint8[len - 1];
  24802. output += lookup[tmp >> 2];
  24803. output += lookup[(tmp << 4) & 0x3F];
  24804. output += '==';
  24805. } else if (extraBytes === 2) {
  24806. tmp = (uint8[len - 2] << 8) + (uint8[len - 1]);
  24807. output += lookup[tmp >> 10];
  24808. output += lookup[(tmp >> 4) & 0x3F];
  24809. output += lookup[(tmp << 2) & 0x3F];
  24810. output += '=';
  24811. }
  24812. parts.push(output);
  24813. return parts.join('')
  24814. }
  24815. function read (buffer, offset, isLE, mLen, nBytes) {
  24816. var e, m;
  24817. var eLen = nBytes * 8 - mLen - 1;
  24818. var eMax = (1 << eLen) - 1;
  24819. var eBias = eMax >> 1;
  24820. var nBits = -7;
  24821. var i = isLE ? (nBytes - 1) : 0;
  24822. var d = isLE ? -1 : 1;
  24823. var s = buffer[offset + i];
  24824. i += d;
  24825. e = s & ((1 << (-nBits)) - 1);
  24826. s >>= (-nBits);
  24827. nBits += eLen;
  24828. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  24829. m = e & ((1 << (-nBits)) - 1);
  24830. e >>= (-nBits);
  24831. nBits += mLen;
  24832. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  24833. if (e === 0) {
  24834. e = 1 - eBias;
  24835. } else if (e === eMax) {
  24836. return m ? NaN : ((s ? -1 : 1) * Infinity)
  24837. } else {
  24838. m = m + Math.pow(2, mLen);
  24839. e = e - eBias;
  24840. }
  24841. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  24842. }
  24843. function write (buffer, value, offset, isLE, mLen, nBytes) {
  24844. var e, m, c;
  24845. var eLen = nBytes * 8 - mLen - 1;
  24846. var eMax = (1 << eLen) - 1;
  24847. var eBias = eMax >> 1;
  24848. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);
  24849. var i = isLE ? 0 : (nBytes - 1);
  24850. var d = isLE ? 1 : -1;
  24851. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
  24852. value = Math.abs(value);
  24853. if (isNaN(value) || value === Infinity) {
  24854. m = isNaN(value) ? 1 : 0;
  24855. e = eMax;
  24856. } else {
  24857. e = Math.floor(Math.log(value) / Math.LN2);
  24858. if (value * (c = Math.pow(2, -e)) < 1) {
  24859. e--;
  24860. c *= 2;
  24861. }
  24862. if (e + eBias >= 1) {
  24863. value += rt / c;
  24864. } else {
  24865. value += rt * Math.pow(2, 1 - eBias);
  24866. }
  24867. if (value * c >= 2) {
  24868. e++;
  24869. c /= 2;
  24870. }
  24871. if (e + eBias >= eMax) {
  24872. m = 0;
  24873. e = eMax;
  24874. } else if (e + eBias >= 1) {
  24875. m = (value * c - 1) * Math.pow(2, mLen);
  24876. e = e + eBias;
  24877. } else {
  24878. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  24879. e = 0;
  24880. }
  24881. }
  24882. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  24883. e = (e << mLen) | m;
  24884. eLen += mLen;
  24885. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  24886. buffer[offset + i - d] |= s * 128;
  24887. }
  24888. var toString$1 = {}.toString;
  24889. var isArray$1 = Array.isArray || function (arr) {
  24890. return toString$1.call(arr) == '[object Array]';
  24891. };
  24892. /*!
  24893. * The buffer module from node.js, for the browser.
  24894. *
  24895. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  24896. * @license MIT
  24897. */
  24898. var INSPECT_MAX_BYTES = 50;
  24899. /**
  24900. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  24901. * === true Use Uint8Array implementation (fastest)
  24902. * === false Use Object implementation (most compatible, even IE6)
  24903. *
  24904. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  24905. * Opera 11.6+, iOS 4.2+.
  24906. *
  24907. * Due to various browser bugs, sometimes the Object implementation will be used even
  24908. * when the browser supports typed arrays.
  24909. *
  24910. * Note:
  24911. *
  24912. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  24913. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  24914. *
  24915. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  24916. *
  24917. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  24918. * incorrect length in some situations.
  24919. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  24920. * get the Object implementation, which is slower but behaves correctly.
  24921. */
  24922. Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  24923. ? global.TYPED_ARRAY_SUPPORT
  24924. : true;
  24925. function kMaxLength () {
  24926. return Buffer.TYPED_ARRAY_SUPPORT
  24927. ? 0x7fffffff
  24928. : 0x3fffffff
  24929. }
  24930. function createBuffer (that, length) {
  24931. if (kMaxLength() < length) {
  24932. throw new RangeError('Invalid typed array length')
  24933. }
  24934. if (Buffer.TYPED_ARRAY_SUPPORT) {
  24935. // Return an augmented `Uint8Array` instance, for best performance
  24936. that = new Uint8Array(length);
  24937. that.__proto__ = Buffer.prototype;
  24938. } else {
  24939. // Fallback: Return an object instance of the Buffer class
  24940. if (that === null) {
  24941. that = new Buffer(length);
  24942. }
  24943. that.length = length;
  24944. }
  24945. return that
  24946. }
  24947. /**
  24948. * The Buffer constructor returns instances of `Uint8Array` that have their
  24949. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  24950. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  24951. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  24952. * returns a single octet.
  24953. *
  24954. * The `Uint8Array` prototype remains unmodified.
  24955. */
  24956. function Buffer (arg, encodingOrOffset, length) {
  24957. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  24958. return new Buffer(arg, encodingOrOffset, length)
  24959. }
  24960. // Common case.
  24961. if (typeof arg === 'number') {
  24962. if (typeof encodingOrOffset === 'string') {
  24963. throw new Error(
  24964. 'If encoding is specified then the first argument must be a string'
  24965. )
  24966. }
  24967. return allocUnsafe(this, arg)
  24968. }
  24969. return from(this, arg, encodingOrOffset, length)
  24970. }
  24971. Buffer.poolSize = 8192; // not used by this implementation
  24972. // TODO: Legacy, not needed anymore. Remove in next major version.
  24973. Buffer._augment = function (arr) {
  24974. arr.__proto__ = Buffer.prototype;
  24975. return arr
  24976. };
  24977. function from (that, value, encodingOrOffset, length) {
  24978. if (typeof value === 'number') {
  24979. throw new TypeError('"value" argument must not be a number')
  24980. }
  24981. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  24982. return fromArrayBuffer(that, value, encodingOrOffset, length)
  24983. }
  24984. if (typeof value === 'string') {
  24985. return fromString(that, value, encodingOrOffset)
  24986. }
  24987. return fromObject(that, value)
  24988. }
  24989. /**
  24990. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  24991. * if value is a number.
  24992. * Buffer.from(str[, encoding])
  24993. * Buffer.from(array)
  24994. * Buffer.from(buffer)
  24995. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  24996. **/
  24997. Buffer.from = function (value, encodingOrOffset, length) {
  24998. return from(null, value, encodingOrOffset, length)
  24999. };
  25000. if (Buffer.TYPED_ARRAY_SUPPORT) {
  25001. Buffer.prototype.__proto__ = Uint8Array.prototype;
  25002. Buffer.__proto__ = Uint8Array;
  25003. }
  25004. function assertSize (size) {
  25005. if (typeof size !== 'number') {
  25006. throw new TypeError('"size" argument must be a number')
  25007. } else if (size < 0) {
  25008. throw new RangeError('"size" argument must not be negative')
  25009. }
  25010. }
  25011. function alloc (that, size, fill, encoding) {
  25012. assertSize(size);
  25013. if (size <= 0) {
  25014. return createBuffer(that, size)
  25015. }
  25016. if (fill !== undefined) {
  25017. // Only pay attention to encoding if it's a string. This
  25018. // prevents accidentally sending in a number that would
  25019. // be interpretted as a start offset.
  25020. return typeof encoding === 'string'
  25021. ? createBuffer(that, size).fill(fill, encoding)
  25022. : createBuffer(that, size).fill(fill)
  25023. }
  25024. return createBuffer(that, size)
  25025. }
  25026. /**
  25027. * Creates a new filled Buffer instance.
  25028. * alloc(size[, fill[, encoding]])
  25029. **/
  25030. Buffer.alloc = function (size, fill, encoding) {
  25031. return alloc(null, size, fill, encoding)
  25032. };
  25033. function allocUnsafe (that, size) {
  25034. assertSize(size);
  25035. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
  25036. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  25037. for (var i = 0; i < size; ++i) {
  25038. that[i] = 0;
  25039. }
  25040. }
  25041. return that
  25042. }
  25043. /**
  25044. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  25045. * */
  25046. Buffer.allocUnsafe = function (size) {
  25047. return allocUnsafe(null, size)
  25048. };
  25049. /**
  25050. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  25051. */
  25052. Buffer.allocUnsafeSlow = function (size) {
  25053. return allocUnsafe(null, size)
  25054. };
  25055. function fromString (that, string, encoding) {
  25056. if (typeof encoding !== 'string' || encoding === '') {
  25057. encoding = 'utf8';
  25058. }
  25059. if (!Buffer.isEncoding(encoding)) {
  25060. throw new TypeError('"encoding" must be a valid string encoding')
  25061. }
  25062. var length = byteLength(string, encoding) | 0;
  25063. that = createBuffer(that, length);
  25064. var actual = that.write(string, encoding);
  25065. if (actual !== length) {
  25066. // Writing a hex string, for example, that contains invalid characters will
  25067. // cause everything after the first invalid character to be ignored. (e.g.
  25068. // 'abxxcd' will be treated as 'ab')
  25069. that = that.slice(0, actual);
  25070. }
  25071. return that
  25072. }
  25073. function fromArrayLike (that, array) {
  25074. var length = array.length < 0 ? 0 : checked(array.length) | 0;
  25075. that = createBuffer(that, length);
  25076. for (var i = 0; i < length; i += 1) {
  25077. that[i] = array[i] & 255;
  25078. }
  25079. return that
  25080. }
  25081. function fromArrayBuffer (that, array, byteOffset, length) {
  25082. array.byteLength; // this throws if `array` is not a valid ArrayBuffer
  25083. if (byteOffset < 0 || array.byteLength < byteOffset) {
  25084. throw new RangeError('\'offset\' is out of bounds')
  25085. }
  25086. if (array.byteLength < byteOffset + (length || 0)) {
  25087. throw new RangeError('\'length\' is out of bounds')
  25088. }
  25089. if (byteOffset === undefined && length === undefined) {
  25090. array = new Uint8Array(array);
  25091. } else if (length === undefined) {
  25092. array = new Uint8Array(array, byteOffset);
  25093. } else {
  25094. array = new Uint8Array(array, byteOffset, length);
  25095. }
  25096. if (Buffer.TYPED_ARRAY_SUPPORT) {
  25097. // Return an augmented `Uint8Array` instance, for best performance
  25098. that = array;
  25099. that.__proto__ = Buffer.prototype;
  25100. } else {
  25101. // Fallback: Return an object instance of the Buffer class
  25102. that = fromArrayLike(that, array);
  25103. }
  25104. return that
  25105. }
  25106. function fromObject (that, obj) {
  25107. if (internalIsBuffer(obj)) {
  25108. var len = checked(obj.length) | 0;
  25109. that = createBuffer(that, len);
  25110. if (that.length === 0) {
  25111. return that
  25112. }
  25113. obj.copy(that, 0, 0, len);
  25114. return that
  25115. }
  25116. if (obj) {
  25117. if ((typeof ArrayBuffer !== 'undefined' &&
  25118. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  25119. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  25120. return createBuffer(that, 0)
  25121. }
  25122. return fromArrayLike(that, obj)
  25123. }
  25124. if (obj.type === 'Buffer' && isArray$1(obj.data)) {
  25125. return fromArrayLike(that, obj.data)
  25126. }
  25127. }
  25128. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  25129. }
  25130. function checked (length) {
  25131. // Note: cannot use `length < kMaxLength()` here because that fails when
  25132. // length is NaN (which is otherwise coerced to zero.)
  25133. if (length >= kMaxLength()) {
  25134. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  25135. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  25136. }
  25137. return length | 0
  25138. }
  25139. Buffer.isBuffer = isBuffer;
  25140. function internalIsBuffer (b) {
  25141. return !!(b != null && b._isBuffer)
  25142. }
  25143. Buffer.compare = function compare (a, b) {
  25144. if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
  25145. throw new TypeError('Arguments must be Buffers')
  25146. }
  25147. if (a === b) return 0
  25148. var x = a.length;
  25149. var y = b.length;
  25150. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  25151. if (a[i] !== b[i]) {
  25152. x = a[i];
  25153. y = b[i];
  25154. break
  25155. }
  25156. }
  25157. if (x < y) return -1
  25158. if (y < x) return 1
  25159. return 0
  25160. };
  25161. Buffer.isEncoding = function isEncoding (encoding) {
  25162. switch (String(encoding).toLowerCase()) {
  25163. case 'hex':
  25164. case 'utf8':
  25165. case 'utf-8':
  25166. case 'ascii':
  25167. case 'latin1':
  25168. case 'binary':
  25169. case 'base64':
  25170. case 'ucs2':
  25171. case 'ucs-2':
  25172. case 'utf16le':
  25173. case 'utf-16le':
  25174. return true
  25175. default:
  25176. return false
  25177. }
  25178. };
  25179. Buffer.concat = function concat (list, length) {
  25180. if (!isArray$1(list)) {
  25181. throw new TypeError('"list" argument must be an Array of Buffers')
  25182. }
  25183. if (list.length === 0) {
  25184. return Buffer.alloc(0)
  25185. }
  25186. var i;
  25187. if (length === undefined) {
  25188. length = 0;
  25189. for (i = 0; i < list.length; ++i) {
  25190. length += list[i].length;
  25191. }
  25192. }
  25193. var buffer = Buffer.allocUnsafe(length);
  25194. var pos = 0;
  25195. for (i = 0; i < list.length; ++i) {
  25196. var buf = list[i];
  25197. if (!internalIsBuffer(buf)) {
  25198. throw new TypeError('"list" argument must be an Array of Buffers')
  25199. }
  25200. buf.copy(buffer, pos);
  25201. pos += buf.length;
  25202. }
  25203. return buffer
  25204. };
  25205. function byteLength (string, encoding) {
  25206. if (internalIsBuffer(string)) {
  25207. return string.length
  25208. }
  25209. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  25210. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  25211. return string.byteLength
  25212. }
  25213. if (typeof string !== 'string') {
  25214. string = '' + string;
  25215. }
  25216. var len = string.length;
  25217. if (len === 0) return 0
  25218. // Use a for loop to avoid recursion
  25219. var loweredCase = false;
  25220. for (;;) {
  25221. switch (encoding) {
  25222. case 'ascii':
  25223. case 'latin1':
  25224. case 'binary':
  25225. return len
  25226. case 'utf8':
  25227. case 'utf-8':
  25228. case undefined:
  25229. return utf8ToBytes(string).length
  25230. case 'ucs2':
  25231. case 'ucs-2':
  25232. case 'utf16le':
  25233. case 'utf-16le':
  25234. return len * 2
  25235. case 'hex':
  25236. return len >>> 1
  25237. case 'base64':
  25238. return base64ToBytes(string).length
  25239. default:
  25240. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  25241. encoding = ('' + encoding).toLowerCase();
  25242. loweredCase = true;
  25243. }
  25244. }
  25245. }
  25246. Buffer.byteLength = byteLength;
  25247. function slowToString (encoding, start, end) {
  25248. var loweredCase = false;
  25249. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  25250. // property of a typed array.
  25251. // This behaves neither like String nor Uint8Array in that we set start/end
  25252. // to their upper/lower bounds if the value passed is out of range.
  25253. // undefined is handled specially as per ECMA-262 6th Edition,
  25254. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  25255. if (start === undefined || start < 0) {
  25256. start = 0;
  25257. }
  25258. // Return early if start > this.length. Done here to prevent potential uint32
  25259. // coercion fail below.
  25260. if (start > this.length) {
  25261. return ''
  25262. }
  25263. if (end === undefined || end > this.length) {
  25264. end = this.length;
  25265. }
  25266. if (end <= 0) {
  25267. return ''
  25268. }
  25269. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  25270. end >>>= 0;
  25271. start >>>= 0;
  25272. if (end <= start) {
  25273. return ''
  25274. }
  25275. if (!encoding) encoding = 'utf8';
  25276. while (true) {
  25277. switch (encoding) {
  25278. case 'hex':
  25279. return hexSlice(this, start, end)
  25280. case 'utf8':
  25281. case 'utf-8':
  25282. return utf8Slice(this, start, end)
  25283. case 'ascii':
  25284. return asciiSlice(this, start, end)
  25285. case 'latin1':
  25286. case 'binary':
  25287. return latin1Slice(this, start, end)
  25288. case 'base64':
  25289. return base64Slice(this, start, end)
  25290. case 'ucs2':
  25291. case 'ucs-2':
  25292. case 'utf16le':
  25293. case 'utf-16le':
  25294. return utf16leSlice(this, start, end)
  25295. default:
  25296. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  25297. encoding = (encoding + '').toLowerCase();
  25298. loweredCase = true;
  25299. }
  25300. }
  25301. }
  25302. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  25303. // Buffer instances.
  25304. Buffer.prototype._isBuffer = true;
  25305. function swap$1 (b, n, m) {
  25306. var i = b[n];
  25307. b[n] = b[m];
  25308. b[m] = i;
  25309. }
  25310. Buffer.prototype.swap16 = function swap16 () {
  25311. var len = this.length;
  25312. if (len % 2 !== 0) {
  25313. throw new RangeError('Buffer size must be a multiple of 16-bits')
  25314. }
  25315. for (var i = 0; i < len; i += 2) {
  25316. swap$1(this, i, i + 1);
  25317. }
  25318. return this
  25319. };
  25320. Buffer.prototype.swap32 = function swap32 () {
  25321. var len = this.length;
  25322. if (len % 4 !== 0) {
  25323. throw new RangeError('Buffer size must be a multiple of 32-bits')
  25324. }
  25325. for (var i = 0; i < len; i += 4) {
  25326. swap$1(this, i, i + 3);
  25327. swap$1(this, i + 1, i + 2);
  25328. }
  25329. return this
  25330. };
  25331. Buffer.prototype.swap64 = function swap64 () {
  25332. var len = this.length;
  25333. if (len % 8 !== 0) {
  25334. throw new RangeError('Buffer size must be a multiple of 64-bits')
  25335. }
  25336. for (var i = 0; i < len; i += 8) {
  25337. swap$1(this, i, i + 7);
  25338. swap$1(this, i + 1, i + 6);
  25339. swap$1(this, i + 2, i + 5);
  25340. swap$1(this, i + 3, i + 4);
  25341. }
  25342. return this
  25343. };
  25344. Buffer.prototype.toString = function toString () {
  25345. var length = this.length | 0;
  25346. if (length === 0) return ''
  25347. if (arguments.length === 0) return utf8Slice(this, 0, length)
  25348. return slowToString.apply(this, arguments)
  25349. };
  25350. Buffer.prototype.equals = function equals (b) {
  25351. if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')
  25352. if (this === b) return true
  25353. return Buffer.compare(this, b) === 0
  25354. };
  25355. Buffer.prototype.inspect = function inspect () {
  25356. var str = '';
  25357. var max = INSPECT_MAX_BYTES;
  25358. if (this.length > 0) {
  25359. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
  25360. if (this.length > max) str += ' ... ';
  25361. }
  25362. return '<Buffer ' + str + '>'
  25363. };
  25364. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  25365. if (!internalIsBuffer(target)) {
  25366. throw new TypeError('Argument must be a Buffer')
  25367. }
  25368. if (start === undefined) {
  25369. start = 0;
  25370. }
  25371. if (end === undefined) {
  25372. end = target ? target.length : 0;
  25373. }
  25374. if (thisStart === undefined) {
  25375. thisStart = 0;
  25376. }
  25377. if (thisEnd === undefined) {
  25378. thisEnd = this.length;
  25379. }
  25380. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  25381. throw new RangeError('out of range index')
  25382. }
  25383. if (thisStart >= thisEnd && start >= end) {
  25384. return 0
  25385. }
  25386. if (thisStart >= thisEnd) {
  25387. return -1
  25388. }
  25389. if (start >= end) {
  25390. return 1
  25391. }
  25392. start >>>= 0;
  25393. end >>>= 0;
  25394. thisStart >>>= 0;
  25395. thisEnd >>>= 0;
  25396. if (this === target) return 0
  25397. var x = thisEnd - thisStart;
  25398. var y = end - start;
  25399. var len = Math.min(x, y);
  25400. var thisCopy = this.slice(thisStart, thisEnd);
  25401. var targetCopy = target.slice(start, end);
  25402. for (var i = 0; i < len; ++i) {
  25403. if (thisCopy[i] !== targetCopy[i]) {
  25404. x = thisCopy[i];
  25405. y = targetCopy[i];
  25406. break
  25407. }
  25408. }
  25409. if (x < y) return -1
  25410. if (y < x) return 1
  25411. return 0
  25412. };
  25413. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  25414. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  25415. //
  25416. // Arguments:
  25417. // - buffer - a Buffer to search
  25418. // - val - a string, Buffer, or number
  25419. // - byteOffset - an index into `buffer`; will be clamped to an int32
  25420. // - encoding - an optional encoding, relevant is val is a string
  25421. // - dir - true for indexOf, false for lastIndexOf
  25422. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  25423. // Empty buffer means no match
  25424. if (buffer.length === 0) return -1
  25425. // Normalize byteOffset
  25426. if (typeof byteOffset === 'string') {
  25427. encoding = byteOffset;
  25428. byteOffset = 0;
  25429. } else if (byteOffset > 0x7fffffff) {
  25430. byteOffset = 0x7fffffff;
  25431. } else if (byteOffset < -0x80000000) {
  25432. byteOffset = -0x80000000;
  25433. }
  25434. byteOffset = +byteOffset; // Coerce to Number.
  25435. if (isNaN(byteOffset)) {
  25436. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  25437. byteOffset = dir ? 0 : (buffer.length - 1);
  25438. }
  25439. // Normalize byteOffset: negative offsets start from the end of the buffer
  25440. if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
  25441. if (byteOffset >= buffer.length) {
  25442. if (dir) return -1
  25443. else byteOffset = buffer.length - 1;
  25444. } else if (byteOffset < 0) {
  25445. if (dir) byteOffset = 0;
  25446. else return -1
  25447. }
  25448. // Normalize val
  25449. if (typeof val === 'string') {
  25450. val = Buffer.from(val, encoding);
  25451. }
  25452. // Finally, search either indexOf (if dir is true) or lastIndexOf
  25453. if (internalIsBuffer(val)) {
  25454. // Special case: looking for empty string/buffer always fails
  25455. if (val.length === 0) {
  25456. return -1
  25457. }
  25458. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  25459. } else if (typeof val === 'number') {
  25460. val = val & 0xFF; // Search for a byte value [0-255]
  25461. if (Buffer.TYPED_ARRAY_SUPPORT &&
  25462. typeof Uint8Array.prototype.indexOf === 'function') {
  25463. if (dir) {
  25464. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  25465. } else {
  25466. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  25467. }
  25468. }
  25469. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  25470. }
  25471. throw new TypeError('val must be string, number or Buffer')
  25472. }
  25473. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  25474. var indexSize = 1;
  25475. var arrLength = arr.length;
  25476. var valLength = val.length;
  25477. if (encoding !== undefined) {
  25478. encoding = String(encoding).toLowerCase();
  25479. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  25480. encoding === 'utf16le' || encoding === 'utf-16le') {
  25481. if (arr.length < 2 || val.length < 2) {
  25482. return -1
  25483. }
  25484. indexSize = 2;
  25485. arrLength /= 2;
  25486. valLength /= 2;
  25487. byteOffset /= 2;
  25488. }
  25489. }
  25490. function read (buf, i) {
  25491. if (indexSize === 1) {
  25492. return buf[i]
  25493. } else {
  25494. return buf.readUInt16BE(i * indexSize)
  25495. }
  25496. }
  25497. var i;
  25498. if (dir) {
  25499. var foundIndex = -1;
  25500. for (i = byteOffset; i < arrLength; i++) {
  25501. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  25502. if (foundIndex === -1) foundIndex = i;
  25503. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  25504. } else {
  25505. if (foundIndex !== -1) i -= i - foundIndex;
  25506. foundIndex = -1;
  25507. }
  25508. }
  25509. } else {
  25510. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
  25511. for (i = byteOffset; i >= 0; i--) {
  25512. var found = true;
  25513. for (var j = 0; j < valLength; j++) {
  25514. if (read(arr, i + j) !== read(val, j)) {
  25515. found = false;
  25516. break
  25517. }
  25518. }
  25519. if (found) return i
  25520. }
  25521. }
  25522. return -1
  25523. }
  25524. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  25525. return this.indexOf(val, byteOffset, encoding) !== -1
  25526. };
  25527. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  25528. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  25529. };
  25530. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  25531. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  25532. };
  25533. function hexWrite (buf, string, offset, length) {
  25534. offset = Number(offset) || 0;
  25535. var remaining = buf.length - offset;
  25536. if (!length) {
  25537. length = remaining;
  25538. } else {
  25539. length = Number(length);
  25540. if (length > remaining) {
  25541. length = remaining;
  25542. }
  25543. }
  25544. // must be an even number of digits
  25545. var strLen = string.length;
  25546. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  25547. if (length > strLen / 2) {
  25548. length = strLen / 2;
  25549. }
  25550. for (var i = 0; i < length; ++i) {
  25551. var parsed = parseInt(string.substr(i * 2, 2), 16);
  25552. if (isNaN(parsed)) return i
  25553. buf[offset + i] = parsed;
  25554. }
  25555. return i
  25556. }
  25557. function utf8Write (buf, string, offset, length) {
  25558. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  25559. }
  25560. function asciiWrite (buf, string, offset, length) {
  25561. return blitBuffer(asciiToBytes(string), buf, offset, length)
  25562. }
  25563. function latin1Write (buf, string, offset, length) {
  25564. return asciiWrite(buf, string, offset, length)
  25565. }
  25566. function base64Write (buf, string, offset, length) {
  25567. return blitBuffer(base64ToBytes(string), buf, offset, length)
  25568. }
  25569. function ucs2Write (buf, string, offset, length) {
  25570. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  25571. }
  25572. Buffer.prototype.write = function write (string, offset, length, encoding) {
  25573. // Buffer#write(string)
  25574. if (offset === undefined) {
  25575. encoding = 'utf8';
  25576. length = this.length;
  25577. offset = 0;
  25578. // Buffer#write(string, encoding)
  25579. } else if (length === undefined && typeof offset === 'string') {
  25580. encoding = offset;
  25581. length = this.length;
  25582. offset = 0;
  25583. // Buffer#write(string, offset[, length][, encoding])
  25584. } else if (isFinite(offset)) {
  25585. offset = offset | 0;
  25586. if (isFinite(length)) {
  25587. length = length | 0;
  25588. if (encoding === undefined) encoding = 'utf8';
  25589. } else {
  25590. encoding = length;
  25591. length = undefined;
  25592. }
  25593. // legacy write(string, encoding, offset, length) - remove in v0.13
  25594. } else {
  25595. throw new Error(
  25596. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  25597. )
  25598. }
  25599. var remaining = this.length - offset;
  25600. if (length === undefined || length > remaining) length = remaining;
  25601. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  25602. throw new RangeError('Attempt to write outside buffer bounds')
  25603. }
  25604. if (!encoding) encoding = 'utf8';
  25605. var loweredCase = false;
  25606. for (;;) {
  25607. switch (encoding) {
  25608. case 'hex':
  25609. return hexWrite(this, string, offset, length)
  25610. case 'utf8':
  25611. case 'utf-8':
  25612. return utf8Write(this, string, offset, length)
  25613. case 'ascii':
  25614. return asciiWrite(this, string, offset, length)
  25615. case 'latin1':
  25616. case 'binary':
  25617. return latin1Write(this, string, offset, length)
  25618. case 'base64':
  25619. // Warning: maxLength not taken into account in base64Write
  25620. return base64Write(this, string, offset, length)
  25621. case 'ucs2':
  25622. case 'ucs-2':
  25623. case 'utf16le':
  25624. case 'utf-16le':
  25625. return ucs2Write(this, string, offset, length)
  25626. default:
  25627. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  25628. encoding = ('' + encoding).toLowerCase();
  25629. loweredCase = true;
  25630. }
  25631. }
  25632. };
  25633. Buffer.prototype.toJSON = function toJSON () {
  25634. return {
  25635. type: 'Buffer',
  25636. data: Array.prototype.slice.call(this._arr || this, 0)
  25637. }
  25638. };
  25639. function base64Slice (buf, start, end) {
  25640. if (start === 0 && end === buf.length) {
  25641. return fromByteArray(buf)
  25642. } else {
  25643. return fromByteArray(buf.slice(start, end))
  25644. }
  25645. }
  25646. function utf8Slice (buf, start, end) {
  25647. end = Math.min(buf.length, end);
  25648. var res = [];
  25649. var i = start;
  25650. while (i < end) {
  25651. var firstByte = buf[i];
  25652. var codePoint = null;
  25653. var bytesPerSequence = (firstByte > 0xEF) ? 4
  25654. : (firstByte > 0xDF) ? 3
  25655. : (firstByte > 0xBF) ? 2
  25656. : 1;
  25657. if (i + bytesPerSequence <= end) {
  25658. var secondByte, thirdByte, fourthByte, tempCodePoint;
  25659. switch (bytesPerSequence) {
  25660. case 1:
  25661. if (firstByte < 0x80) {
  25662. codePoint = firstByte;
  25663. }
  25664. break
  25665. case 2:
  25666. secondByte = buf[i + 1];
  25667. if ((secondByte & 0xC0) === 0x80) {
  25668. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
  25669. if (tempCodePoint > 0x7F) {
  25670. codePoint = tempCodePoint;
  25671. }
  25672. }
  25673. break
  25674. case 3:
  25675. secondByte = buf[i + 1];
  25676. thirdByte = buf[i + 2];
  25677. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  25678. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
  25679. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  25680. codePoint = tempCodePoint;
  25681. }
  25682. }
  25683. break
  25684. case 4:
  25685. secondByte = buf[i + 1];
  25686. thirdByte = buf[i + 2];
  25687. fourthByte = buf[i + 3];
  25688. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  25689. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
  25690. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  25691. codePoint = tempCodePoint;
  25692. }
  25693. }
  25694. }
  25695. }
  25696. if (codePoint === null) {
  25697. // we did not generate a valid codePoint so insert a
  25698. // replacement char (U+FFFD) and advance only 1 byte
  25699. codePoint = 0xFFFD;
  25700. bytesPerSequence = 1;
  25701. } else if (codePoint > 0xFFFF) {
  25702. // encode to utf16 (surrogate pair dance)
  25703. codePoint -= 0x10000;
  25704. res.push(codePoint >>> 10 & 0x3FF | 0xD800);
  25705. codePoint = 0xDC00 | codePoint & 0x3FF;
  25706. }
  25707. res.push(codePoint);
  25708. i += bytesPerSequence;
  25709. }
  25710. return decodeCodePointsArray(res)
  25711. }
  25712. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  25713. // the lowest limit is Chrome, with 0x10000 args.
  25714. // We go 1 magnitude less, for safety
  25715. var MAX_ARGUMENTS_LENGTH = 0x1000;
  25716. function decodeCodePointsArray (codePoints) {
  25717. var len = codePoints.length;
  25718. if (len <= MAX_ARGUMENTS_LENGTH) {
  25719. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  25720. }
  25721. // Decode in chunks to avoid "call stack size exceeded".
  25722. var res = '';
  25723. var i = 0;
  25724. while (i < len) {
  25725. res += String.fromCharCode.apply(
  25726. String,
  25727. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  25728. );
  25729. }
  25730. return res
  25731. }
  25732. function asciiSlice (buf, start, end) {
  25733. var ret = '';
  25734. end = Math.min(buf.length, end);
  25735. for (var i = start; i < end; ++i) {
  25736. ret += String.fromCharCode(buf[i] & 0x7F);
  25737. }
  25738. return ret
  25739. }
  25740. function latin1Slice (buf, start, end) {
  25741. var ret = '';
  25742. end = Math.min(buf.length, end);
  25743. for (var i = start; i < end; ++i) {
  25744. ret += String.fromCharCode(buf[i]);
  25745. }
  25746. return ret
  25747. }
  25748. function hexSlice (buf, start, end) {
  25749. var len = buf.length;
  25750. if (!start || start < 0) start = 0;
  25751. if (!end || end < 0 || end > len) end = len;
  25752. var out = '';
  25753. for (var i = start; i < end; ++i) {
  25754. out += toHex(buf[i]);
  25755. }
  25756. return out
  25757. }
  25758. function utf16leSlice (buf, start, end) {
  25759. var bytes = buf.slice(start, end);
  25760. var res = '';
  25761. for (var i = 0; i < bytes.length; i += 2) {
  25762. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
  25763. }
  25764. return res
  25765. }
  25766. Buffer.prototype.slice = function slice (start, end) {
  25767. var len = this.length;
  25768. start = ~~start;
  25769. end = end === undefined ? len : ~~end;
  25770. if (start < 0) {
  25771. start += len;
  25772. if (start < 0) start = 0;
  25773. } else if (start > len) {
  25774. start = len;
  25775. }
  25776. if (end < 0) {
  25777. end += len;
  25778. if (end < 0) end = 0;
  25779. } else if (end > len) {
  25780. end = len;
  25781. }
  25782. if (end < start) end = start;
  25783. var newBuf;
  25784. if (Buffer.TYPED_ARRAY_SUPPORT) {
  25785. newBuf = this.subarray(start, end);
  25786. newBuf.__proto__ = Buffer.prototype;
  25787. } else {
  25788. var sliceLen = end - start;
  25789. newBuf = new Buffer(sliceLen, undefined);
  25790. for (var i = 0; i < sliceLen; ++i) {
  25791. newBuf[i] = this[i + start];
  25792. }
  25793. }
  25794. return newBuf
  25795. };
  25796. /*
  25797. * Need to make sure that buffer isn't trying to write out of bounds.
  25798. */
  25799. function checkOffset (offset, ext, length) {
  25800. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  25801. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  25802. }
  25803. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  25804. offset = offset | 0;
  25805. byteLength = byteLength | 0;
  25806. if (!noAssert) checkOffset(offset, byteLength, this.length);
  25807. var val = this[offset];
  25808. var mul = 1;
  25809. var i = 0;
  25810. while (++i < byteLength && (mul *= 0x100)) {
  25811. val += this[offset + i] * mul;
  25812. }
  25813. return val
  25814. };
  25815. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  25816. offset = offset | 0;
  25817. byteLength = byteLength | 0;
  25818. if (!noAssert) {
  25819. checkOffset(offset, byteLength, this.length);
  25820. }
  25821. var val = this[offset + --byteLength];
  25822. var mul = 1;
  25823. while (byteLength > 0 && (mul *= 0x100)) {
  25824. val += this[offset + --byteLength] * mul;
  25825. }
  25826. return val
  25827. };
  25828. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  25829. if (!noAssert) checkOffset(offset, 1, this.length);
  25830. return this[offset]
  25831. };
  25832. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  25833. if (!noAssert) checkOffset(offset, 2, this.length);
  25834. return this[offset] | (this[offset + 1] << 8)
  25835. };
  25836. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  25837. if (!noAssert) checkOffset(offset, 2, this.length);
  25838. return (this[offset] << 8) | this[offset + 1]
  25839. };
  25840. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  25841. if (!noAssert) checkOffset(offset, 4, this.length);
  25842. return ((this[offset]) |
  25843. (this[offset + 1] << 8) |
  25844. (this[offset + 2] << 16)) +
  25845. (this[offset + 3] * 0x1000000)
  25846. };
  25847. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  25848. if (!noAssert) checkOffset(offset, 4, this.length);
  25849. return (this[offset] * 0x1000000) +
  25850. ((this[offset + 1] << 16) |
  25851. (this[offset + 2] << 8) |
  25852. this[offset + 3])
  25853. };
  25854. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  25855. offset = offset | 0;
  25856. byteLength = byteLength | 0;
  25857. if (!noAssert) checkOffset(offset, byteLength, this.length);
  25858. var val = this[offset];
  25859. var mul = 1;
  25860. var i = 0;
  25861. while (++i < byteLength && (mul *= 0x100)) {
  25862. val += this[offset + i] * mul;
  25863. }
  25864. mul *= 0x80;
  25865. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  25866. return val
  25867. };
  25868. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  25869. offset = offset | 0;
  25870. byteLength = byteLength | 0;
  25871. if (!noAssert) checkOffset(offset, byteLength, this.length);
  25872. var i = byteLength;
  25873. var mul = 1;
  25874. var val = this[offset + --i];
  25875. while (i > 0 && (mul *= 0x100)) {
  25876. val += this[offset + --i] * mul;
  25877. }
  25878. mul *= 0x80;
  25879. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  25880. return val
  25881. };
  25882. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  25883. if (!noAssert) checkOffset(offset, 1, this.length);
  25884. if (!(this[offset] & 0x80)) return (this[offset])
  25885. return ((0xff - this[offset] + 1) * -1)
  25886. };
  25887. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  25888. if (!noAssert) checkOffset(offset, 2, this.length);
  25889. var val = this[offset] | (this[offset + 1] << 8);
  25890. return (val & 0x8000) ? val | 0xFFFF0000 : val
  25891. };
  25892. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  25893. if (!noAssert) checkOffset(offset, 2, this.length);
  25894. var val = this[offset + 1] | (this[offset] << 8);
  25895. return (val & 0x8000) ? val | 0xFFFF0000 : val
  25896. };
  25897. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  25898. if (!noAssert) checkOffset(offset, 4, this.length);
  25899. return (this[offset]) |
  25900. (this[offset + 1] << 8) |
  25901. (this[offset + 2] << 16) |
  25902. (this[offset + 3] << 24)
  25903. };
  25904. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  25905. if (!noAssert) checkOffset(offset, 4, this.length);
  25906. return (this[offset] << 24) |
  25907. (this[offset + 1] << 16) |
  25908. (this[offset + 2] << 8) |
  25909. (this[offset + 3])
  25910. };
  25911. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  25912. if (!noAssert) checkOffset(offset, 4, this.length);
  25913. return read(this, offset, true, 23, 4)
  25914. };
  25915. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  25916. if (!noAssert) checkOffset(offset, 4, this.length);
  25917. return read(this, offset, false, 23, 4)
  25918. };
  25919. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  25920. if (!noAssert) checkOffset(offset, 8, this.length);
  25921. return read(this, offset, true, 52, 8)
  25922. };
  25923. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  25924. if (!noAssert) checkOffset(offset, 8, this.length);
  25925. return read(this, offset, false, 52, 8)
  25926. };
  25927. function checkInt (buf, value, offset, ext, max, min) {
  25928. if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  25929. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  25930. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  25931. }
  25932. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  25933. value = +value;
  25934. offset = offset | 0;
  25935. byteLength = byteLength | 0;
  25936. if (!noAssert) {
  25937. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  25938. checkInt(this, value, offset, byteLength, maxBytes, 0);
  25939. }
  25940. var mul = 1;
  25941. var i = 0;
  25942. this[offset] = value & 0xFF;
  25943. while (++i < byteLength && (mul *= 0x100)) {
  25944. this[offset + i] = (value / mul) & 0xFF;
  25945. }
  25946. return offset + byteLength
  25947. };
  25948. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  25949. value = +value;
  25950. offset = offset | 0;
  25951. byteLength = byteLength | 0;
  25952. if (!noAssert) {
  25953. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  25954. checkInt(this, value, offset, byteLength, maxBytes, 0);
  25955. }
  25956. var i = byteLength - 1;
  25957. var mul = 1;
  25958. this[offset + i] = value & 0xFF;
  25959. while (--i >= 0 && (mul *= 0x100)) {
  25960. this[offset + i] = (value / mul) & 0xFF;
  25961. }
  25962. return offset + byteLength
  25963. };
  25964. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  25965. value = +value;
  25966. offset = offset | 0;
  25967. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
  25968. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
  25969. this[offset] = (value & 0xff);
  25970. return offset + 1
  25971. };
  25972. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  25973. if (value < 0) value = 0xffff + value + 1;
  25974. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  25975. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  25976. (littleEndian ? i : 1 - i) * 8;
  25977. }
  25978. }
  25979. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  25980. value = +value;
  25981. offset = offset | 0;
  25982. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  25983. if (Buffer.TYPED_ARRAY_SUPPORT) {
  25984. this[offset] = (value & 0xff);
  25985. this[offset + 1] = (value >>> 8);
  25986. } else {
  25987. objectWriteUInt16(this, value, offset, true);
  25988. }
  25989. return offset + 2
  25990. };
  25991. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  25992. value = +value;
  25993. offset = offset | 0;
  25994. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  25995. if (Buffer.TYPED_ARRAY_SUPPORT) {
  25996. this[offset] = (value >>> 8);
  25997. this[offset + 1] = (value & 0xff);
  25998. } else {
  25999. objectWriteUInt16(this, value, offset, false);
  26000. }
  26001. return offset + 2
  26002. };
  26003. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  26004. if (value < 0) value = 0xffffffff + value + 1;
  26005. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  26006. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff;
  26007. }
  26008. }
  26009. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  26010. value = +value;
  26011. offset = offset | 0;
  26012. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  26013. if (Buffer.TYPED_ARRAY_SUPPORT) {
  26014. this[offset + 3] = (value >>> 24);
  26015. this[offset + 2] = (value >>> 16);
  26016. this[offset + 1] = (value >>> 8);
  26017. this[offset] = (value & 0xff);
  26018. } else {
  26019. objectWriteUInt32(this, value, offset, true);
  26020. }
  26021. return offset + 4
  26022. };
  26023. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  26024. value = +value;
  26025. offset = offset | 0;
  26026. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  26027. if (Buffer.TYPED_ARRAY_SUPPORT) {
  26028. this[offset] = (value >>> 24);
  26029. this[offset + 1] = (value >>> 16);
  26030. this[offset + 2] = (value >>> 8);
  26031. this[offset + 3] = (value & 0xff);
  26032. } else {
  26033. objectWriteUInt32(this, value, offset, false);
  26034. }
  26035. return offset + 4
  26036. };
  26037. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  26038. value = +value;
  26039. offset = offset | 0;
  26040. if (!noAssert) {
  26041. var limit = Math.pow(2, 8 * byteLength - 1);
  26042. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  26043. }
  26044. var i = 0;
  26045. var mul = 1;
  26046. var sub = 0;
  26047. this[offset] = value & 0xFF;
  26048. while (++i < byteLength && (mul *= 0x100)) {
  26049. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  26050. sub = 1;
  26051. }
  26052. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  26053. }
  26054. return offset + byteLength
  26055. };
  26056. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  26057. value = +value;
  26058. offset = offset | 0;
  26059. if (!noAssert) {
  26060. var limit = Math.pow(2, 8 * byteLength - 1);
  26061. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  26062. }
  26063. var i = byteLength - 1;
  26064. var mul = 1;
  26065. var sub = 0;
  26066. this[offset + i] = value & 0xFF;
  26067. while (--i >= 0 && (mul *= 0x100)) {
  26068. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  26069. sub = 1;
  26070. }
  26071. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  26072. }
  26073. return offset + byteLength
  26074. };
  26075. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  26076. value = +value;
  26077. offset = offset | 0;
  26078. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
  26079. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
  26080. if (value < 0) value = 0xff + value + 1;
  26081. this[offset] = (value & 0xff);
  26082. return offset + 1
  26083. };
  26084. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  26085. value = +value;
  26086. offset = offset | 0;
  26087. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  26088. if (Buffer.TYPED_ARRAY_SUPPORT) {
  26089. this[offset] = (value & 0xff);
  26090. this[offset + 1] = (value >>> 8);
  26091. } else {
  26092. objectWriteUInt16(this, value, offset, true);
  26093. }
  26094. return offset + 2
  26095. };
  26096. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  26097. value = +value;
  26098. offset = offset | 0;
  26099. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  26100. if (Buffer.TYPED_ARRAY_SUPPORT) {
  26101. this[offset] = (value >>> 8);
  26102. this[offset + 1] = (value & 0xff);
  26103. } else {
  26104. objectWriteUInt16(this, value, offset, false);
  26105. }
  26106. return offset + 2
  26107. };
  26108. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  26109. value = +value;
  26110. offset = offset | 0;
  26111. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  26112. if (Buffer.TYPED_ARRAY_SUPPORT) {
  26113. this[offset] = (value & 0xff);
  26114. this[offset + 1] = (value >>> 8);
  26115. this[offset + 2] = (value >>> 16);
  26116. this[offset + 3] = (value >>> 24);
  26117. } else {
  26118. objectWriteUInt32(this, value, offset, true);
  26119. }
  26120. return offset + 4
  26121. };
  26122. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  26123. value = +value;
  26124. offset = offset | 0;
  26125. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  26126. if (value < 0) value = 0xffffffff + value + 1;
  26127. if (Buffer.TYPED_ARRAY_SUPPORT) {
  26128. this[offset] = (value >>> 24);
  26129. this[offset + 1] = (value >>> 16);
  26130. this[offset + 2] = (value >>> 8);
  26131. this[offset + 3] = (value & 0xff);
  26132. } else {
  26133. objectWriteUInt32(this, value, offset, false);
  26134. }
  26135. return offset + 4
  26136. };
  26137. function checkIEEE754 (buf, value, offset, ext, max, min) {
  26138. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  26139. if (offset < 0) throw new RangeError('Index out of range')
  26140. }
  26141. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  26142. if (!noAssert) {
  26143. checkIEEE754(buf, value, offset, 4);
  26144. }
  26145. write(buf, value, offset, littleEndian, 23, 4);
  26146. return offset + 4
  26147. }
  26148. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  26149. return writeFloat(this, value, offset, true, noAssert)
  26150. };
  26151. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  26152. return writeFloat(this, value, offset, false, noAssert)
  26153. };
  26154. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  26155. if (!noAssert) {
  26156. checkIEEE754(buf, value, offset, 8);
  26157. }
  26158. write(buf, value, offset, littleEndian, 52, 8);
  26159. return offset + 8
  26160. }
  26161. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  26162. return writeDouble(this, value, offset, true, noAssert)
  26163. };
  26164. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  26165. return writeDouble(this, value, offset, false, noAssert)
  26166. };
  26167. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  26168. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  26169. if (!start) start = 0;
  26170. if (!end && end !== 0) end = this.length;
  26171. if (targetStart >= target.length) targetStart = target.length;
  26172. if (!targetStart) targetStart = 0;
  26173. if (end > 0 && end < start) end = start;
  26174. // Copy 0 bytes; we're done
  26175. if (end === start) return 0
  26176. if (target.length === 0 || this.length === 0) return 0
  26177. // Fatal error conditions
  26178. if (targetStart < 0) {
  26179. throw new RangeError('targetStart out of bounds')
  26180. }
  26181. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  26182. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  26183. // Are we oob?
  26184. if (end > this.length) end = this.length;
  26185. if (target.length - targetStart < end - start) {
  26186. end = target.length - targetStart + start;
  26187. }
  26188. var len = end - start;
  26189. var i;
  26190. if (this === target && start < targetStart && targetStart < end) {
  26191. // descending copy from end
  26192. for (i = len - 1; i >= 0; --i) {
  26193. target[i + targetStart] = this[i + start];
  26194. }
  26195. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  26196. // ascending copy from start
  26197. for (i = 0; i < len; ++i) {
  26198. target[i + targetStart] = this[i + start];
  26199. }
  26200. } else {
  26201. Uint8Array.prototype.set.call(
  26202. target,
  26203. this.subarray(start, start + len),
  26204. targetStart
  26205. );
  26206. }
  26207. return len
  26208. };
  26209. // Usage:
  26210. // buffer.fill(number[, offset[, end]])
  26211. // buffer.fill(buffer[, offset[, end]])
  26212. // buffer.fill(string[, offset[, end]][, encoding])
  26213. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  26214. // Handle string cases:
  26215. if (typeof val === 'string') {
  26216. if (typeof start === 'string') {
  26217. encoding = start;
  26218. start = 0;
  26219. end = this.length;
  26220. } else if (typeof end === 'string') {
  26221. encoding = end;
  26222. end = this.length;
  26223. }
  26224. if (val.length === 1) {
  26225. var code = val.charCodeAt(0);
  26226. if (code < 256) {
  26227. val = code;
  26228. }
  26229. }
  26230. if (encoding !== undefined && typeof encoding !== 'string') {
  26231. throw new TypeError('encoding must be a string')
  26232. }
  26233. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  26234. throw new TypeError('Unknown encoding: ' + encoding)
  26235. }
  26236. } else if (typeof val === 'number') {
  26237. val = val & 255;
  26238. }
  26239. // Invalid ranges are not set to a default, so can range check early.
  26240. if (start < 0 || this.length < start || this.length < end) {
  26241. throw new RangeError('Out of range index')
  26242. }
  26243. if (end <= start) {
  26244. return this
  26245. }
  26246. start = start >>> 0;
  26247. end = end === undefined ? this.length : end >>> 0;
  26248. if (!val) val = 0;
  26249. var i;
  26250. if (typeof val === 'number') {
  26251. for (i = start; i < end; ++i) {
  26252. this[i] = val;
  26253. }
  26254. } else {
  26255. var bytes = internalIsBuffer(val)
  26256. ? val
  26257. : utf8ToBytes(new Buffer(val, encoding).toString());
  26258. var len = bytes.length;
  26259. for (i = 0; i < end - start; ++i) {
  26260. this[i + start] = bytes[i % len];
  26261. }
  26262. }
  26263. return this
  26264. };
  26265. // HELPER FUNCTIONS
  26266. // ================
  26267. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
  26268. function base64clean (str) {
  26269. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  26270. str = stringtrim(str).replace(INVALID_BASE64_RE, '');
  26271. // Node converts strings with length < 2 to ''
  26272. if (str.length < 2) return ''
  26273. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  26274. while (str.length % 4 !== 0) {
  26275. str = str + '=';
  26276. }
  26277. return str
  26278. }
  26279. function stringtrim (str) {
  26280. if (str.trim) return str.trim()
  26281. return str.replace(/^\s+|\s+$/g, '')
  26282. }
  26283. function toHex (n) {
  26284. if (n < 16) return '0' + n.toString(16)
  26285. return n.toString(16)
  26286. }
  26287. function utf8ToBytes (string, units) {
  26288. units = units || Infinity;
  26289. var codePoint;
  26290. var length = string.length;
  26291. var leadSurrogate = null;
  26292. var bytes = [];
  26293. for (var i = 0; i < length; ++i) {
  26294. codePoint = string.charCodeAt(i);
  26295. // is surrogate component
  26296. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  26297. // last char was a lead
  26298. if (!leadSurrogate) {
  26299. // no lead yet
  26300. if (codePoint > 0xDBFF) {
  26301. // unexpected trail
  26302. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  26303. continue
  26304. } else if (i + 1 === length) {
  26305. // unpaired lead
  26306. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  26307. continue
  26308. }
  26309. // valid lead
  26310. leadSurrogate = codePoint;
  26311. continue
  26312. }
  26313. // 2 leads in a row
  26314. if (codePoint < 0xDC00) {
  26315. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  26316. leadSurrogate = codePoint;
  26317. continue
  26318. }
  26319. // valid surrogate pair
  26320. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
  26321. } else if (leadSurrogate) {
  26322. // valid bmp char, but last char was a lead
  26323. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  26324. }
  26325. leadSurrogate = null;
  26326. // encode utf8
  26327. if (codePoint < 0x80) {
  26328. if ((units -= 1) < 0) break
  26329. bytes.push(codePoint);
  26330. } else if (codePoint < 0x800) {
  26331. if ((units -= 2) < 0) break
  26332. bytes.push(
  26333. codePoint >> 0x6 | 0xC0,
  26334. codePoint & 0x3F | 0x80
  26335. );
  26336. } else if (codePoint < 0x10000) {
  26337. if ((units -= 3) < 0) break
  26338. bytes.push(
  26339. codePoint >> 0xC | 0xE0,
  26340. codePoint >> 0x6 & 0x3F | 0x80,
  26341. codePoint & 0x3F | 0x80
  26342. );
  26343. } else if (codePoint < 0x110000) {
  26344. if ((units -= 4) < 0) break
  26345. bytes.push(
  26346. codePoint >> 0x12 | 0xF0,
  26347. codePoint >> 0xC & 0x3F | 0x80,
  26348. codePoint >> 0x6 & 0x3F | 0x80,
  26349. codePoint & 0x3F | 0x80
  26350. );
  26351. } else {
  26352. throw new Error('Invalid code point')
  26353. }
  26354. }
  26355. return bytes
  26356. }
  26357. function asciiToBytes (str) {
  26358. var byteArray = [];
  26359. for (var i = 0; i < str.length; ++i) {
  26360. // Node's code seems to be doing this and not & 0x7F..
  26361. byteArray.push(str.charCodeAt(i) & 0xFF);
  26362. }
  26363. return byteArray
  26364. }
  26365. function utf16leToBytes (str, units) {
  26366. var c, hi, lo;
  26367. var byteArray = [];
  26368. for (var i = 0; i < str.length; ++i) {
  26369. if ((units -= 2) < 0) break
  26370. c = str.charCodeAt(i);
  26371. hi = c >> 8;
  26372. lo = c % 256;
  26373. byteArray.push(lo);
  26374. byteArray.push(hi);
  26375. }
  26376. return byteArray
  26377. }
  26378. function base64ToBytes (str) {
  26379. return toByteArray(base64clean(str))
  26380. }
  26381. function blitBuffer (src, dst, offset, length) {
  26382. for (var i = 0; i < length; ++i) {
  26383. if ((i + offset >= dst.length) || (i >= src.length)) break
  26384. dst[i + offset] = src[i];
  26385. }
  26386. return i
  26387. }
  26388. function isnan (val) {
  26389. return val !== val // eslint-disable-line no-self-compare
  26390. }
  26391. // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
  26392. // The _isBuffer check is for Safari 5-7 support, because it's missing
  26393. // Object.prototype.constructor. Remove this eventually
  26394. function isBuffer(obj) {
  26395. return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))
  26396. }
  26397. function isFastBuffer (obj) {
  26398. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  26399. }
  26400. // For Node v0.10 support. Remove this eventually.
  26401. function isSlowBuffer (obj) {
  26402. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))
  26403. }
  26404. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  26405. function encode$2(decoded) {
  26406. var sourceFileIndex = 0; // second field
  26407. var sourceCodeLine = 0; // third field
  26408. var sourceCodeColumn = 0; // fourth field
  26409. var nameIndex = 0; // fifth field
  26410. var mappings = '';
  26411. for (var i = 0; i < decoded.length; i++) {
  26412. var line = decoded[i];
  26413. if (i > 0)
  26414. mappings += ';';
  26415. if (line.length === 0)
  26416. continue;
  26417. var generatedCodeColumn = 0; // first field
  26418. var lineMappings = [];
  26419. for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
  26420. var segment = line_1[_i];
  26421. var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
  26422. generatedCodeColumn = segment[0];
  26423. if (segment.length > 1) {
  26424. segmentMappings +=
  26425. encodeInteger(segment[1] - sourceFileIndex) +
  26426. encodeInteger(segment[2] - sourceCodeLine) +
  26427. encodeInteger(segment[3] - sourceCodeColumn);
  26428. sourceFileIndex = segment[1];
  26429. sourceCodeLine = segment[2];
  26430. sourceCodeColumn = segment[3];
  26431. }
  26432. if (segment.length === 5) {
  26433. segmentMappings += encodeInteger(segment[4] - nameIndex);
  26434. nameIndex = segment[4];
  26435. }
  26436. lineMappings.push(segmentMappings);
  26437. }
  26438. mappings += lineMappings.join(',');
  26439. }
  26440. return mappings;
  26441. }
  26442. function encodeInteger(num) {
  26443. var result = '';
  26444. num = num < 0 ? (-num << 1) | 1 : num << 1;
  26445. do {
  26446. var clamped = num & 31;
  26447. num >>>= 5;
  26448. if (num > 0) {
  26449. clamped |= 32;
  26450. }
  26451. result += chars[clamped];
  26452. } while (num > 0);
  26453. return result;
  26454. }
  26455. var BitSet = function BitSet(arg) {
  26456. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  26457. };
  26458. BitSet.prototype.add = function add (n) {
  26459. this.bits[n >> 5] |= 1 << (n & 31);
  26460. };
  26461. BitSet.prototype.has = function has (n) {
  26462. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  26463. };
  26464. var Chunk = function Chunk(start, end, content) {
  26465. this.start = start;
  26466. this.end = end;
  26467. this.original = content;
  26468. this.intro = '';
  26469. this.outro = '';
  26470. this.content = content;
  26471. this.storeName = false;
  26472. this.edited = false;
  26473. // we make these non-enumerable, for sanity while debugging
  26474. Object.defineProperties(this, {
  26475. previous: { writable: true, value: null },
  26476. next: { writable: true, value: null }
  26477. });
  26478. };
  26479. Chunk.prototype.appendLeft = function appendLeft (content) {
  26480. this.outro += content;
  26481. };
  26482. Chunk.prototype.appendRight = function appendRight (content) {
  26483. this.intro = this.intro + content;
  26484. };
  26485. Chunk.prototype.clone = function clone () {
  26486. var chunk = new Chunk(this.start, this.end, this.original);
  26487. chunk.intro = this.intro;
  26488. chunk.outro = this.outro;
  26489. chunk.content = this.content;
  26490. chunk.storeName = this.storeName;
  26491. chunk.edited = this.edited;
  26492. return chunk;
  26493. };
  26494. Chunk.prototype.contains = function contains (index) {
  26495. return this.start < index && index < this.end;
  26496. };
  26497. Chunk.prototype.eachNext = function eachNext (fn) {
  26498. var chunk = this;
  26499. while (chunk) {
  26500. fn(chunk);
  26501. chunk = chunk.next;
  26502. }
  26503. };
  26504. Chunk.prototype.eachPrevious = function eachPrevious (fn) {
  26505. var chunk = this;
  26506. while (chunk) {
  26507. fn(chunk);
  26508. chunk = chunk.previous;
  26509. }
  26510. };
  26511. Chunk.prototype.edit = function edit (content, storeName, contentOnly) {
  26512. this.content = content;
  26513. if (!contentOnly) {
  26514. this.intro = '';
  26515. this.outro = '';
  26516. }
  26517. this.storeName = storeName;
  26518. this.edited = true;
  26519. return this;
  26520. };
  26521. Chunk.prototype.prependLeft = function prependLeft (content) {
  26522. this.outro = content + this.outro;
  26523. };
  26524. Chunk.prototype.prependRight = function prependRight (content) {
  26525. this.intro = content + this.intro;
  26526. };
  26527. Chunk.prototype.split = function split (index) {
  26528. var sliceIndex = index - this.start;
  26529. var originalBefore = this.original.slice(0, sliceIndex);
  26530. var originalAfter = this.original.slice(sliceIndex);
  26531. this.original = originalBefore;
  26532. var newChunk = new Chunk(index, this.end, originalAfter);
  26533. newChunk.outro = this.outro;
  26534. this.outro = '';
  26535. this.end = index;
  26536. if (this.edited) {
  26537. // TODO is this block necessary?...
  26538. newChunk.edit('', false);
  26539. this.content = '';
  26540. } else {
  26541. this.content = originalBefore;
  26542. }
  26543. newChunk.next = this.next;
  26544. if (newChunk.next) { newChunk.next.previous = newChunk; }
  26545. newChunk.previous = this;
  26546. this.next = newChunk;
  26547. return newChunk;
  26548. };
  26549. Chunk.prototype.toString = function toString () {
  26550. return this.intro + this.content + this.outro;
  26551. };
  26552. Chunk.prototype.trimEnd = function trimEnd (rx) {
  26553. this.outro = this.outro.replace(rx, '');
  26554. if (this.outro.length) { return true; }
  26555. var trimmed = this.content.replace(rx, '');
  26556. if (trimmed.length) {
  26557. if (trimmed !== this.content) {
  26558. this.split(this.start + trimmed.length).edit('', undefined, true);
  26559. }
  26560. return true;
  26561. } else {
  26562. this.edit('', undefined, true);
  26563. this.intro = this.intro.replace(rx, '');
  26564. if (this.intro.length) { return true; }
  26565. }
  26566. };
  26567. Chunk.prototype.trimStart = function trimStart (rx) {
  26568. this.intro = this.intro.replace(rx, '');
  26569. if (this.intro.length) { return true; }
  26570. var trimmed = this.content.replace(rx, '');
  26571. if (trimmed.length) {
  26572. if (trimmed !== this.content) {
  26573. this.split(this.end - trimmed.length);
  26574. this.edit('', undefined, true);
  26575. }
  26576. return true;
  26577. } else {
  26578. this.edit('', undefined, true);
  26579. this.outro = this.outro.replace(rx, '');
  26580. if (this.outro.length) { return true; }
  26581. }
  26582. };
  26583. var btoa = function () {
  26584. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  26585. };
  26586. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  26587. btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
  26588. } else if (typeof Buffer === 'function') {
  26589. btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
  26590. }
  26591. var SourceMap = function SourceMap(properties) {
  26592. this.version = 3;
  26593. this.file = properties.file;
  26594. this.sources = properties.sources;
  26595. this.sourcesContent = properties.sourcesContent;
  26596. this.names = properties.names;
  26597. this.mappings = encode$2(properties.mappings);
  26598. };
  26599. SourceMap.prototype.toString = function toString () {
  26600. return JSON.stringify(this);
  26601. };
  26602. SourceMap.prototype.toUrl = function toUrl () {
  26603. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  26604. };
  26605. function guessIndent(code) {
  26606. var lines = code.split('\n');
  26607. var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
  26608. var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
  26609. if (tabbed.length === 0 && spaced.length === 0) {
  26610. return null;
  26611. }
  26612. // More lines tabbed than spaced? Assume tabs, and
  26613. // default to tabs in the case of a tie (or nothing
  26614. // to go on)
  26615. if (tabbed.length >= spaced.length) {
  26616. return '\t';
  26617. }
  26618. // Otherwise, we need to guess the multiple
  26619. var min = spaced.reduce(function (previous, current) {
  26620. var numSpaces = /^ +/.exec(current)[0].length;
  26621. return Math.min(numSpaces, previous);
  26622. }, Infinity);
  26623. return new Array(min + 1).join(' ');
  26624. }
  26625. function getRelativePath(from, to) {
  26626. var fromParts = from.split(/[/\\]/);
  26627. var toParts = to.split(/[/\\]/);
  26628. fromParts.pop(); // get dirname
  26629. while (fromParts[0] === toParts[0]) {
  26630. fromParts.shift();
  26631. toParts.shift();
  26632. }
  26633. if (fromParts.length) {
  26634. var i = fromParts.length;
  26635. while (i--) { fromParts[i] = '..'; }
  26636. }
  26637. return fromParts.concat(toParts).join('/');
  26638. }
  26639. var toString$2 = Object.prototype.toString;
  26640. function isObject$1(thing) {
  26641. return toString$2.call(thing) === '[object Object]';
  26642. }
  26643. function getLocator(source) {
  26644. var originalLines = source.split('\n');
  26645. var lineOffsets = [];
  26646. for (var i = 0, pos = 0; i < originalLines.length; i++) {
  26647. lineOffsets.push(pos);
  26648. pos += originalLines[i].length + 1;
  26649. }
  26650. return function locate(index) {
  26651. var i = 0;
  26652. var j = lineOffsets.length;
  26653. while (i < j) {
  26654. var m = (i + j) >> 1;
  26655. if (index < lineOffsets[m]) {
  26656. j = m;
  26657. } else {
  26658. i = m + 1;
  26659. }
  26660. }
  26661. var line = i - 1;
  26662. var column = index - lineOffsets[line];
  26663. return { line: line, column: column };
  26664. };
  26665. }
  26666. var Mappings = function Mappings(hires) {
  26667. this.hires = hires;
  26668. this.generatedCodeLine = 0;
  26669. this.generatedCodeColumn = 0;
  26670. this.raw = [];
  26671. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  26672. this.pending = null;
  26673. };
  26674. Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) {
  26675. if (content.length) {
  26676. var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  26677. if (nameIndex >= 0) {
  26678. segment.push(nameIndex);
  26679. }
  26680. this.rawSegments.push(segment);
  26681. } else if (this.pending) {
  26682. this.rawSegments.push(this.pending);
  26683. }
  26684. this.advance(content);
  26685. this.pending = null;
  26686. };
  26687. Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) {
  26688. var originalCharIndex = chunk.start;
  26689. var first = true;
  26690. while (originalCharIndex < chunk.end) {
  26691. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  26692. this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
  26693. }
  26694. if (original[originalCharIndex] === '\n') {
  26695. loc.line += 1;
  26696. loc.column = 0;
  26697. this.generatedCodeLine += 1;
  26698. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  26699. this.generatedCodeColumn = 0;
  26700. first = true;
  26701. } else {
  26702. loc.column += 1;
  26703. this.generatedCodeColumn += 1;
  26704. first = false;
  26705. }
  26706. originalCharIndex += 1;
  26707. }
  26708. this.pending = null;
  26709. };
  26710. Mappings.prototype.advance = function advance (str) {
  26711. if (!str) { return; }
  26712. var lines = str.split('\n');
  26713. if (lines.length > 1) {
  26714. for (var i = 0; i < lines.length - 1; i++) {
  26715. this.generatedCodeLine++;
  26716. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  26717. }
  26718. this.generatedCodeColumn = 0;
  26719. }
  26720. this.generatedCodeColumn += lines[lines.length - 1].length;
  26721. };
  26722. var n = '\n';
  26723. var warned = {
  26724. insertLeft: false,
  26725. insertRight: false,
  26726. storeName: false
  26727. };
  26728. var MagicString = function MagicString(string, options) {
  26729. if ( options === void 0 ) options = {};
  26730. var chunk = new Chunk(0, string.length, string);
  26731. Object.defineProperties(this, {
  26732. original: { writable: true, value: string },
  26733. outro: { writable: true, value: '' },
  26734. intro: { writable: true, value: '' },
  26735. firstChunk: { writable: true, value: chunk },
  26736. lastChunk: { writable: true, value: chunk },
  26737. lastSearchedChunk: { writable: true, value: chunk },
  26738. byStart: { writable: true, value: {} },
  26739. byEnd: { writable: true, value: {} },
  26740. filename: { writable: true, value: options.filename },
  26741. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  26742. sourcemapLocations: { writable: true, value: new BitSet() },
  26743. storedNames: { writable: true, value: {} },
  26744. indentStr: { writable: true, value: guessIndent(string) }
  26745. });
  26746. this.byStart[0] = chunk;
  26747. this.byEnd[string.length] = chunk;
  26748. };
  26749. MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) {
  26750. this.sourcemapLocations.add(char);
  26751. };
  26752. MagicString.prototype.append = function append (content) {
  26753. if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
  26754. this.outro += content;
  26755. return this;
  26756. };
  26757. MagicString.prototype.appendLeft = function appendLeft (index, content) {
  26758. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  26759. this._split(index);
  26760. var chunk = this.byEnd[index];
  26761. if (chunk) {
  26762. chunk.appendLeft(content);
  26763. } else {
  26764. this.intro += content;
  26765. }
  26766. return this;
  26767. };
  26768. MagicString.prototype.appendRight = function appendRight (index, content) {
  26769. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  26770. this._split(index);
  26771. var chunk = this.byStart[index];
  26772. if (chunk) {
  26773. chunk.appendRight(content);
  26774. } else {
  26775. this.outro += content;
  26776. }
  26777. return this;
  26778. };
  26779. MagicString.prototype.clone = function clone () {
  26780. var cloned = new MagicString(this.original, { filename: this.filename });
  26781. var originalChunk = this.firstChunk;
  26782. var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  26783. while (originalChunk) {
  26784. cloned.byStart[clonedChunk.start] = clonedChunk;
  26785. cloned.byEnd[clonedChunk.end] = clonedChunk;
  26786. var nextOriginalChunk = originalChunk.next;
  26787. var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  26788. if (nextClonedChunk) {
  26789. clonedChunk.next = nextClonedChunk;
  26790. nextClonedChunk.previous = clonedChunk;
  26791. clonedChunk = nextClonedChunk;
  26792. }
  26793. originalChunk = nextOriginalChunk;
  26794. }
  26795. cloned.lastChunk = clonedChunk;
  26796. if (this.indentExclusionRanges) {
  26797. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  26798. }
  26799. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  26800. cloned.intro = this.intro;
  26801. cloned.outro = this.outro;
  26802. return cloned;
  26803. };
  26804. MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) {
  26805. var this$1 = this;
  26806. options = options || {};
  26807. var sourceIndex = 0;
  26808. var names = Object.keys(this.storedNames);
  26809. var mappings = new Mappings(options.hires);
  26810. var locate = getLocator(this.original);
  26811. if (this.intro) {
  26812. mappings.advance(this.intro);
  26813. }
  26814. this.firstChunk.eachNext(function (chunk) {
  26815. var loc = locate(chunk.start);
  26816. if (chunk.intro.length) { mappings.advance(chunk.intro); }
  26817. if (chunk.edited) {
  26818. mappings.addEdit(
  26819. sourceIndex,
  26820. chunk.content,
  26821. loc,
  26822. chunk.storeName ? names.indexOf(chunk.original) : -1
  26823. );
  26824. } else {
  26825. mappings.addUneditedChunk(sourceIndex, chunk, this$1.original, loc, this$1.sourcemapLocations);
  26826. }
  26827. if (chunk.outro.length) { mappings.advance(chunk.outro); }
  26828. });
  26829. return {
  26830. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  26831. sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
  26832. sourcesContent: options.includeContent ? [this.original] : [null],
  26833. names: names,
  26834. mappings: mappings.raw
  26835. };
  26836. };
  26837. MagicString.prototype.generateMap = function generateMap (options) {
  26838. return new SourceMap(this.generateDecodedMap(options));
  26839. };
  26840. MagicString.prototype.getIndentString = function getIndentString () {
  26841. return this.indentStr === null ? '\t' : this.indentStr;
  26842. };
  26843. MagicString.prototype.indent = function indent (indentStr, options) {
  26844. var pattern = /^[^\r\n]/gm;
  26845. if (isObject$1(indentStr)) {
  26846. options = indentStr;
  26847. indentStr = undefined;
  26848. }
  26849. indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
  26850. if (indentStr === '') { return this; } // noop
  26851. options = options || {};
  26852. // Process exclusion ranges
  26853. var isExcluded = {};
  26854. if (options.exclude) {
  26855. var exclusions =
  26856. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  26857. exclusions.forEach(function (exclusion) {
  26858. for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
  26859. isExcluded[i] = true;
  26860. }
  26861. });
  26862. }
  26863. var shouldIndentNextCharacter = options.indentStart !== false;
  26864. var replacer = function (match) {
  26865. if (shouldIndentNextCharacter) { return ("" + indentStr + match); }
  26866. shouldIndentNextCharacter = true;
  26867. return match;
  26868. };
  26869. this.intro = this.intro.replace(pattern, replacer);
  26870. var charIndex = 0;
  26871. var chunk = this.firstChunk;
  26872. while (chunk) {
  26873. var end = chunk.end;
  26874. if (chunk.edited) {
  26875. if (!isExcluded[charIndex]) {
  26876. chunk.content = chunk.content.replace(pattern, replacer);
  26877. if (chunk.content.length) {
  26878. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  26879. }
  26880. }
  26881. } else {
  26882. charIndex = chunk.start;
  26883. while (charIndex < end) {
  26884. if (!isExcluded[charIndex]) {
  26885. var char = this.original[charIndex];
  26886. if (char === '\n') {
  26887. shouldIndentNextCharacter = true;
  26888. } else if (char !== '\r' && shouldIndentNextCharacter) {
  26889. shouldIndentNextCharacter = false;
  26890. if (charIndex === chunk.start) {
  26891. chunk.prependRight(indentStr);
  26892. } else {
  26893. this._splitChunk(chunk, charIndex);
  26894. chunk = chunk.next;
  26895. chunk.prependRight(indentStr);
  26896. }
  26897. }
  26898. }
  26899. charIndex += 1;
  26900. }
  26901. }
  26902. charIndex = chunk.end;
  26903. chunk = chunk.next;
  26904. }
  26905. this.outro = this.outro.replace(pattern, replacer);
  26906. return this;
  26907. };
  26908. MagicString.prototype.insert = function insert () {
  26909. throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
  26910. };
  26911. MagicString.prototype.insertLeft = function insertLeft (index, content) {
  26912. if (!warned.insertLeft) {
  26913. console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console
  26914. warned.insertLeft = true;
  26915. }
  26916. return this.appendLeft(index, content);
  26917. };
  26918. MagicString.prototype.insertRight = function insertRight (index, content) {
  26919. if (!warned.insertRight) {
  26920. console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console
  26921. warned.insertRight = true;
  26922. }
  26923. return this.prependRight(index, content);
  26924. };
  26925. MagicString.prototype.move = function move (start, end, index) {
  26926. if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); }
  26927. this._split(start);
  26928. this._split(end);
  26929. this._split(index);
  26930. var first = this.byStart[start];
  26931. var last = this.byEnd[end];
  26932. var oldLeft = first.previous;
  26933. var oldRight = last.next;
  26934. var newRight = this.byStart[index];
  26935. if (!newRight && last === this.lastChunk) { return this; }
  26936. var newLeft = newRight ? newRight.previous : this.lastChunk;
  26937. if (oldLeft) { oldLeft.next = oldRight; }
  26938. if (oldRight) { oldRight.previous = oldLeft; }
  26939. if (newLeft) { newLeft.next = first; }
  26940. if (newRight) { newRight.previous = last; }
  26941. if (!first.previous) { this.firstChunk = last.next; }
  26942. if (!last.next) {
  26943. this.lastChunk = first.previous;
  26944. this.lastChunk.next = null;
  26945. }
  26946. first.previous = newLeft;
  26947. last.next = newRight || null;
  26948. if (!newLeft) { this.firstChunk = first; }
  26949. if (!newRight) { this.lastChunk = last; }
  26950. return this;
  26951. };
  26952. MagicString.prototype.overwrite = function overwrite (start, end, content, options) {
  26953. if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); }
  26954. while (start < 0) { start += this.original.length; }
  26955. while (end < 0) { end += this.original.length; }
  26956. if (end > this.original.length) { throw new Error('end is out of bounds'); }
  26957. if (start === end)
  26958. { throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead'); }
  26959. this._split(start);
  26960. this._split(end);
  26961. if (options === true) {
  26962. if (!warned.storeName) {
  26963. 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
  26964. warned.storeName = true;
  26965. }
  26966. options = { storeName: true };
  26967. }
  26968. var storeName = options !== undefined ? options.storeName : false;
  26969. var contentOnly = options !== undefined ? options.contentOnly : false;
  26970. if (storeName) {
  26971. var original = this.original.slice(start, end);
  26972. this.storedNames[original] = true;
  26973. }
  26974. var first = this.byStart[start];
  26975. var last = this.byEnd[end];
  26976. if (first) {
  26977. if (end > first.end && first.next !== this.byStart[first.end]) {
  26978. throw new Error('Cannot overwrite across a split point');
  26979. }
  26980. first.edit(content, storeName, contentOnly);
  26981. if (first !== last) {
  26982. var chunk = first.next;
  26983. while (chunk !== last) {
  26984. chunk.edit('', false);
  26985. chunk = chunk.next;
  26986. }
  26987. chunk.edit('', false);
  26988. }
  26989. } else {
  26990. // must be inserting at the end
  26991. var newChunk = new Chunk(start, end, '').edit(content, storeName);
  26992. // TODO last chunk in the array may not be the last chunk, if it's moved...
  26993. last.next = newChunk;
  26994. newChunk.previous = last;
  26995. }
  26996. return this;
  26997. };
  26998. MagicString.prototype.prepend = function prepend (content) {
  26999. if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
  27000. this.intro = content + this.intro;
  27001. return this;
  27002. };
  27003. MagicString.prototype.prependLeft = function prependLeft (index, content) {
  27004. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  27005. this._split(index);
  27006. var chunk = this.byEnd[index];
  27007. if (chunk) {
  27008. chunk.prependLeft(content);
  27009. } else {
  27010. this.intro = content + this.intro;
  27011. }
  27012. return this;
  27013. };
  27014. MagicString.prototype.prependRight = function prependRight (index, content) {
  27015. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  27016. this._split(index);
  27017. var chunk = this.byStart[index];
  27018. if (chunk) {
  27019. chunk.prependRight(content);
  27020. } else {
  27021. this.outro = content + this.outro;
  27022. }
  27023. return this;
  27024. };
  27025. MagicString.prototype.remove = function remove (start, end) {
  27026. while (start < 0) { start += this.original.length; }
  27027. while (end < 0) { end += this.original.length; }
  27028. if (start === end) { return this; }
  27029. if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); }
  27030. if (start > end) { throw new Error('end must be greater than start'); }
  27031. this._split(start);
  27032. this._split(end);
  27033. var chunk = this.byStart[start];
  27034. while (chunk) {
  27035. chunk.intro = '';
  27036. chunk.outro = '';
  27037. chunk.edit('');
  27038. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  27039. }
  27040. return this;
  27041. };
  27042. MagicString.prototype.lastChar = function lastChar () {
  27043. if (this.outro.length)
  27044. { return this.outro[this.outro.length - 1]; }
  27045. var chunk = this.lastChunk;
  27046. do {
  27047. if (chunk.outro.length)
  27048. { return chunk.outro[chunk.outro.length - 1]; }
  27049. if (chunk.content.length)
  27050. { return chunk.content[chunk.content.length - 1]; }
  27051. if (chunk.intro.length)
  27052. { return chunk.intro[chunk.intro.length - 1]; }
  27053. } while (chunk = chunk.previous);
  27054. if (this.intro.length)
  27055. { return this.intro[this.intro.length - 1]; }
  27056. return '';
  27057. };
  27058. MagicString.prototype.lastLine = function lastLine () {
  27059. var lineIndex = this.outro.lastIndexOf(n);
  27060. if (lineIndex !== -1)
  27061. { return this.outro.substr(lineIndex + 1); }
  27062. var lineStr = this.outro;
  27063. var chunk = this.lastChunk;
  27064. do {
  27065. if (chunk.outro.length > 0) {
  27066. lineIndex = chunk.outro.lastIndexOf(n);
  27067. if (lineIndex !== -1)
  27068. { return chunk.outro.substr(lineIndex + 1) + lineStr; }
  27069. lineStr = chunk.outro + lineStr;
  27070. }
  27071. if (chunk.content.length > 0) {
  27072. lineIndex = chunk.content.lastIndexOf(n);
  27073. if (lineIndex !== -1)
  27074. { return chunk.content.substr(lineIndex + 1) + lineStr; }
  27075. lineStr = chunk.content + lineStr;
  27076. }
  27077. if (chunk.intro.length > 0) {
  27078. lineIndex = chunk.intro.lastIndexOf(n);
  27079. if (lineIndex !== -1)
  27080. { return chunk.intro.substr(lineIndex + 1) + lineStr; }
  27081. lineStr = chunk.intro + lineStr;
  27082. }
  27083. } while (chunk = chunk.previous);
  27084. lineIndex = this.intro.lastIndexOf(n);
  27085. if (lineIndex !== -1)
  27086. { return this.intro.substr(lineIndex + 1) + lineStr; }
  27087. return this.intro + lineStr;
  27088. };
  27089. MagicString.prototype.slice = function slice (start, end) {
  27090. if ( start === void 0 ) start = 0;
  27091. if ( end === void 0 ) end = this.original.length;
  27092. while (start < 0) { start += this.original.length; }
  27093. while (end < 0) { end += this.original.length; }
  27094. var result = '';
  27095. // find start chunk
  27096. var chunk = this.firstChunk;
  27097. while (chunk && (chunk.start > start || chunk.end <= start)) {
  27098. // found end chunk before start
  27099. if (chunk.start < end && chunk.end >= end) {
  27100. return result;
  27101. }
  27102. chunk = chunk.next;
  27103. }
  27104. if (chunk && chunk.edited && chunk.start !== start)
  27105. { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
  27106. var startChunk = chunk;
  27107. while (chunk) {
  27108. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  27109. result += chunk.intro;
  27110. }
  27111. var containsEnd = chunk.start < end && chunk.end >= end;
  27112. if (containsEnd && chunk.edited && chunk.end !== end)
  27113. { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
  27114. var sliceStart = startChunk === chunk ? start - chunk.start : 0;
  27115. var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  27116. result += chunk.content.slice(sliceStart, sliceEnd);
  27117. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  27118. result += chunk.outro;
  27119. }
  27120. if (containsEnd) {
  27121. break;
  27122. }
  27123. chunk = chunk.next;
  27124. }
  27125. return result;
  27126. };
  27127. // TODO deprecate this? not really very useful
  27128. MagicString.prototype.snip = function snip (start, end) {
  27129. var clone = this.clone();
  27130. clone.remove(0, start);
  27131. clone.remove(end, clone.original.length);
  27132. return clone;
  27133. };
  27134. MagicString.prototype._split = function _split (index) {
  27135. if (this.byStart[index] || this.byEnd[index]) { return; }
  27136. var chunk = this.lastSearchedChunk;
  27137. var searchForward = index > chunk.end;
  27138. while (chunk) {
  27139. if (chunk.contains(index)) { return this._splitChunk(chunk, index); }
  27140. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  27141. }
  27142. };
  27143. MagicString.prototype._splitChunk = function _splitChunk (chunk, index) {
  27144. if (chunk.edited && chunk.content.length) {
  27145. // zero-length edited chunks are a special case (overlapping replacements)
  27146. var loc = getLocator(this.original)(index);
  27147. throw new Error(
  27148. ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")")
  27149. );
  27150. }
  27151. var newChunk = chunk.split(index);
  27152. this.byEnd[index] = chunk;
  27153. this.byStart[index] = newChunk;
  27154. this.byEnd[newChunk.end] = newChunk;
  27155. if (chunk === this.lastChunk) { this.lastChunk = newChunk; }
  27156. this.lastSearchedChunk = chunk;
  27157. return true;
  27158. };
  27159. MagicString.prototype.toString = function toString () {
  27160. var str = this.intro;
  27161. var chunk = this.firstChunk;
  27162. while (chunk) {
  27163. str += chunk.toString();
  27164. chunk = chunk.next;
  27165. }
  27166. return str + this.outro;
  27167. };
  27168. MagicString.prototype.isEmpty = function isEmpty () {
  27169. var chunk = this.firstChunk;
  27170. do {
  27171. if (chunk.intro.length && chunk.intro.trim() ||
  27172. chunk.content.length && chunk.content.trim() ||
  27173. chunk.outro.length && chunk.outro.trim())
  27174. { return false; }
  27175. } while (chunk = chunk.next);
  27176. return true;
  27177. };
  27178. MagicString.prototype.length = function length () {
  27179. var chunk = this.firstChunk;
  27180. var length = 0;
  27181. do {
  27182. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  27183. } while (chunk = chunk.next);
  27184. return length;
  27185. };
  27186. MagicString.prototype.trimLines = function trimLines () {
  27187. return this.trim('[\\r\\n]');
  27188. };
  27189. MagicString.prototype.trim = function trim (charType) {
  27190. return this.trimStart(charType).trimEnd(charType);
  27191. };
  27192. MagicString.prototype.trimEndAborted = function trimEndAborted (charType) {
  27193. var rx = new RegExp((charType || '\\s') + '+$');
  27194. this.outro = this.outro.replace(rx, '');
  27195. if (this.outro.length) { return true; }
  27196. var chunk = this.lastChunk;
  27197. do {
  27198. var end = chunk.end;
  27199. var aborted = chunk.trimEnd(rx);
  27200. // if chunk was trimmed, we have a new lastChunk
  27201. if (chunk.end !== end) {
  27202. if (this.lastChunk === chunk) {
  27203. this.lastChunk = chunk.next;
  27204. }
  27205. this.byEnd[chunk.end] = chunk;
  27206. this.byStart[chunk.next.start] = chunk.next;
  27207. this.byEnd[chunk.next.end] = chunk.next;
  27208. }
  27209. if (aborted) { return true; }
  27210. chunk = chunk.previous;
  27211. } while (chunk);
  27212. return false;
  27213. };
  27214. MagicString.prototype.trimEnd = function trimEnd (charType) {
  27215. this.trimEndAborted(charType);
  27216. return this;
  27217. };
  27218. MagicString.prototype.trimStartAborted = function trimStartAborted (charType) {
  27219. var rx = new RegExp('^' + (charType || '\\s') + '+');
  27220. this.intro = this.intro.replace(rx, '');
  27221. if (this.intro.length) { return true; }
  27222. var chunk = this.firstChunk;
  27223. do {
  27224. var end = chunk.end;
  27225. var aborted = chunk.trimStart(rx);
  27226. if (chunk.end !== end) {
  27227. // special case...
  27228. if (chunk === this.lastChunk) { this.lastChunk = chunk.next; }
  27229. this.byEnd[chunk.end] = chunk;
  27230. this.byStart[chunk.next.start] = chunk.next;
  27231. this.byEnd[chunk.next.end] = chunk.next;
  27232. }
  27233. if (aborted) { return true; }
  27234. chunk = chunk.next;
  27235. } while (chunk);
  27236. return false;
  27237. };
  27238. MagicString.prototype.trimStart = function trimStart (charType) {
  27239. this.trimStartAborted(charType);
  27240. return this;
  27241. };
  27242. // Copyright Joyent, Inc. and other Node contributors.
  27243. //
  27244. // Permission is hereby granted, free of charge, to any person obtaining a
  27245. // copy of this software and associated documentation files (the
  27246. // "Software"), to deal in the Software without restriction, including
  27247. // without limitation the rights to use, copy, modify, merge, publish,
  27248. // distribute, sublicense, and/or sell copies of the Software, and to permit
  27249. // persons to whom the Software is furnished to do so, subject to the
  27250. // following conditions:
  27251. //
  27252. // The above copyright notice and this permission notice shall be included
  27253. // in all copies or substantial portions of the Software.
  27254. //
  27255. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  27256. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27257. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  27258. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  27259. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  27260. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  27261. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  27262. // resolves . and .. elements in a path array with directory names there
  27263. // must be no slashes, empty elements, or device names (c:\) in the array
  27264. // (so also no leading and trailing slashes - it does not distinguish
  27265. // relative and absolute paths)
  27266. function normalizeArray(parts, allowAboveRoot) {
  27267. // if the path tries to go above the root, `up` ends up > 0
  27268. var up = 0;
  27269. for (var i = parts.length - 1; i >= 0; i--) {
  27270. var last = parts[i];
  27271. if (last === '.') {
  27272. parts.splice(i, 1);
  27273. } else if (last === '..') {
  27274. parts.splice(i, 1);
  27275. up++;
  27276. } else if (up) {
  27277. parts.splice(i, 1);
  27278. up--;
  27279. }
  27280. }
  27281. // if the path is allowed to go above the root, restore leading ..s
  27282. if (allowAboveRoot) {
  27283. for (; up--; up) {
  27284. parts.unshift('..');
  27285. }
  27286. }
  27287. return parts;
  27288. }
  27289. // Split a filename into [root, dir, basename, ext], unix version
  27290. // 'root' is just a slash, or nothing.
  27291. var splitPathRe =
  27292. /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
  27293. var splitPath = function(filename) {
  27294. return splitPathRe.exec(filename).slice(1);
  27295. };
  27296. // path.resolve([from ...], to)
  27297. // posix version
  27298. function resolve() {
  27299. var resolvedPath = '',
  27300. resolvedAbsolute = false;
  27301. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  27302. var path = (i >= 0) ? arguments[i] : '/';
  27303. // Skip empty and invalid entries
  27304. if (typeof path !== 'string') {
  27305. throw new TypeError('Arguments to path.resolve must be strings');
  27306. } else if (!path) {
  27307. continue;
  27308. }
  27309. resolvedPath = path + '/' + resolvedPath;
  27310. resolvedAbsolute = path.charAt(0) === '/';
  27311. }
  27312. // At this point the path should be resolved to a full absolute path, but
  27313. // handle relative paths to be safe (might happen when process.cwd() fails)
  27314. // Normalize the path
  27315. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  27316. return !!p;
  27317. }), !resolvedAbsolute).join('/');
  27318. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  27319. }
  27320. // path.normalize(path)
  27321. // posix version
  27322. function normalize(path) {
  27323. var isPathAbsolute = isAbsolute(path),
  27324. trailingSlash = substr(path, -1) === '/';
  27325. // Normalize the path
  27326. path = normalizeArray(filter(path.split('/'), function(p) {
  27327. return !!p;
  27328. }), !isPathAbsolute).join('/');
  27329. if (!path && !isPathAbsolute) {
  27330. path = '.';
  27331. }
  27332. if (path && trailingSlash) {
  27333. path += '/';
  27334. }
  27335. return (isPathAbsolute ? '/' : '') + path;
  27336. }
  27337. // posix version
  27338. function isAbsolute(path) {
  27339. return path.charAt(0) === '/';
  27340. }
  27341. // posix version
  27342. function join() {
  27343. var paths = Array.prototype.slice.call(arguments, 0);
  27344. return normalize(filter(paths, function(p, index) {
  27345. if (typeof p !== 'string') {
  27346. throw new TypeError('Arguments to path.join must be strings');
  27347. }
  27348. return p;
  27349. }).join('/'));
  27350. }
  27351. // path.relative(from, to)
  27352. // posix version
  27353. function relative(from, to) {
  27354. from = resolve(from).substr(1);
  27355. to = resolve(to).substr(1);
  27356. function trim(arr) {
  27357. var start = 0;
  27358. for (; start < arr.length; start++) {
  27359. if (arr[start] !== '') break;
  27360. }
  27361. var end = arr.length - 1;
  27362. for (; end >= 0; end--) {
  27363. if (arr[end] !== '') break;
  27364. }
  27365. if (start > end) return [];
  27366. return arr.slice(start, end - start + 1);
  27367. }
  27368. var fromParts = trim(from.split('/'));
  27369. var toParts = trim(to.split('/'));
  27370. var length = Math.min(fromParts.length, toParts.length);
  27371. var samePartsLength = length;
  27372. for (var i = 0; i < length; i++) {
  27373. if (fromParts[i] !== toParts[i]) {
  27374. samePartsLength = i;
  27375. break;
  27376. }
  27377. }
  27378. var outputParts = [];
  27379. for (var i = samePartsLength; i < fromParts.length; i++) {
  27380. outputParts.push('..');
  27381. }
  27382. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  27383. return outputParts.join('/');
  27384. }
  27385. var sep = '/';
  27386. var delimiter = ':';
  27387. function dirname(path) {
  27388. var result = splitPath(path),
  27389. root = result[0],
  27390. dir = result[1];
  27391. if (!root && !dir) {
  27392. // No dirname whatsoever
  27393. return '.';
  27394. }
  27395. if (dir) {
  27396. // It has a dirname, strip trailing slash
  27397. dir = dir.substr(0, dir.length - 1);
  27398. }
  27399. return root + dir;
  27400. }
  27401. function basename(path, ext) {
  27402. var f = splitPath(path)[2];
  27403. // TODO: make this comparison case-insensitive on windows?
  27404. if (ext && f.substr(-1 * ext.length) === ext) {
  27405. f = f.substr(0, f.length - ext.length);
  27406. }
  27407. return f;
  27408. }
  27409. function extname(path) {
  27410. return splitPath(path)[3];
  27411. }
  27412. var path = {
  27413. extname: extname,
  27414. basename: basename,
  27415. dirname: dirname,
  27416. sep: sep,
  27417. delimiter: delimiter,
  27418. relative: relative,
  27419. join: join,
  27420. isAbsolute: isAbsolute,
  27421. normalize: normalize,
  27422. resolve: resolve
  27423. };
  27424. function filter (xs, f) {
  27425. if (xs.filter) return xs.filter(f);
  27426. var res = [];
  27427. for (var i = 0; i < xs.length; i++) {
  27428. if (f(xs[i], i, xs)) res.push(xs[i]);
  27429. }
  27430. return res;
  27431. }
  27432. // String.prototype.substr - negative index don't work in IE8
  27433. var substr = 'ab'.substr(-1) === 'b' ?
  27434. function (str, start, len) { return str.substr(start, len) } :
  27435. function (str, start, len) {
  27436. if (start < 0) start = str.length + start;
  27437. return str.substr(start, len);
  27438. }
  27439. ;
  27440. var _polyfillNode_path = /*#__PURE__*/Object.freeze({
  27441. __proto__: null,
  27442. resolve: resolve,
  27443. normalize: normalize,
  27444. isAbsolute: isAbsolute,
  27445. join: join,
  27446. relative: relative,
  27447. sep: sep,
  27448. delimiter: delimiter,
  27449. dirname: dirname,
  27450. basename: basename,
  27451. extname: extname,
  27452. 'default': path
  27453. });
  27454. /*! https://mths.be/punycode v1.4.1 by @mathias */
  27455. /** Highest positive signed 32-bit float value */
  27456. var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
  27457. /** Bootstring parameters */
  27458. var base = 36;
  27459. var tMin = 1;
  27460. var tMax = 26;
  27461. var skew = 38;
  27462. var damp = 700;
  27463. var initialBias = 72;
  27464. var initialN = 128; // 0x80
  27465. var delimiter$1 = '-'; // '\x2D'
  27466. var regexNonASCII = /[^\x20-\x7E]/; // unprintable ASCII chars + non-ASCII chars
  27467. var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
  27468. /** Error messages */
  27469. var errors = {
  27470. 'overflow': 'Overflow: input needs wider integers to process',
  27471. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  27472. 'invalid-input': 'Invalid input'
  27473. };
  27474. /** Convenience shortcuts */
  27475. var baseMinusTMin = base - tMin;
  27476. var floor = Math.floor;
  27477. var stringFromCharCode = String.fromCharCode;
  27478. /*--------------------------------------------------------------------------*/
  27479. /**
  27480. * A generic error utility function.
  27481. * @private
  27482. * @param {String} type The error type.
  27483. * @returns {Error} Throws a `RangeError` with the applicable error message.
  27484. */
  27485. function error(type) {
  27486. throw new RangeError(errors[type]);
  27487. }
  27488. /**
  27489. * A generic `Array#map` utility function.
  27490. * @private
  27491. * @param {Array} array The array to iterate over.
  27492. * @param {Function} callback The function that gets called for every array
  27493. * item.
  27494. * @returns {Array} A new array of values returned by the callback function.
  27495. */
  27496. function map(array, fn) {
  27497. var length = array.length;
  27498. var result = [];
  27499. while (length--) {
  27500. result[length] = fn(array[length]);
  27501. }
  27502. return result;
  27503. }
  27504. /**
  27505. * A simple `Array#map`-like wrapper to work with domain name strings or email
  27506. * addresses.
  27507. * @private
  27508. * @param {String} domain The domain name or email address.
  27509. * @param {Function} callback The function that gets called for every
  27510. * character.
  27511. * @returns {Array} A new string of characters returned by the callback
  27512. * function.
  27513. */
  27514. function mapDomain(string, fn) {
  27515. var parts = string.split('@');
  27516. var result = '';
  27517. if (parts.length > 1) {
  27518. // In email addresses, only the domain name should be punycoded. Leave
  27519. // the local part (i.e. everything up to `@`) intact.
  27520. result = parts[0] + '@';
  27521. string = parts[1];
  27522. }
  27523. // Avoid `split(regex)` for IE8 compatibility. See #17.
  27524. string = string.replace(regexSeparators, '\x2E');
  27525. var labels = string.split('.');
  27526. var encoded = map(labels, fn).join('.');
  27527. return result + encoded;
  27528. }
  27529. /**
  27530. * Creates an array containing the numeric code points of each Unicode
  27531. * character in the string. While JavaScript uses UCS-2 internally,
  27532. * this function will convert a pair of surrogate halves (each of which
  27533. * UCS-2 exposes as separate characters) into a single code point,
  27534. * matching UTF-16.
  27535. * @see `punycode.ucs2.encode`
  27536. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  27537. * @memberOf punycode.ucs2
  27538. * @name decode
  27539. * @param {String} string The Unicode input string (UCS-2).
  27540. * @returns {Array} The new array of code points.
  27541. */
  27542. function ucs2decode(string) {
  27543. var output = [],
  27544. counter = 0,
  27545. length = string.length,
  27546. value,
  27547. extra;
  27548. while (counter < length) {
  27549. value = string.charCodeAt(counter++);
  27550. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  27551. // high surrogate, and there is a next character
  27552. extra = string.charCodeAt(counter++);
  27553. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  27554. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  27555. } else {
  27556. // unmatched surrogate; only append this code unit, in case the next
  27557. // code unit is the high surrogate of a surrogate pair
  27558. output.push(value);
  27559. counter--;
  27560. }
  27561. } else {
  27562. output.push(value);
  27563. }
  27564. }
  27565. return output;
  27566. }
  27567. /**
  27568. * Converts a digit/integer into a basic code point.
  27569. * @see `basicToDigit()`
  27570. * @private
  27571. * @param {Number} digit The numeric value of a basic code point.
  27572. * @returns {Number} The basic code point whose value (when used for
  27573. * representing integers) is `digit`, which needs to be in the range
  27574. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  27575. * used; else, the lowercase form is used. The behavior is undefined
  27576. * if `flag` is non-zero and `digit` has no uppercase form.
  27577. */
  27578. function digitToBasic(digit, flag) {
  27579. // 0..25 map to ASCII a..z or A..Z
  27580. // 26..35 map to ASCII 0..9
  27581. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  27582. }
  27583. /**
  27584. * Bias adaptation function as per section 3.4 of RFC 3492.
  27585. * https://tools.ietf.org/html/rfc3492#section-3.4
  27586. * @private
  27587. */
  27588. function adapt(delta, numPoints, firstTime) {
  27589. var k = 0;
  27590. delta = firstTime ? floor(delta / damp) : delta >> 1;
  27591. delta += floor(delta / numPoints);
  27592. for ( /* no initialization */ ; delta > baseMinusTMin * tMax >> 1; k += base) {
  27593. delta = floor(delta / baseMinusTMin);
  27594. }
  27595. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  27596. }
  27597. /**
  27598. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  27599. * Punycode string of ASCII-only symbols.
  27600. * @memberOf punycode
  27601. * @param {String} input The string of Unicode symbols.
  27602. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  27603. */
  27604. function encode$3(input) {
  27605. var n,
  27606. delta,
  27607. handledCPCount,
  27608. basicLength,
  27609. bias,
  27610. j,
  27611. m,
  27612. q,
  27613. k,
  27614. t,
  27615. currentValue,
  27616. output = [],
  27617. /** `inputLength` will hold the number of code points in `input`. */
  27618. inputLength,
  27619. /** Cached calculation results */
  27620. handledCPCountPlusOne,
  27621. baseMinusT,
  27622. qMinusT;
  27623. // Convert the input in UCS-2 to Unicode
  27624. input = ucs2decode(input);
  27625. // Cache the length
  27626. inputLength = input.length;
  27627. // Initialize the state
  27628. n = initialN;
  27629. delta = 0;
  27630. bias = initialBias;
  27631. // Handle the basic code points
  27632. for (j = 0; j < inputLength; ++j) {
  27633. currentValue = input[j];
  27634. if (currentValue < 0x80) {
  27635. output.push(stringFromCharCode(currentValue));
  27636. }
  27637. }
  27638. handledCPCount = basicLength = output.length;
  27639. // `handledCPCount` is the number of code points that have been handled;
  27640. // `basicLength` is the number of basic code points.
  27641. // Finish the basic string - if it is not empty - with a delimiter
  27642. if (basicLength) {
  27643. output.push(delimiter$1);
  27644. }
  27645. // Main encoding loop:
  27646. while (handledCPCount < inputLength) {
  27647. // All non-basic code points < n have been handled already. Find the next
  27648. // larger one:
  27649. for (m = maxInt, j = 0; j < inputLength; ++j) {
  27650. currentValue = input[j];
  27651. if (currentValue >= n && currentValue < m) {
  27652. m = currentValue;
  27653. }
  27654. }
  27655. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  27656. // but guard against overflow
  27657. handledCPCountPlusOne = handledCPCount + 1;
  27658. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  27659. error('overflow');
  27660. }
  27661. delta += (m - n) * handledCPCountPlusOne;
  27662. n = m;
  27663. for (j = 0; j < inputLength; ++j) {
  27664. currentValue = input[j];
  27665. if (currentValue < n && ++delta > maxInt) {
  27666. error('overflow');
  27667. }
  27668. if (currentValue == n) {
  27669. // Represent delta as a generalized variable-length integer
  27670. for (q = delta, k = base; /* no condition */ ; k += base) {
  27671. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  27672. if (q < t) {
  27673. break;
  27674. }
  27675. qMinusT = q - t;
  27676. baseMinusT = base - t;
  27677. output.push(
  27678. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  27679. );
  27680. q = floor(qMinusT / baseMinusT);
  27681. }
  27682. output.push(stringFromCharCode(digitToBasic(q, 0)));
  27683. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  27684. delta = 0;
  27685. ++handledCPCount;
  27686. }
  27687. }
  27688. ++delta;
  27689. ++n;
  27690. }
  27691. return output.join('');
  27692. }
  27693. /**
  27694. * Converts a Unicode string representing a domain name or an email address to
  27695. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  27696. * i.e. it doesn't matter if you call it with a domain that's already in
  27697. * ASCII.
  27698. * @memberOf punycode
  27699. * @param {String} input The domain name or email address to convert, as a
  27700. * Unicode string.
  27701. * @returns {String} The Punycode representation of the given domain name or
  27702. * email address.
  27703. */
  27704. function toASCII(input) {
  27705. return mapDomain(input, function(string) {
  27706. return regexNonASCII.test(string) ?
  27707. 'xn--' + encode$3(string) :
  27708. string;
  27709. });
  27710. }
  27711. // shim for using process in browser
  27712. // based off https://github.com/defunctzombie/node-process/blob/master/browser.js
  27713. function defaultSetTimout() {
  27714. throw new Error('setTimeout has not been defined');
  27715. }
  27716. function defaultClearTimeout () {
  27717. throw new Error('clearTimeout has not been defined');
  27718. }
  27719. var cachedSetTimeout = defaultSetTimout;
  27720. var cachedClearTimeout = defaultClearTimeout;
  27721. if (typeof global.setTimeout === 'function') {
  27722. cachedSetTimeout = setTimeout;
  27723. }
  27724. if (typeof global.clearTimeout === 'function') {
  27725. cachedClearTimeout = clearTimeout;
  27726. }
  27727. function runTimeout(fun) {
  27728. if (cachedSetTimeout === setTimeout) {
  27729. //normal enviroments in sane situations
  27730. return setTimeout(fun, 0);
  27731. }
  27732. // if setTimeout wasn't available but was latter defined
  27733. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  27734. cachedSetTimeout = setTimeout;
  27735. return setTimeout(fun, 0);
  27736. }
  27737. try {
  27738. // when when somebody has screwed with setTimeout but no I.E. maddness
  27739. return cachedSetTimeout(fun, 0);
  27740. } catch(e){
  27741. try {
  27742. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  27743. return cachedSetTimeout.call(null, fun, 0);
  27744. } catch(e){
  27745. // 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
  27746. return cachedSetTimeout.call(this, fun, 0);
  27747. }
  27748. }
  27749. }
  27750. function runClearTimeout(marker) {
  27751. if (cachedClearTimeout === clearTimeout) {
  27752. //normal enviroments in sane situations
  27753. return clearTimeout(marker);
  27754. }
  27755. // if clearTimeout wasn't available but was latter defined
  27756. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  27757. cachedClearTimeout = clearTimeout;
  27758. return clearTimeout(marker);
  27759. }
  27760. try {
  27761. // when when somebody has screwed with setTimeout but no I.E. maddness
  27762. return cachedClearTimeout(marker);
  27763. } catch (e){
  27764. try {
  27765. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  27766. return cachedClearTimeout.call(null, marker);
  27767. } catch (e){
  27768. // 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.
  27769. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  27770. return cachedClearTimeout.call(this, marker);
  27771. }
  27772. }
  27773. }
  27774. var queue = [];
  27775. var draining = false;
  27776. var currentQueue;
  27777. var queueIndex = -1;
  27778. function cleanUpNextTick() {
  27779. if (!draining || !currentQueue) {
  27780. return;
  27781. }
  27782. draining = false;
  27783. if (currentQueue.length) {
  27784. queue = currentQueue.concat(queue);
  27785. } else {
  27786. queueIndex = -1;
  27787. }
  27788. if (queue.length) {
  27789. drainQueue();
  27790. }
  27791. }
  27792. function drainQueue() {
  27793. if (draining) {
  27794. return;
  27795. }
  27796. var timeout = runTimeout(cleanUpNextTick);
  27797. draining = true;
  27798. var len = queue.length;
  27799. while(len) {
  27800. currentQueue = queue;
  27801. queue = [];
  27802. while (++queueIndex < len) {
  27803. if (currentQueue) {
  27804. currentQueue[queueIndex].run();
  27805. }
  27806. }
  27807. queueIndex = -1;
  27808. len = queue.length;
  27809. }
  27810. currentQueue = null;
  27811. draining = false;
  27812. runClearTimeout(timeout);
  27813. }
  27814. function nextTick(fun) {
  27815. var args = new Array(arguments.length - 1);
  27816. if (arguments.length > 1) {
  27817. for (var i = 1; i < arguments.length; i++) {
  27818. args[i - 1] = arguments[i];
  27819. }
  27820. }
  27821. queue.push(new Item(fun, args));
  27822. if (queue.length === 1 && !draining) {
  27823. runTimeout(drainQueue);
  27824. }
  27825. }
  27826. // v8 likes predictible objects
  27827. function Item(fun, array) {
  27828. this.fun = fun;
  27829. this.array = array;
  27830. }
  27831. Item.prototype.run = function () {
  27832. this.fun.apply(null, this.array);
  27833. };
  27834. var title = 'browser';
  27835. var platform = 'browser';
  27836. var browser = true;
  27837. var env = {};
  27838. var argv = [];
  27839. var version = ''; // empty string to avoid regexp issues
  27840. var versions = {};
  27841. var release = {};
  27842. var config = {};
  27843. function noop() {}
  27844. var on = noop;
  27845. var addListener = noop;
  27846. var once = noop;
  27847. var off = noop;
  27848. var removeListener = noop;
  27849. var removeAllListeners = noop;
  27850. var emit = noop;
  27851. function binding(name) {
  27852. throw new Error('process.binding is not supported');
  27853. }
  27854. function cwd () { return '/' }
  27855. function chdir (dir) {
  27856. throw new Error('process.chdir is not supported');
  27857. }function umask() { return 0; }
  27858. // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
  27859. var performance = global.performance || {};
  27860. var performanceNow =
  27861. performance.now ||
  27862. performance.mozNow ||
  27863. performance.msNow ||
  27864. performance.oNow ||
  27865. performance.webkitNow ||
  27866. function(){ return (new Date()).getTime() };
  27867. // generate timestamp or delta
  27868. // see http://nodejs.org/api/process.html#process_process_hrtime
  27869. function hrtime(previousTimestamp){
  27870. var clocktime = performanceNow.call(performance)*1e-3;
  27871. var seconds = Math.floor(clocktime);
  27872. var nanoseconds = Math.floor((clocktime%1)*1e9);
  27873. if (previousTimestamp) {
  27874. seconds = seconds - previousTimestamp[0];
  27875. nanoseconds = nanoseconds - previousTimestamp[1];
  27876. if (nanoseconds<0) {
  27877. seconds--;
  27878. nanoseconds += 1e9;
  27879. }
  27880. }
  27881. return [seconds,nanoseconds]
  27882. }
  27883. var startTime = new Date();
  27884. function uptime() {
  27885. var currentTime = new Date();
  27886. var dif = currentTime - startTime;
  27887. return dif / 1000;
  27888. }
  27889. var browser$1 = {
  27890. nextTick: nextTick,
  27891. title: title,
  27892. browser: browser,
  27893. env: env,
  27894. argv: argv,
  27895. version: version,
  27896. versions: versions,
  27897. on: on,
  27898. addListener: addListener,
  27899. once: once,
  27900. off: off,
  27901. removeListener: removeListener,
  27902. removeAllListeners: removeAllListeners,
  27903. emit: emit,
  27904. binding: binding,
  27905. cwd: cwd,
  27906. chdir: chdir,
  27907. umask: umask,
  27908. hrtime: hrtime,
  27909. platform: platform,
  27910. release: release,
  27911. config: config,
  27912. uptime: uptime
  27913. };
  27914. var inherits;
  27915. if (typeof Object.create === 'function'){
  27916. inherits = function inherits(ctor, superCtor) {
  27917. // implementation from standard node.js 'util' module
  27918. ctor.super_ = superCtor;
  27919. ctor.prototype = Object.create(superCtor.prototype, {
  27920. constructor: {
  27921. value: ctor,
  27922. enumerable: false,
  27923. writable: true,
  27924. configurable: true
  27925. }
  27926. });
  27927. };
  27928. } else {
  27929. inherits = function inherits(ctor, superCtor) {
  27930. ctor.super_ = superCtor;
  27931. var TempCtor = function () {};
  27932. TempCtor.prototype = superCtor.prototype;
  27933. ctor.prototype = new TempCtor();
  27934. ctor.prototype.constructor = ctor;
  27935. };
  27936. }
  27937. var inherits$1 = inherits;
  27938. var formatRegExp = /%[sdj%]/g;
  27939. function format(f) {
  27940. if (!isString$1(f)) {
  27941. var objects = [];
  27942. for (var i = 0; i < arguments.length; i++) {
  27943. objects.push(inspect(arguments[i]));
  27944. }
  27945. return objects.join(' ');
  27946. }
  27947. var i = 1;
  27948. var args = arguments;
  27949. var len = args.length;
  27950. var str = String(f).replace(formatRegExp, function(x) {
  27951. if (x === '%%') return '%';
  27952. if (i >= len) return x;
  27953. switch (x) {
  27954. case '%s': return String(args[i++]);
  27955. case '%d': return Number(args[i++]);
  27956. case '%j':
  27957. try {
  27958. return JSON.stringify(args[i++]);
  27959. } catch (_) {
  27960. return '[Circular]';
  27961. }
  27962. default:
  27963. return x;
  27964. }
  27965. });
  27966. for (var x = args[i]; i < len; x = args[++i]) {
  27967. if (isNull(x) || !isObject$2(x)) {
  27968. str += ' ' + x;
  27969. } else {
  27970. str += ' ' + inspect(x);
  27971. }
  27972. }
  27973. return str;
  27974. }
  27975. // Mark that a method should not be used.
  27976. // Returns a modified function which warns once by default.
  27977. // If --no-deprecation is set, then it is a no-op.
  27978. function deprecate(fn, msg) {
  27979. // Allow for deprecating things in the process of starting up.
  27980. if (isUndefined(global.process)) {
  27981. return function() {
  27982. return deprecate(fn, msg).apply(this, arguments);
  27983. };
  27984. }
  27985. if (browser$1.noDeprecation === true) {
  27986. return fn;
  27987. }
  27988. var warned = false;
  27989. function deprecated() {
  27990. if (!warned) {
  27991. if (browser$1.throwDeprecation) {
  27992. throw new Error(msg);
  27993. } else if (browser$1.traceDeprecation) {
  27994. console.trace(msg);
  27995. } else {
  27996. console.error(msg);
  27997. }
  27998. warned = true;
  27999. }
  28000. return fn.apply(this, arguments);
  28001. }
  28002. return deprecated;
  28003. }
  28004. var debugs = {};
  28005. var debugEnviron;
  28006. function debuglog(set) {
  28007. if (isUndefined(debugEnviron))
  28008. debugEnviron = browser$1.env.NODE_DEBUG || '';
  28009. set = set.toUpperCase();
  28010. if (!debugs[set]) {
  28011. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  28012. var pid = 0;
  28013. debugs[set] = function() {
  28014. var msg = format.apply(null, arguments);
  28015. console.error('%s %d: %s', set, pid, msg);
  28016. };
  28017. } else {
  28018. debugs[set] = function() {};
  28019. }
  28020. }
  28021. return debugs[set];
  28022. }
  28023. /**
  28024. * Echos the value of a value. Trys to print the value out
  28025. * in the best way possible given the different types.
  28026. *
  28027. * @param {Object} obj The object to print out.
  28028. * @param {Object} opts Optional options object that alters the output.
  28029. */
  28030. /* legacy: obj, showHidden, depth, colors*/
  28031. function inspect(obj, opts) {
  28032. // default options
  28033. var ctx = {
  28034. seen: [],
  28035. stylize: stylizeNoColor
  28036. };
  28037. // legacy...
  28038. if (arguments.length >= 3) ctx.depth = arguments[2];
  28039. if (arguments.length >= 4) ctx.colors = arguments[3];
  28040. if (isBoolean(opts)) {
  28041. // legacy...
  28042. ctx.showHidden = opts;
  28043. } else if (opts) {
  28044. // got an "options" object
  28045. _extend(ctx, opts);
  28046. }
  28047. // set default options
  28048. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  28049. if (isUndefined(ctx.depth)) ctx.depth = 2;
  28050. if (isUndefined(ctx.colors)) ctx.colors = false;
  28051. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  28052. if (ctx.colors) ctx.stylize = stylizeWithColor;
  28053. return formatValue(ctx, obj, ctx.depth);
  28054. }
  28055. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  28056. inspect.colors = {
  28057. 'bold' : [1, 22],
  28058. 'italic' : [3, 23],
  28059. 'underline' : [4, 24],
  28060. 'inverse' : [7, 27],
  28061. 'white' : [37, 39],
  28062. 'grey' : [90, 39],
  28063. 'black' : [30, 39],
  28064. 'blue' : [34, 39],
  28065. 'cyan' : [36, 39],
  28066. 'green' : [32, 39],
  28067. 'magenta' : [35, 39],
  28068. 'red' : [31, 39],
  28069. 'yellow' : [33, 39]
  28070. };
  28071. // Don't use 'blue' not visible on cmd.exe
  28072. inspect.styles = {
  28073. 'special': 'cyan',
  28074. 'number': 'yellow',
  28075. 'boolean': 'yellow',
  28076. 'undefined': 'grey',
  28077. 'null': 'bold',
  28078. 'string': 'green',
  28079. 'date': 'magenta',
  28080. // "name": intentionally not styling
  28081. 'regexp': 'red'
  28082. };
  28083. function stylizeWithColor(str, styleType) {
  28084. var style = inspect.styles[styleType];
  28085. if (style) {
  28086. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  28087. '\u001b[' + inspect.colors[style][1] + 'm';
  28088. } else {
  28089. return str;
  28090. }
  28091. }
  28092. function stylizeNoColor(str, styleType) {
  28093. return str;
  28094. }
  28095. function arrayToHash(array) {
  28096. var hash = {};
  28097. array.forEach(function(val, idx) {
  28098. hash[val] = true;
  28099. });
  28100. return hash;
  28101. }
  28102. function formatValue(ctx, value, recurseTimes) {
  28103. // Provide a hook for user-specified inspect functions.
  28104. // Check that value is an object with an inspect function on it
  28105. if (ctx.customInspect &&
  28106. value &&
  28107. isFunction$1(value.inspect) &&
  28108. // Filter out the util module, it's inspect function is special
  28109. value.inspect !== inspect &&
  28110. // Also filter out any prototype objects using the circular check.
  28111. !(value.constructor && value.constructor.prototype === value)) {
  28112. var ret = value.inspect(recurseTimes, ctx);
  28113. if (!isString$1(ret)) {
  28114. ret = formatValue(ctx, ret, recurseTimes);
  28115. }
  28116. return ret;
  28117. }
  28118. // Primitive types cannot have properties
  28119. var primitive = formatPrimitive(ctx, value);
  28120. if (primitive) {
  28121. return primitive;
  28122. }
  28123. // Look up the keys of the object.
  28124. var keys = Object.keys(value);
  28125. var visibleKeys = arrayToHash(keys);
  28126. if (ctx.showHidden) {
  28127. keys = Object.getOwnPropertyNames(value);
  28128. }
  28129. // IE doesn't make error fields non-enumerable
  28130. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  28131. if (isError(value)
  28132. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  28133. return formatError(value);
  28134. }
  28135. // Some type of object without properties can be shortcutted.
  28136. if (keys.length === 0) {
  28137. if (isFunction$1(value)) {
  28138. var name = value.name ? ': ' + value.name : '';
  28139. return ctx.stylize('[Function' + name + ']', 'special');
  28140. }
  28141. if (isRegExp(value)) {
  28142. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  28143. }
  28144. if (isDate(value)) {
  28145. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  28146. }
  28147. if (isError(value)) {
  28148. return formatError(value);
  28149. }
  28150. }
  28151. var base = '', array = false, braces = ['{', '}'];
  28152. // Make Array say that they are Array
  28153. if (isArray$2(value)) {
  28154. array = true;
  28155. braces = ['[', ']'];
  28156. }
  28157. // Make functions say that they are functions
  28158. if (isFunction$1(value)) {
  28159. var n = value.name ? ': ' + value.name : '';
  28160. base = ' [Function' + n + ']';
  28161. }
  28162. // Make RegExps say that they are RegExps
  28163. if (isRegExp(value)) {
  28164. base = ' ' + RegExp.prototype.toString.call(value);
  28165. }
  28166. // Make dates with properties first say the date
  28167. if (isDate(value)) {
  28168. base = ' ' + Date.prototype.toUTCString.call(value);
  28169. }
  28170. // Make error with message first say the error
  28171. if (isError(value)) {
  28172. base = ' ' + formatError(value);
  28173. }
  28174. if (keys.length === 0 && (!array || value.length == 0)) {
  28175. return braces[0] + base + braces[1];
  28176. }
  28177. if (recurseTimes < 0) {
  28178. if (isRegExp(value)) {
  28179. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  28180. } else {
  28181. return ctx.stylize('[Object]', 'special');
  28182. }
  28183. }
  28184. ctx.seen.push(value);
  28185. var output;
  28186. if (array) {
  28187. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  28188. } else {
  28189. output = keys.map(function(key) {
  28190. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  28191. });
  28192. }
  28193. ctx.seen.pop();
  28194. return reduceToSingleString(output, base, braces);
  28195. }
  28196. function formatPrimitive(ctx, value) {
  28197. if (isUndefined(value))
  28198. return ctx.stylize('undefined', 'undefined');
  28199. if (isString$1(value)) {
  28200. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  28201. .replace(/'/g, "\\'")
  28202. .replace(/\\"/g, '"') + '\'';
  28203. return ctx.stylize(simple, 'string');
  28204. }
  28205. if (isNumber(value))
  28206. return ctx.stylize('' + value, 'number');
  28207. if (isBoolean(value))
  28208. return ctx.stylize('' + value, 'boolean');
  28209. // For some reason typeof null is "object", so special case here.
  28210. if (isNull(value))
  28211. return ctx.stylize('null', 'null');
  28212. }
  28213. function formatError(value) {
  28214. return '[' + Error.prototype.toString.call(value) + ']';
  28215. }
  28216. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  28217. var output = [];
  28218. for (var i = 0, l = value.length; i < l; ++i) {
  28219. if (hasOwnProperty$1(value, String(i))) {
  28220. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  28221. String(i), true));
  28222. } else {
  28223. output.push('');
  28224. }
  28225. }
  28226. keys.forEach(function(key) {
  28227. if (!key.match(/^\d+$/)) {
  28228. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  28229. key, true));
  28230. }
  28231. });
  28232. return output;
  28233. }
  28234. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  28235. var name, str, desc;
  28236. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  28237. if (desc.get) {
  28238. if (desc.set) {
  28239. str = ctx.stylize('[Getter/Setter]', 'special');
  28240. } else {
  28241. str = ctx.stylize('[Getter]', 'special');
  28242. }
  28243. } else {
  28244. if (desc.set) {
  28245. str = ctx.stylize('[Setter]', 'special');
  28246. }
  28247. }
  28248. if (!hasOwnProperty$1(visibleKeys, key)) {
  28249. name = '[' + key + ']';
  28250. }
  28251. if (!str) {
  28252. if (ctx.seen.indexOf(desc.value) < 0) {
  28253. if (isNull(recurseTimes)) {
  28254. str = formatValue(ctx, desc.value, null);
  28255. } else {
  28256. str = formatValue(ctx, desc.value, recurseTimes - 1);
  28257. }
  28258. if (str.indexOf('\n') > -1) {
  28259. if (array) {
  28260. str = str.split('\n').map(function(line) {
  28261. return ' ' + line;
  28262. }).join('\n').substr(2);
  28263. } else {
  28264. str = '\n' + str.split('\n').map(function(line) {
  28265. return ' ' + line;
  28266. }).join('\n');
  28267. }
  28268. }
  28269. } else {
  28270. str = ctx.stylize('[Circular]', 'special');
  28271. }
  28272. }
  28273. if (isUndefined(name)) {
  28274. if (array && key.match(/^\d+$/)) {
  28275. return str;
  28276. }
  28277. name = JSON.stringify('' + key);
  28278. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  28279. name = name.substr(1, name.length - 2);
  28280. name = ctx.stylize(name, 'name');
  28281. } else {
  28282. name = name.replace(/'/g, "\\'")
  28283. .replace(/\\"/g, '"')
  28284. .replace(/(^"|"$)/g, "'");
  28285. name = ctx.stylize(name, 'string');
  28286. }
  28287. }
  28288. return name + ': ' + str;
  28289. }
  28290. function reduceToSingleString(output, base, braces) {
  28291. var length = output.reduce(function(prev, cur) {
  28292. if (cur.indexOf('\n') >= 0) ;
  28293. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  28294. }, 0);
  28295. if (length > 60) {
  28296. return braces[0] +
  28297. (base === '' ? '' : base + '\n ') +
  28298. ' ' +
  28299. output.join(',\n ') +
  28300. ' ' +
  28301. braces[1];
  28302. }
  28303. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  28304. }
  28305. // NOTE: These type checking functions intentionally don't use `instanceof`
  28306. // because it is fragile and can be easily faked with `Object.create()`.
  28307. function isArray$2(ar) {
  28308. return Array.isArray(ar);
  28309. }
  28310. function isBoolean(arg) {
  28311. return typeof arg === 'boolean';
  28312. }
  28313. function isNull(arg) {
  28314. return arg === null;
  28315. }
  28316. function isNullOrUndefined(arg) {
  28317. return arg == null;
  28318. }
  28319. function isNumber(arg) {
  28320. return typeof arg === 'number';
  28321. }
  28322. function isString$1(arg) {
  28323. return typeof arg === 'string';
  28324. }
  28325. function isSymbol$1(arg) {
  28326. return typeof arg === 'symbol';
  28327. }
  28328. function isUndefined(arg) {
  28329. return arg === void 0;
  28330. }
  28331. function isRegExp(re) {
  28332. return isObject$2(re) && objectToString$1(re) === '[object RegExp]';
  28333. }
  28334. function isObject$2(arg) {
  28335. return typeof arg === 'object' && arg !== null;
  28336. }
  28337. function isDate(d) {
  28338. return isObject$2(d) && objectToString$1(d) === '[object Date]';
  28339. }
  28340. function isError(e) {
  28341. return isObject$2(e) &&
  28342. (objectToString$1(e) === '[object Error]' || e instanceof Error);
  28343. }
  28344. function isFunction$1(arg) {
  28345. return typeof arg === 'function';
  28346. }
  28347. function isPrimitive(arg) {
  28348. return arg === null ||
  28349. typeof arg === 'boolean' ||
  28350. typeof arg === 'number' ||
  28351. typeof arg === 'string' ||
  28352. typeof arg === 'symbol' || // ES6 symbol
  28353. typeof arg === 'undefined';
  28354. }
  28355. function isBuffer$1(maybeBuf) {
  28356. return Buffer.isBuffer(maybeBuf);
  28357. }
  28358. function objectToString$1(o) {
  28359. return Object.prototype.toString.call(o);
  28360. }
  28361. function pad$1(n) {
  28362. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  28363. }
  28364. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  28365. 'Oct', 'Nov', 'Dec'];
  28366. // 26 Feb 16:19:34
  28367. function timestamp() {
  28368. var d = new Date();
  28369. var time = [pad$1(d.getHours()),
  28370. pad$1(d.getMinutes()),
  28371. pad$1(d.getSeconds())].join(':');
  28372. return [d.getDate(), months[d.getMonth()], time].join(' ');
  28373. }
  28374. // log is just a thin wrapper to console.log that prepends a timestamp
  28375. function log() {
  28376. console.log('%s - %s', timestamp(), format.apply(null, arguments));
  28377. }
  28378. function _extend(origin, add) {
  28379. // Don't do anything if add isn't an object
  28380. if (!add || !isObject$2(add)) return origin;
  28381. var keys = Object.keys(add);
  28382. var i = keys.length;
  28383. while (i--) {
  28384. origin[keys[i]] = add[keys[i]];
  28385. }
  28386. return origin;
  28387. }
  28388. function hasOwnProperty$1(obj, prop) {
  28389. return Object.prototype.hasOwnProperty.call(obj, prop);
  28390. }
  28391. var _polyfillNode_util = {
  28392. inherits: inherits$1,
  28393. _extend: _extend,
  28394. log: log,
  28395. isBuffer: isBuffer$1,
  28396. isPrimitive: isPrimitive,
  28397. isFunction: isFunction$1,
  28398. isError: isError,
  28399. isDate: isDate,
  28400. isObject: isObject$2,
  28401. isRegExp: isRegExp,
  28402. isUndefined: isUndefined,
  28403. isSymbol: isSymbol$1,
  28404. isString: isString$1,
  28405. isNumber: isNumber,
  28406. isNullOrUndefined: isNullOrUndefined,
  28407. isNull: isNull,
  28408. isBoolean: isBoolean,
  28409. isArray: isArray$2,
  28410. inspect: inspect,
  28411. deprecate: deprecate,
  28412. format: format,
  28413. debuglog: debuglog
  28414. };
  28415. var _polyfillNode_util$1 = /*#__PURE__*/Object.freeze({
  28416. __proto__: null,
  28417. format: format,
  28418. deprecate: deprecate,
  28419. debuglog: debuglog,
  28420. inspect: inspect,
  28421. isArray: isArray$2,
  28422. isBoolean: isBoolean,
  28423. isNull: isNull,
  28424. isNullOrUndefined: isNullOrUndefined,
  28425. isNumber: isNumber,
  28426. isString: isString$1,
  28427. isSymbol: isSymbol$1,
  28428. isUndefined: isUndefined,
  28429. isRegExp: isRegExp,
  28430. isObject: isObject$2,
  28431. isDate: isDate,
  28432. isError: isError,
  28433. isFunction: isFunction$1,
  28434. isPrimitive: isPrimitive,
  28435. isBuffer: isBuffer$1,
  28436. log: log,
  28437. inherits: inherits$1,
  28438. _extend: _extend,
  28439. 'default': _polyfillNode_util
  28440. });
  28441. // Copyright Joyent, Inc. and other Node contributors.
  28442. //
  28443. // Permission is hereby granted, free of charge, to any person obtaining a
  28444. // copy of this software and associated documentation files (the
  28445. // "Software"), to deal in the Software without restriction, including
  28446. // without limitation the rights to use, copy, modify, merge, publish,
  28447. // distribute, sublicense, and/or sell copies of the Software, and to permit
  28448. // persons to whom the Software is furnished to do so, subject to the
  28449. // following conditions:
  28450. //
  28451. // The above copyright notice and this permission notice shall be included
  28452. // in all copies or substantial portions of the Software.
  28453. //
  28454. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  28455. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  28456. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  28457. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  28458. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  28459. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  28460. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  28461. // If obj.hasOwnProperty has been overridden, then calling
  28462. // obj.hasOwnProperty(prop) will break.
  28463. // See: https://github.com/joyent/node/issues/1707
  28464. function hasOwnProperty$2(obj, prop) {
  28465. return Object.prototype.hasOwnProperty.call(obj, prop);
  28466. }
  28467. var isArray$3 = Array.isArray || function (xs) {
  28468. return Object.prototype.toString.call(xs) === '[object Array]';
  28469. };
  28470. function stringifyPrimitive(v) {
  28471. switch (typeof v) {
  28472. case 'string':
  28473. return v;
  28474. case 'boolean':
  28475. return v ? 'true' : 'false';
  28476. case 'number':
  28477. return isFinite(v) ? v : '';
  28478. default:
  28479. return '';
  28480. }
  28481. }
  28482. function stringify (obj, sep, eq, name) {
  28483. sep = sep || '&';
  28484. eq = eq || '=';
  28485. if (obj === null) {
  28486. obj = undefined;
  28487. }
  28488. if (typeof obj === 'object') {
  28489. return map$1(objectKeys(obj), function(k) {
  28490. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  28491. if (isArray$3(obj[k])) {
  28492. return map$1(obj[k], function(v) {
  28493. return ks + encodeURIComponent(stringifyPrimitive(v));
  28494. }).join(sep);
  28495. } else {
  28496. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  28497. }
  28498. }).join(sep);
  28499. }
  28500. if (!name) return '';
  28501. return encodeURIComponent(stringifyPrimitive(name)) + eq +
  28502. encodeURIComponent(stringifyPrimitive(obj));
  28503. }
  28504. function map$1 (xs, f) {
  28505. if (xs.map) return xs.map(f);
  28506. var res = [];
  28507. for (var i = 0; i < xs.length; i++) {
  28508. res.push(f(xs[i], i));
  28509. }
  28510. return res;
  28511. }
  28512. var objectKeys = Object.keys || function (obj) {
  28513. var res = [];
  28514. for (var key in obj) {
  28515. if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
  28516. }
  28517. return res;
  28518. };
  28519. function parse$2(qs, sep, eq, options) {
  28520. sep = sep || '&';
  28521. eq = eq || '=';
  28522. var obj = {};
  28523. if (typeof qs !== 'string' || qs.length === 0) {
  28524. return obj;
  28525. }
  28526. var regexp = /\+/g;
  28527. qs = qs.split(sep);
  28528. var maxKeys = 1000;
  28529. if (options && typeof options.maxKeys === 'number') {
  28530. maxKeys = options.maxKeys;
  28531. }
  28532. var len = qs.length;
  28533. // maxKeys <= 0 means that we should not limit keys count
  28534. if (maxKeys > 0 && len > maxKeys) {
  28535. len = maxKeys;
  28536. }
  28537. for (var i = 0; i < len; ++i) {
  28538. var x = qs[i].replace(regexp, '%20'),
  28539. idx = x.indexOf(eq),
  28540. kstr, vstr, k, v;
  28541. if (idx >= 0) {
  28542. kstr = x.substr(0, idx);
  28543. vstr = x.substr(idx + 1);
  28544. } else {
  28545. kstr = x;
  28546. vstr = '';
  28547. }
  28548. k = decodeURIComponent(kstr);
  28549. v = decodeURIComponent(vstr);
  28550. if (!hasOwnProperty$2(obj, k)) {
  28551. obj[k] = v;
  28552. } else if (isArray$3(obj[k])) {
  28553. obj[k].push(v);
  28554. } else {
  28555. obj[k] = [obj[k], v];
  28556. }
  28557. }
  28558. return obj;
  28559. }
  28560. // Copyright Joyent, Inc. and other Node contributors.
  28561. var _polyfillNode_url = {
  28562. parse: urlParse,
  28563. resolve: urlResolve,
  28564. resolveObject: urlResolveObject,
  28565. format: urlFormat,
  28566. Url: Url
  28567. };
  28568. function Url() {
  28569. this.protocol = null;
  28570. this.slashes = null;
  28571. this.auth = null;
  28572. this.host = null;
  28573. this.port = null;
  28574. this.hostname = null;
  28575. this.hash = null;
  28576. this.search = null;
  28577. this.query = null;
  28578. this.pathname = null;
  28579. this.path = null;
  28580. this.href = null;
  28581. }
  28582. // Reference: RFC 3986, RFC 1808, RFC 2396
  28583. // define these here so at least they only have to be
  28584. // compiled once on the first module load.
  28585. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  28586. portPattern = /:[0-9]*$/,
  28587. // Special case for a simple path URL
  28588. simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
  28589. // RFC 2396: characters reserved for delimiting URLs.
  28590. // We actually just auto-escape these.
  28591. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  28592. // RFC 2396: characters not allowed for various reasons.
  28593. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  28594. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  28595. autoEscape = ['\''].concat(unwise),
  28596. // Characters that are never ever allowed in a hostname.
  28597. // Note that any invalid chars are also handled, but these
  28598. // are the ones that are *expected* to be seen, so we fast-path
  28599. // them.
  28600. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  28601. hostEndingChars = ['/', '?', '#'],
  28602. hostnameMaxLen = 255,
  28603. hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
  28604. hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
  28605. // protocols that can allow "unsafe" and "unwise" chars.
  28606. unsafeProtocol = {
  28607. 'javascript': true,
  28608. 'javascript:': true
  28609. },
  28610. // protocols that never have a hostname.
  28611. hostlessProtocol = {
  28612. 'javascript': true,
  28613. 'javascript:': true
  28614. },
  28615. // protocols that always contain a // bit.
  28616. slashedProtocol = {
  28617. 'http': true,
  28618. 'https': true,
  28619. 'ftp': true,
  28620. 'gopher': true,
  28621. 'file': true,
  28622. 'http:': true,
  28623. 'https:': true,
  28624. 'ftp:': true,
  28625. 'gopher:': true,
  28626. 'file:': true
  28627. };
  28628. function urlParse(url, parseQueryString, slashesDenoteHost) {
  28629. if (url && isObject$2(url) && url instanceof Url) return url;
  28630. var u = new Url;
  28631. u.parse(url, parseQueryString, slashesDenoteHost);
  28632. return u;
  28633. }
  28634. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  28635. return parse$3(this, url, parseQueryString, slashesDenoteHost);
  28636. };
  28637. function parse$3(self, url, parseQueryString, slashesDenoteHost) {
  28638. if (!isString$1(url)) {
  28639. throw new TypeError('Parameter \'url\' must be a string, not ' + typeof url);
  28640. }
  28641. // Copy chrome, IE, opera backslash-handling behavior.
  28642. // Back slashes before the query string get converted to forward slashes
  28643. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  28644. var queryIndex = url.indexOf('?'),
  28645. splitter =
  28646. (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
  28647. uSplit = url.split(splitter),
  28648. slashRegex = /\\/g;
  28649. uSplit[0] = uSplit[0].replace(slashRegex, '/');
  28650. url = uSplit.join(splitter);
  28651. var rest = url;
  28652. // trim before proceeding.
  28653. // This is to support parse stuff like " http://foo.com \n"
  28654. rest = rest.trim();
  28655. if (!slashesDenoteHost && url.split('#').length === 1) {
  28656. // Try fast path regexp
  28657. var simplePath = simplePathPattern.exec(rest);
  28658. if (simplePath) {
  28659. self.path = rest;
  28660. self.href = rest;
  28661. self.pathname = simplePath[1];
  28662. if (simplePath[2]) {
  28663. self.search = simplePath[2];
  28664. if (parseQueryString) {
  28665. self.query = parse$2(self.search.substr(1));
  28666. } else {
  28667. self.query = self.search.substr(1);
  28668. }
  28669. } else if (parseQueryString) {
  28670. self.search = '';
  28671. self.query = {};
  28672. }
  28673. return self;
  28674. }
  28675. }
  28676. var proto = protocolPattern.exec(rest);
  28677. if (proto) {
  28678. proto = proto[0];
  28679. var lowerProto = proto.toLowerCase();
  28680. self.protocol = lowerProto;
  28681. rest = rest.substr(proto.length);
  28682. }
  28683. // figure out if it's got a host
  28684. // user@server is *always* interpreted as a hostname, and url
  28685. // resolution will treat //foo/bar as host=foo,path=bar because that's
  28686. // how the browser resolves relative URLs.
  28687. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  28688. var slashes = rest.substr(0, 2) === '//';
  28689. if (slashes && !(proto && hostlessProtocol[proto])) {
  28690. rest = rest.substr(2);
  28691. self.slashes = true;
  28692. }
  28693. }
  28694. var i, hec, l, p;
  28695. if (!hostlessProtocol[proto] &&
  28696. (slashes || (proto && !slashedProtocol[proto]))) {
  28697. // there's a hostname.
  28698. // the first instance of /, ?, ;, or # ends the host.
  28699. //
  28700. // If there is an @ in the hostname, then non-host chars *are* allowed
  28701. // to the left of the last @ sign, unless some host-ending character
  28702. // comes *before* the @-sign.
  28703. // URLs are obnoxious.
  28704. //
  28705. // ex:
  28706. // http://a@b@c/ => user:a@b host:c
  28707. // http://a@b?@c => user:a host:c path:/?@c
  28708. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  28709. // Review our test case against browsers more comprehensively.
  28710. // find the first instance of any hostEndingChars
  28711. var hostEnd = -1;
  28712. for (i = 0; i < hostEndingChars.length; i++) {
  28713. hec = rest.indexOf(hostEndingChars[i]);
  28714. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  28715. hostEnd = hec;
  28716. }
  28717. // at this point, either we have an explicit point where the
  28718. // auth portion cannot go past, or the last @ char is the decider.
  28719. var auth, atSign;
  28720. if (hostEnd === -1) {
  28721. // atSign can be anywhere.
  28722. atSign = rest.lastIndexOf('@');
  28723. } else {
  28724. // atSign must be in auth portion.
  28725. // http://a@b/c@d => host:b auth:a path:/c@d
  28726. atSign = rest.lastIndexOf('@', hostEnd);
  28727. }
  28728. // Now we have a portion which is definitely the auth.
  28729. // Pull that off.
  28730. if (atSign !== -1) {
  28731. auth = rest.slice(0, atSign);
  28732. rest = rest.slice(atSign + 1);
  28733. self.auth = decodeURIComponent(auth);
  28734. }
  28735. // the host is the remaining to the left of the first non-host char
  28736. hostEnd = -1;
  28737. for (i = 0; i < nonHostChars.length; i++) {
  28738. hec = rest.indexOf(nonHostChars[i]);
  28739. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  28740. hostEnd = hec;
  28741. }
  28742. // if we still have not hit it, then the entire thing is a host.
  28743. if (hostEnd === -1)
  28744. hostEnd = rest.length;
  28745. self.host = rest.slice(0, hostEnd);
  28746. rest = rest.slice(hostEnd);
  28747. // pull out port.
  28748. parseHost(self);
  28749. // we've indicated that there is a hostname,
  28750. // so even if it's empty, it has to be present.
  28751. self.hostname = self.hostname || '';
  28752. // if hostname begins with [ and ends with ]
  28753. // assume that it's an IPv6 address.
  28754. var ipv6Hostname = self.hostname[0] === '[' &&
  28755. self.hostname[self.hostname.length - 1] === ']';
  28756. // validate a little.
  28757. if (!ipv6Hostname) {
  28758. var hostparts = self.hostname.split(/\./);
  28759. for (i = 0, l = hostparts.length; i < l; i++) {
  28760. var part = hostparts[i];
  28761. if (!part) continue;
  28762. if (!part.match(hostnamePartPattern)) {
  28763. var newpart = '';
  28764. for (var j = 0, k = part.length; j < k; j++) {
  28765. if (part.charCodeAt(j) > 127) {
  28766. // we replace non-ASCII char with a temporary placeholder
  28767. // we need this to make sure size of hostname is not
  28768. // broken by replacing non-ASCII by nothing
  28769. newpart += 'x';
  28770. } else {
  28771. newpart += part[j];
  28772. }
  28773. }
  28774. // we test again with ASCII char only
  28775. if (!newpart.match(hostnamePartPattern)) {
  28776. var validParts = hostparts.slice(0, i);
  28777. var notHost = hostparts.slice(i + 1);
  28778. var bit = part.match(hostnamePartStart);
  28779. if (bit) {
  28780. validParts.push(bit[1]);
  28781. notHost.unshift(bit[2]);
  28782. }
  28783. if (notHost.length) {
  28784. rest = '/' + notHost.join('.') + rest;
  28785. }
  28786. self.hostname = validParts.join('.');
  28787. break;
  28788. }
  28789. }
  28790. }
  28791. }
  28792. if (self.hostname.length > hostnameMaxLen) {
  28793. self.hostname = '';
  28794. } else {
  28795. // hostnames are always lower case.
  28796. self.hostname = self.hostname.toLowerCase();
  28797. }
  28798. if (!ipv6Hostname) {
  28799. // IDNA Support: Returns a punycoded representation of "domain".
  28800. // It only converts parts of the domain name that
  28801. // have non-ASCII characters, i.e. it doesn't matter if
  28802. // you call it with a domain that already is ASCII-only.
  28803. self.hostname = toASCII(self.hostname);
  28804. }
  28805. p = self.port ? ':' + self.port : '';
  28806. var h = self.hostname || '';
  28807. self.host = h + p;
  28808. self.href += self.host;
  28809. // strip [ and ] from the hostname
  28810. // the host field still retains them, though
  28811. if (ipv6Hostname) {
  28812. self.hostname = self.hostname.substr(1, self.hostname.length - 2);
  28813. if (rest[0] !== '/') {
  28814. rest = '/' + rest;
  28815. }
  28816. }
  28817. }
  28818. // now rest is set to the post-host stuff.
  28819. // chop off any delim chars.
  28820. if (!unsafeProtocol[lowerProto]) {
  28821. // First, make 100% sure that any "autoEscape" chars get
  28822. // escaped, even if encodeURIComponent doesn't think they
  28823. // need to be.
  28824. for (i = 0, l = autoEscape.length; i < l; i++) {
  28825. var ae = autoEscape[i];
  28826. if (rest.indexOf(ae) === -1)
  28827. continue;
  28828. var esc = encodeURIComponent(ae);
  28829. if (esc === ae) {
  28830. esc = escape(ae);
  28831. }
  28832. rest = rest.split(ae).join(esc);
  28833. }
  28834. }
  28835. // chop off from the tail first.
  28836. var hash = rest.indexOf('#');
  28837. if (hash !== -1) {
  28838. // got a fragment string.
  28839. self.hash = rest.substr(hash);
  28840. rest = rest.slice(0, hash);
  28841. }
  28842. var qm = rest.indexOf('?');
  28843. if (qm !== -1) {
  28844. self.search = rest.substr(qm);
  28845. self.query = rest.substr(qm + 1);
  28846. if (parseQueryString) {
  28847. self.query = parse$2(self.query);
  28848. }
  28849. rest = rest.slice(0, qm);
  28850. } else if (parseQueryString) {
  28851. // no query string, but parseQueryString still requested
  28852. self.search = '';
  28853. self.query = {};
  28854. }
  28855. if (rest) self.pathname = rest;
  28856. if (slashedProtocol[lowerProto] &&
  28857. self.hostname && !self.pathname) {
  28858. self.pathname = '/';
  28859. }
  28860. //to support http.request
  28861. if (self.pathname || self.search) {
  28862. p = self.pathname || '';
  28863. var s = self.search || '';
  28864. self.path = p + s;
  28865. }
  28866. // finally, reconstruct the href based on what has been validated.
  28867. self.href = format$1(self);
  28868. return self;
  28869. }
  28870. // format a parsed object into a url string
  28871. function urlFormat(obj) {
  28872. // ensure it's an object, and not a string url.
  28873. // If it's an obj, this is a no-op.
  28874. // this way, you can call url_format() on strings
  28875. // to clean up potentially wonky urls.
  28876. if (isString$1(obj)) obj = parse$3({}, obj);
  28877. return format$1(obj);
  28878. }
  28879. function format$1(self) {
  28880. var auth = self.auth || '';
  28881. if (auth) {
  28882. auth = encodeURIComponent(auth);
  28883. auth = auth.replace(/%3A/i, ':');
  28884. auth += '@';
  28885. }
  28886. var protocol = self.protocol || '',
  28887. pathname = self.pathname || '',
  28888. hash = self.hash || '',
  28889. host = false,
  28890. query = '';
  28891. if (self.host) {
  28892. host = auth + self.host;
  28893. } else if (self.hostname) {
  28894. host = auth + (self.hostname.indexOf(':') === -1 ?
  28895. self.hostname :
  28896. '[' + this.hostname + ']');
  28897. if (self.port) {
  28898. host += ':' + self.port;
  28899. }
  28900. }
  28901. if (self.query &&
  28902. isObject$2(self.query) &&
  28903. Object.keys(self.query).length) {
  28904. query = stringify(self.query);
  28905. }
  28906. var search = self.search || (query && ('?' + query)) || '';
  28907. if (protocol && protocol.substr(-1) !== ':') protocol += ':';
  28908. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  28909. // unless they had them to begin with.
  28910. if (self.slashes ||
  28911. (!protocol || slashedProtocol[protocol]) && host !== false) {
  28912. host = '//' + (host || '');
  28913. if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  28914. } else if (!host) {
  28915. host = '';
  28916. }
  28917. if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  28918. if (search && search.charAt(0) !== '?') search = '?' + search;
  28919. pathname = pathname.replace(/[?#]/g, function(match) {
  28920. return encodeURIComponent(match);
  28921. });
  28922. search = search.replace('#', '%23');
  28923. return protocol + host + pathname + search + hash;
  28924. }
  28925. Url.prototype.format = function() {
  28926. return format$1(this);
  28927. };
  28928. function urlResolve(source, relative) {
  28929. return urlParse(source, false, true).resolve(relative);
  28930. }
  28931. Url.prototype.resolve = function(relative) {
  28932. return this.resolveObject(urlParse(relative, false, true)).format();
  28933. };
  28934. function urlResolveObject(source, relative) {
  28935. if (!source) return relative;
  28936. return urlParse(source, false, true).resolveObject(relative);
  28937. }
  28938. Url.prototype.resolveObject = function(relative) {
  28939. if (isString$1(relative)) {
  28940. var rel = new Url();
  28941. rel.parse(relative, false, true);
  28942. relative = rel;
  28943. }
  28944. var result = new Url();
  28945. var tkeys = Object.keys(this);
  28946. for (var tk = 0; tk < tkeys.length; tk++) {
  28947. var tkey = tkeys[tk];
  28948. result[tkey] = this[tkey];
  28949. }
  28950. // hash is always overridden, no matter what.
  28951. // even href="" will remove it.
  28952. result.hash = relative.hash;
  28953. // if the relative url is empty, then there's nothing left to do here.
  28954. if (relative.href === '') {
  28955. result.href = result.format();
  28956. return result;
  28957. }
  28958. // hrefs like //foo/bar always cut to the protocol.
  28959. if (relative.slashes && !relative.protocol) {
  28960. // take everything except the protocol from relative
  28961. var rkeys = Object.keys(relative);
  28962. for (var rk = 0; rk < rkeys.length; rk++) {
  28963. var rkey = rkeys[rk];
  28964. if (rkey !== 'protocol')
  28965. result[rkey] = relative[rkey];
  28966. }
  28967. //urlParse appends trailing / to urls like http://www.example.com
  28968. if (slashedProtocol[result.protocol] &&
  28969. result.hostname && !result.pathname) {
  28970. result.path = result.pathname = '/';
  28971. }
  28972. result.href = result.format();
  28973. return result;
  28974. }
  28975. var relPath;
  28976. if (relative.protocol && relative.protocol !== result.protocol) {
  28977. // if it's a known url protocol, then changing
  28978. // the protocol does weird things
  28979. // first, if it's not file:, then we MUST have a host,
  28980. // and if there was a path
  28981. // to begin with, then we MUST have a path.
  28982. // if it is file:, then the host is dropped,
  28983. // because that's known to be hostless.
  28984. // anything else is assumed to be absolute.
  28985. if (!slashedProtocol[relative.protocol]) {
  28986. var keys = Object.keys(relative);
  28987. for (var v = 0; v < keys.length; v++) {
  28988. var k = keys[v];
  28989. result[k] = relative[k];
  28990. }
  28991. result.href = result.format();
  28992. return result;
  28993. }
  28994. result.protocol = relative.protocol;
  28995. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  28996. relPath = (relative.pathname || '').split('/');
  28997. while (relPath.length && !(relative.host = relPath.shift()));
  28998. if (!relative.host) relative.host = '';
  28999. if (!relative.hostname) relative.hostname = '';
  29000. if (relPath[0] !== '') relPath.unshift('');
  29001. if (relPath.length < 2) relPath.unshift('');
  29002. result.pathname = relPath.join('/');
  29003. } else {
  29004. result.pathname = relative.pathname;
  29005. }
  29006. result.search = relative.search;
  29007. result.query = relative.query;
  29008. result.host = relative.host || '';
  29009. result.auth = relative.auth;
  29010. result.hostname = relative.hostname || relative.host;
  29011. result.port = relative.port;
  29012. // to support http.request
  29013. if (result.pathname || result.search) {
  29014. var p = result.pathname || '';
  29015. var s = result.search || '';
  29016. result.path = p + s;
  29017. }
  29018. result.slashes = result.slashes || relative.slashes;
  29019. result.href = result.format();
  29020. return result;
  29021. }
  29022. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  29023. isRelAbs = (
  29024. relative.host ||
  29025. relative.pathname && relative.pathname.charAt(0) === '/'
  29026. ),
  29027. mustEndAbs = (isRelAbs || isSourceAbs ||
  29028. (result.host && relative.pathname)),
  29029. removeAllDots = mustEndAbs,
  29030. srcPath = result.pathname && result.pathname.split('/') || [],
  29031. psychotic = result.protocol && !slashedProtocol[result.protocol];
  29032. relPath = relative.pathname && relative.pathname.split('/') || [];
  29033. // if the url is a non-slashed url, then relative
  29034. // links like ../.. should be able
  29035. // to crawl up to the hostname, as well. This is strange.
  29036. // result.protocol has already been set by now.
  29037. // Later on, put the first path part into the host field.
  29038. if (psychotic) {
  29039. result.hostname = '';
  29040. result.port = null;
  29041. if (result.host) {
  29042. if (srcPath[0] === '') srcPath[0] = result.host;
  29043. else srcPath.unshift(result.host);
  29044. }
  29045. result.host = '';
  29046. if (relative.protocol) {
  29047. relative.hostname = null;
  29048. relative.port = null;
  29049. if (relative.host) {
  29050. if (relPath[0] === '') relPath[0] = relative.host;
  29051. else relPath.unshift(relative.host);
  29052. }
  29053. relative.host = null;
  29054. }
  29055. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  29056. }
  29057. var authInHost;
  29058. if (isRelAbs) {
  29059. // it's absolute.
  29060. result.host = (relative.host || relative.host === '') ?
  29061. relative.host : result.host;
  29062. result.hostname = (relative.hostname || relative.hostname === '') ?
  29063. relative.hostname : result.hostname;
  29064. result.search = relative.search;
  29065. result.query = relative.query;
  29066. srcPath = relPath;
  29067. // fall through to the dot-handling below.
  29068. } else if (relPath.length) {
  29069. // it's relative
  29070. // throw away the existing file, and take the new path instead.
  29071. if (!srcPath) srcPath = [];
  29072. srcPath.pop();
  29073. srcPath = srcPath.concat(relPath);
  29074. result.search = relative.search;
  29075. result.query = relative.query;
  29076. } else if (!isNullOrUndefined(relative.search)) {
  29077. // just pull out the search.
  29078. // like href='?foo'.
  29079. // Put this after the other two cases because it simplifies the booleans
  29080. if (psychotic) {
  29081. result.hostname = result.host = srcPath.shift();
  29082. //occationaly the auth can get stuck only in host
  29083. //this especially happens in cases like
  29084. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  29085. authInHost = result.host && result.host.indexOf('@') > 0 ?
  29086. result.host.split('@') : false;
  29087. if (authInHost) {
  29088. result.auth = authInHost.shift();
  29089. result.host = result.hostname = authInHost.shift();
  29090. }
  29091. }
  29092. result.search = relative.search;
  29093. result.query = relative.query;
  29094. //to support http.request
  29095. if (!isNull(result.pathname) || !isNull(result.search)) {
  29096. result.path = (result.pathname ? result.pathname : '') +
  29097. (result.search ? result.search : '');
  29098. }
  29099. result.href = result.format();
  29100. return result;
  29101. }
  29102. if (!srcPath.length) {
  29103. // no path at all. easy.
  29104. // we've already handled the other stuff above.
  29105. result.pathname = null;
  29106. //to support http.request
  29107. if (result.search) {
  29108. result.path = '/' + result.search;
  29109. } else {
  29110. result.path = null;
  29111. }
  29112. result.href = result.format();
  29113. return result;
  29114. }
  29115. // if a url ENDs in . or .., then it must get a trailing slash.
  29116. // however, if it ends in anything else non-slashy,
  29117. // then it must NOT get a trailing slash.
  29118. var last = srcPath.slice(-1)[0];
  29119. var hasTrailingSlash = (
  29120. (result.host || relative.host || srcPath.length > 1) &&
  29121. (last === '.' || last === '..') || last === '');
  29122. // strip single dots, resolve double dots to parent dir
  29123. // if the path tries to go above the root, `up` ends up > 0
  29124. var up = 0;
  29125. for (var i = srcPath.length; i >= 0; i--) {
  29126. last = srcPath[i];
  29127. if (last === '.') {
  29128. srcPath.splice(i, 1);
  29129. } else if (last === '..') {
  29130. srcPath.splice(i, 1);
  29131. up++;
  29132. } else if (up) {
  29133. srcPath.splice(i, 1);
  29134. up--;
  29135. }
  29136. }
  29137. // if the path is allowed to go above the root, restore leading ..s
  29138. if (!mustEndAbs && !removeAllDots) {
  29139. for (; up--; up) {
  29140. srcPath.unshift('..');
  29141. }
  29142. }
  29143. if (mustEndAbs && srcPath[0] !== '' &&
  29144. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  29145. srcPath.unshift('');
  29146. }
  29147. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  29148. srcPath.push('');
  29149. }
  29150. var isAbsolute = srcPath[0] === '' ||
  29151. (srcPath[0] && srcPath[0].charAt(0) === '/');
  29152. // put the host back
  29153. if (psychotic) {
  29154. result.hostname = result.host = isAbsolute ? '' :
  29155. srcPath.length ? srcPath.shift() : '';
  29156. //occationaly the auth can get stuck only in host
  29157. //this especially happens in cases like
  29158. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  29159. authInHost = result.host && result.host.indexOf('@') > 0 ?
  29160. result.host.split('@') : false;
  29161. if (authInHost) {
  29162. result.auth = authInHost.shift();
  29163. result.host = result.hostname = authInHost.shift();
  29164. }
  29165. }
  29166. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  29167. if (mustEndAbs && !isAbsolute) {
  29168. srcPath.unshift('');
  29169. }
  29170. if (!srcPath.length) {
  29171. result.pathname = null;
  29172. result.path = null;
  29173. } else {
  29174. result.pathname = srcPath.join('/');
  29175. }
  29176. //to support request.http
  29177. if (!isNull(result.pathname) || !isNull(result.search)) {
  29178. result.path = (result.pathname ? result.pathname : '') +
  29179. (result.search ? result.search : '');
  29180. }
  29181. result.auth = relative.auth || result.auth;
  29182. result.slashes = result.slashes || relative.slashes;
  29183. result.href = result.format();
  29184. return result;
  29185. };
  29186. Url.prototype.parseHost = function() {
  29187. return parseHost(this);
  29188. };
  29189. function parseHost(self) {
  29190. var host = self.host;
  29191. var port = portPattern.exec(host);
  29192. if (port) {
  29193. port = port[0];
  29194. if (port !== ':') {
  29195. self.port = port.substr(1);
  29196. }
  29197. host = host.substr(0, host.length - port.length);
  29198. }
  29199. if (host) self.hostname = host;
  29200. }
  29201. var _polyfillNode_url$1 = /*#__PURE__*/Object.freeze({
  29202. __proto__: null,
  29203. parse: urlParse,
  29204. resolve: urlResolve,
  29205. resolveObject: urlResolveObject,
  29206. format: urlFormat,
  29207. 'default': _polyfillNode_url,
  29208. Url: Url
  29209. });
  29210. function isRelativeUrl(url) {
  29211. const firstChar = url.charAt(0);
  29212. return firstChar === '.' || firstChar === '~' || firstChar === '@';
  29213. }
  29214. const externalRE = /^(https?:)?\/\//;
  29215. function isExternalUrl(url) {
  29216. return externalRE.test(url);
  29217. }
  29218. const dataUrlRE = /^\s*data:/i;
  29219. function isDataUrl(url) {
  29220. return dataUrlRE.test(url);
  29221. }
  29222. /**
  29223. * Parses string url into URL object.
  29224. */
  29225. function parseUrl(url) {
  29226. const firstChar = url.charAt(0);
  29227. if (firstChar === '~') {
  29228. const secondChar = url.charAt(1);
  29229. url = url.slice(secondChar === '/' ? 2 : 1);
  29230. }
  29231. return parseUriParts(url);
  29232. }
  29233. /**
  29234. * vuejs/component-compiler-utils#22 Support uri fragment in transformed require
  29235. * @param urlString an url as a string
  29236. */
  29237. function parseUriParts(urlString) {
  29238. // A TypeError is thrown if urlString is not a string
  29239. // @see https://nodejs.org/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost
  29240. return urlParse(isString(urlString) ? urlString : '', false, true);
  29241. }
  29242. const defaultAssetUrlOptions = {
  29243. base: null,
  29244. includeAbsolute: false,
  29245. tags: {
  29246. video: ['src', 'poster'],
  29247. source: ['src'],
  29248. img: ['src'],
  29249. image: ['xlink:href', 'href'],
  29250. use: ['xlink:href', 'href']
  29251. }
  29252. };
  29253. const normalizeOptions = (options) => {
  29254. if (Object.keys(options).some(key => isArray(options[key]))) {
  29255. // legacy option format which directly passes in tags config
  29256. return Object.assign(Object.assign({}, defaultAssetUrlOptions), { tags: options });
  29257. }
  29258. return Object.assign(Object.assign({}, defaultAssetUrlOptions), options);
  29259. };
  29260. const createAssetUrlTransformWithOptions = (options) => {
  29261. return (node, context) => transformAssetUrl(node, context, options);
  29262. };
  29263. /**
  29264. * A `@vue/compiler-core` plugin that transforms relative asset urls into
  29265. * either imports or absolute urls.
  29266. *
  29267. * ``` js
  29268. * // Before
  29269. * createVNode('img', { src: './logo.png' })
  29270. *
  29271. * // After
  29272. * import _imports_0 from './logo.png'
  29273. * createVNode('img', { src: _imports_0 })
  29274. * ```
  29275. */
  29276. const transformAssetUrl = (node, context, options = defaultAssetUrlOptions) => {
  29277. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  29278. if (!node.props.length) {
  29279. return;
  29280. }
  29281. const tags = options.tags || defaultAssetUrlOptions.tags;
  29282. const attrs = tags[node.tag];
  29283. const wildCardAttrs = tags['*'];
  29284. if (!attrs && !wildCardAttrs) {
  29285. return;
  29286. }
  29287. const assetAttrs = (attrs || []).concat(wildCardAttrs || []);
  29288. node.props.forEach((attr, index) => {
  29289. if (attr.type !== 6 /* NodeTypes.ATTRIBUTE */ ||
  29290. !assetAttrs.includes(attr.name) ||
  29291. !attr.value ||
  29292. isExternalUrl(attr.value.content) ||
  29293. isDataUrl(attr.value.content) ||
  29294. attr.value.content[0] === '#' ||
  29295. (!options.includeAbsolute && !isRelativeUrl(attr.value.content))) {
  29296. return;
  29297. }
  29298. const url = parseUrl(attr.value.content);
  29299. if (options.base && attr.value.content[0] === '.') {
  29300. // explicit base - directly rewrite relative urls into absolute url
  29301. // to avoid generating extra imports
  29302. // Allow for full hostnames provided in options.base
  29303. const base = parseUrl(options.base);
  29304. const protocol = base.protocol || '';
  29305. const host = base.host ? protocol + '//' + base.host : '';
  29306. const basePath = base.path || '/';
  29307. // when packaged in the browser, path will be using the posix-
  29308. // only version provided by rollup-plugin-node-builtins.
  29309. attr.value.content =
  29310. host +
  29311. (path.posix || path).join(basePath, url.path + (url.hash || ''));
  29312. return;
  29313. }
  29314. // otherwise, transform the url into an import.
  29315. // this assumes a bundler will resolve the import into the correct
  29316. // absolute url (e.g. webpack file-loader)
  29317. const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context);
  29318. node.props[index] = {
  29319. type: 7 /* NodeTypes.DIRECTIVE */,
  29320. name: 'bind',
  29321. arg: createSimpleExpression(attr.name, true, attr.loc),
  29322. exp,
  29323. modifiers: [],
  29324. loc: attr.loc
  29325. };
  29326. });
  29327. }
  29328. };
  29329. function getImportsExpressionExp(path, hash, loc, context) {
  29330. if (path) {
  29331. let name;
  29332. let exp;
  29333. const existingIndex = context.imports.findIndex(i => i.path === path);
  29334. if (existingIndex > -1) {
  29335. name = `_imports_${existingIndex}`;
  29336. exp = context.imports[existingIndex].exp;
  29337. }
  29338. else {
  29339. name = `_imports_${context.imports.length}`;
  29340. exp = createSimpleExpression(name, false, loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  29341. context.imports.push({ exp, path });
  29342. }
  29343. if (!hash) {
  29344. return exp;
  29345. }
  29346. const hashExp = `${name} + '${hash}'`;
  29347. const finalExp = createSimpleExpression(hashExp, false, loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  29348. if (!context.hoistStatic) {
  29349. return finalExp;
  29350. }
  29351. const existingHoistIndex = context.hoists.findIndex(h => {
  29352. return (h &&
  29353. h.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  29354. !h.isStatic &&
  29355. h.content === hashExp);
  29356. });
  29357. if (existingHoistIndex > -1) {
  29358. return createSimpleExpression(`_hoisted_${existingHoistIndex + 1}`, false, loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  29359. }
  29360. return context.hoist(finalExp);
  29361. }
  29362. else {
  29363. return createSimpleExpression(`''`, false, loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  29364. }
  29365. }
  29366. const srcsetTags = ['img', 'source'];
  29367. // http://w3c.github.io/html/semantics-embedded-content.html#ref-for-image-candidate-string-5
  29368. const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
  29369. const createSrcsetTransformWithOptions = (options) => {
  29370. return (node, context) => transformSrcset(node, context, options);
  29371. };
  29372. const transformSrcset = (node, context, options = defaultAssetUrlOptions) => {
  29373. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  29374. if (srcsetTags.includes(node.tag) && node.props.length) {
  29375. node.props.forEach((attr, index) => {
  29376. if (attr.name === 'srcset' && attr.type === 6 /* NodeTypes.ATTRIBUTE */) {
  29377. if (!attr.value)
  29378. return;
  29379. const value = attr.value.content;
  29380. if (!value)
  29381. return;
  29382. const imageCandidates = value.split(',').map(s => {
  29383. // The attribute value arrives here with all whitespace, except
  29384. // normal spaces, represented by escape sequences
  29385. const [url, descriptor] = s
  29386. .replace(escapedSpaceCharacters, ' ')
  29387. .trim()
  29388. .split(' ', 2);
  29389. return { url, descriptor };
  29390. });
  29391. // data urls contains comma after the encoding so we need to re-merge
  29392. // them
  29393. for (let i = 0; i < imageCandidates.length; i++) {
  29394. const { url } = imageCandidates[i];
  29395. if (isDataUrl(url)) {
  29396. imageCandidates[i + 1].url =
  29397. url + ',' + imageCandidates[i + 1].url;
  29398. imageCandidates.splice(i, 1);
  29399. }
  29400. }
  29401. const shouldProcessUrl = (url) => {
  29402. return (!isExternalUrl(url) &&
  29403. !isDataUrl(url) &&
  29404. (options.includeAbsolute || isRelativeUrl(url)));
  29405. };
  29406. // When srcset does not contain any qualified URLs, skip transforming
  29407. if (!imageCandidates.some(({ url }) => shouldProcessUrl(url))) {
  29408. return;
  29409. }
  29410. if (options.base) {
  29411. const base = options.base;
  29412. const set = [];
  29413. let needImportTransform = false;
  29414. imageCandidates.forEach(candidate => {
  29415. let { url, descriptor } = candidate;
  29416. descriptor = descriptor ? ` ${descriptor}` : ``;
  29417. if (url[0] === '.') {
  29418. candidate.url = (path.posix || path).join(base, url);
  29419. set.push(candidate.url + descriptor);
  29420. }
  29421. else if (shouldProcessUrl(url)) {
  29422. needImportTransform = true;
  29423. }
  29424. else {
  29425. set.push(url + descriptor);
  29426. }
  29427. });
  29428. if (!needImportTransform) {
  29429. attr.value.content = set.join(', ');
  29430. return;
  29431. }
  29432. }
  29433. const compoundExpression = createCompoundExpression([], attr.loc);
  29434. imageCandidates.forEach(({ url, descriptor }, index) => {
  29435. if (shouldProcessUrl(url)) {
  29436. const { path } = parseUrl(url);
  29437. let exp;
  29438. if (path) {
  29439. const existingImportsIndex = context.imports.findIndex(i => i.path === path);
  29440. if (existingImportsIndex > -1) {
  29441. exp = createSimpleExpression(`_imports_${existingImportsIndex}`, false, attr.loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  29442. }
  29443. else {
  29444. exp = createSimpleExpression(`_imports_${context.imports.length}`, false, attr.loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  29445. context.imports.push({ exp, path });
  29446. }
  29447. compoundExpression.children.push(exp);
  29448. }
  29449. }
  29450. else {
  29451. const exp = createSimpleExpression(`"${url}"`, false, attr.loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  29452. compoundExpression.children.push(exp);
  29453. }
  29454. const isNotLast = imageCandidates.length - 1 > index;
  29455. if (descriptor && isNotLast) {
  29456. compoundExpression.children.push(` + ' ${descriptor}, ' + `);
  29457. }
  29458. else if (descriptor) {
  29459. compoundExpression.children.push(` + ' ${descriptor}'`);
  29460. }
  29461. else if (isNotLast) {
  29462. compoundExpression.children.push(` + ', ' + `);
  29463. }
  29464. });
  29465. let exp = compoundExpression;
  29466. if (context.hoistStatic) {
  29467. exp = context.hoist(compoundExpression);
  29468. exp.constType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  29469. }
  29470. node.props[index] = {
  29471. type: 7 /* NodeTypes.DIRECTIVE */,
  29472. name: 'bind',
  29473. arg: createSimpleExpression('srcset', true, attr.loc),
  29474. exp,
  29475. modifiers: [],
  29476. loc: attr.loc
  29477. };
  29478. }
  29479. });
  29480. }
  29481. }
  29482. };
  29483. const SSR_INTERPOLATE = Symbol(`ssrInterpolate`);
  29484. const SSR_RENDER_VNODE = Symbol(`ssrRenderVNode`);
  29485. const SSR_RENDER_COMPONENT = Symbol(`ssrRenderComponent`);
  29486. const SSR_RENDER_SLOT = Symbol(`ssrRenderSlot`);
  29487. const SSR_RENDER_SLOT_INNER = Symbol(`ssrRenderSlotInner`);
  29488. const SSR_RENDER_CLASS = Symbol(`ssrRenderClass`);
  29489. const SSR_RENDER_STYLE = Symbol(`ssrRenderStyle`);
  29490. const SSR_RENDER_ATTRS = Symbol(`ssrRenderAttrs`);
  29491. const SSR_RENDER_ATTR = Symbol(`ssrRenderAttr`);
  29492. const SSR_RENDER_DYNAMIC_ATTR = Symbol(`ssrRenderDynamicAttr`);
  29493. const SSR_RENDER_LIST = Symbol(`ssrRenderList`);
  29494. const SSR_INCLUDE_BOOLEAN_ATTR = Symbol(`ssrIncludeBooleanAttr`);
  29495. const SSR_LOOSE_EQUAL = Symbol(`ssrLooseEqual`);
  29496. const SSR_LOOSE_CONTAIN = Symbol(`ssrLooseContain`);
  29497. const SSR_RENDER_DYNAMIC_MODEL = Symbol(`ssrRenderDynamicModel`);
  29498. const SSR_GET_DYNAMIC_MODEL_PROPS = Symbol(`ssrGetDynamicModelProps`);
  29499. const SSR_RENDER_TELEPORT = Symbol(`ssrRenderTeleport`);
  29500. const SSR_RENDER_SUSPENSE = Symbol(`ssrRenderSuspense`);
  29501. const SSR_GET_DIRECTIVE_PROPS = Symbol(`ssrGetDirectiveProps`);
  29502. const ssrHelpers = {
  29503. [SSR_INTERPOLATE]: `ssrInterpolate`,
  29504. [SSR_RENDER_VNODE]: `ssrRenderVNode`,
  29505. [SSR_RENDER_COMPONENT]: `ssrRenderComponent`,
  29506. [SSR_RENDER_SLOT]: `ssrRenderSlot`,
  29507. [SSR_RENDER_SLOT_INNER]: `ssrRenderSlotInner`,
  29508. [SSR_RENDER_CLASS]: `ssrRenderClass`,
  29509. [SSR_RENDER_STYLE]: `ssrRenderStyle`,
  29510. [SSR_RENDER_ATTRS]: `ssrRenderAttrs`,
  29511. [SSR_RENDER_ATTR]: `ssrRenderAttr`,
  29512. [SSR_RENDER_DYNAMIC_ATTR]: `ssrRenderDynamicAttr`,
  29513. [SSR_RENDER_LIST]: `ssrRenderList`,
  29514. [SSR_INCLUDE_BOOLEAN_ATTR]: `ssrIncludeBooleanAttr`,
  29515. [SSR_LOOSE_EQUAL]: `ssrLooseEqual`,
  29516. [SSR_LOOSE_CONTAIN]: `ssrLooseContain`,
  29517. [SSR_RENDER_DYNAMIC_MODEL]: `ssrRenderDynamicModel`,
  29518. [SSR_GET_DYNAMIC_MODEL_PROPS]: `ssrGetDynamicModelProps`,
  29519. [SSR_RENDER_TELEPORT]: `ssrRenderTeleport`,
  29520. [SSR_RENDER_SUSPENSE]: `ssrRenderSuspense`,
  29521. [SSR_GET_DIRECTIVE_PROPS]: `ssrGetDirectiveProps`
  29522. };
  29523. // Note: these are helpers imported from @vue/server-renderer
  29524. // make sure the names match!
  29525. registerRuntimeHelpers(ssrHelpers);
  29526. // Plugin for the first transform pass, which simply constructs the AST node
  29527. const ssrTransformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, processIf);
  29528. // This is called during the 2nd transform pass to construct the SSR-specific
  29529. // codegen nodes.
  29530. function ssrProcessIf(node, context, disableNestedFragments = false) {
  29531. const [rootBranch] = node.branches;
  29532. const ifStatement = createIfStatement(rootBranch.condition, processIfBranch(rootBranch, context, disableNestedFragments));
  29533. context.pushStatement(ifStatement);
  29534. let currentIf = ifStatement;
  29535. for (let i = 1; i < node.branches.length; i++) {
  29536. const branch = node.branches[i];
  29537. const branchBlockStatement = processIfBranch(branch, context, disableNestedFragments);
  29538. if (branch.condition) {
  29539. // else-if
  29540. currentIf = currentIf.alternate = createIfStatement(branch.condition, branchBlockStatement);
  29541. }
  29542. else {
  29543. // else
  29544. currentIf.alternate = branchBlockStatement;
  29545. }
  29546. }
  29547. if (!currentIf.alternate) {
  29548. currentIf.alternate = createBlockStatement([
  29549. createCallExpression(`_push`, ['`<!---->`'])
  29550. ]);
  29551. }
  29552. }
  29553. function processIfBranch(branch, context, disableNestedFragments = false) {
  29554. const { children } = branch;
  29555. const needFragmentWrapper = !disableNestedFragments &&
  29556. (children.length !== 1 || children[0].type !== 1 /* NodeTypes.ELEMENT */) &&
  29557. // optimize away nested fragments when the only child is a ForNode
  29558. !(children.length === 1 && children[0].type === 11 /* NodeTypes.FOR */);
  29559. return processChildrenAsStatement(branch, context, needFragmentWrapper);
  29560. }
  29561. // Plugin for the first transform pass, which simply constructs the AST node
  29562. const ssrTransformFor = createStructuralDirectiveTransform('for', processFor);
  29563. // This is called during the 2nd transform pass to construct the SSR-specific
  29564. // codegen nodes.
  29565. function ssrProcessFor(node, context, disableNestedFragments = false) {
  29566. const needFragmentWrapper = !disableNestedFragments &&
  29567. (node.children.length !== 1 || node.children[0].type !== 1 /* NodeTypes.ELEMENT */);
  29568. const renderLoop = createFunctionExpression(createForLoopParams(node.parseResult));
  29569. renderLoop.body = processChildrenAsStatement(node, context, needFragmentWrapper);
  29570. // v-for always renders a fragment unless explicitly disabled
  29571. if (!disableNestedFragments) {
  29572. context.pushStringPart(`<!--[-->`);
  29573. }
  29574. context.pushStatement(createCallExpression(context.helper(SSR_RENDER_LIST), [
  29575. node.source,
  29576. renderLoop
  29577. ]));
  29578. if (!disableNestedFragments) {
  29579. context.pushStringPart(`<!--]-->`);
  29580. }
  29581. }
  29582. const ssrTransformSlotOutlet = (node, context) => {
  29583. if (isSlotOutlet(node)) {
  29584. const { slotName, slotProps } = processSlotOutlet(node, context);
  29585. const args = [
  29586. `_ctx.$slots`,
  29587. slotName,
  29588. slotProps || `{}`,
  29589. // fallback content placeholder. will be replaced in the process phase
  29590. `null`,
  29591. `_push`,
  29592. `_parent`
  29593. ];
  29594. // inject slot scope id if current template uses :slotted
  29595. if (context.scopeId && context.slotted !== false) {
  29596. args.push(`"${context.scopeId}-s"`);
  29597. }
  29598. let method = SSR_RENDER_SLOT;
  29599. // #3989
  29600. // check if this is a single slot inside a transition wrapper - since
  29601. // transition will unwrap the slot fragment into a single vnode at runtime,
  29602. // we need to avoid rendering the slot as a fragment.
  29603. const parent = context.parent;
  29604. if (parent &&
  29605. parent.type === 1 /* NodeTypes.ELEMENT */ &&
  29606. parent.tagType === 1 /* ElementTypes.COMPONENT */ &&
  29607. resolveComponentType(parent, context, true) === TRANSITION &&
  29608. parent.children.filter(c => c.type === 1 /* NodeTypes.ELEMENT */).length === 1) {
  29609. method = SSR_RENDER_SLOT_INNER;
  29610. if (!(context.scopeId && context.slotted !== false)) {
  29611. args.push('null');
  29612. }
  29613. args.push('true');
  29614. }
  29615. node.ssrCodegenNode = createCallExpression(context.helper(method), args);
  29616. }
  29617. };
  29618. function ssrProcessSlotOutlet(node, context) {
  29619. const renderCall = node.ssrCodegenNode;
  29620. // has fallback content
  29621. if (node.children.length) {
  29622. const fallbackRenderFn = createFunctionExpression([]);
  29623. fallbackRenderFn.body = processChildrenAsStatement(node, context);
  29624. // _renderSlot(slots, name, props, fallback, ...)
  29625. renderCall.arguments[3] = fallbackRenderFn;
  29626. }
  29627. // Forwarded <slot/>. Merge slot scope ids
  29628. if (context.withSlotScopeId) {
  29629. const slotScopeId = renderCall.arguments[6];
  29630. renderCall.arguments[6] = slotScopeId
  29631. ? `${slotScopeId} + _scopeId`
  29632. : `_scopeId`;
  29633. }
  29634. context.pushStatement(node.ssrCodegenNode);
  29635. }
  29636. function createSSRCompilerError(code, loc) {
  29637. return createCompilerError(code, loc, SSRErrorMessages);
  29638. }
  29639. const SSRErrorMessages = {
  29640. [62 /* SSRErrorCodes.X_SSR_UNSAFE_ATTR_NAME */]: `Unsafe attribute name for SSR.`,
  29641. [63 /* SSRErrorCodes.X_SSR_NO_TELEPORT_TARGET */]: `Missing the 'to' prop on teleport element.`,
  29642. [64 /* SSRErrorCodes.X_SSR_INVALID_AST_NODE */]: `Invalid AST node during SSR transform.`
  29643. };
  29644. // Note: this is a 2nd-pass codegen transform.
  29645. function ssrProcessTeleport(node, context) {
  29646. const targetProp = findProp(node, 'to');
  29647. if (!targetProp) {
  29648. context.onError(createSSRCompilerError(63 /* SSRErrorCodes.X_SSR_NO_TELEPORT_TARGET */, node.loc));
  29649. return;
  29650. }
  29651. let target;
  29652. if (targetProp.type === 6 /* NodeTypes.ATTRIBUTE */) {
  29653. target =
  29654. targetProp.value && createSimpleExpression(targetProp.value.content, true);
  29655. }
  29656. else {
  29657. target = targetProp.exp;
  29658. }
  29659. if (!target) {
  29660. context.onError(createSSRCompilerError(63 /* SSRErrorCodes.X_SSR_NO_TELEPORT_TARGET */, targetProp.loc));
  29661. return;
  29662. }
  29663. const disabledProp = findProp(node, 'disabled', false, true /* allow empty */);
  29664. const disabled = disabledProp
  29665. ? disabledProp.type === 6 /* NodeTypes.ATTRIBUTE */
  29666. ? `true`
  29667. : disabledProp.exp || `false`
  29668. : `false`;
  29669. const contentRenderFn = createFunctionExpression([`_push`], undefined, // Body is added later
  29670. true, // newline
  29671. false, // isSlot
  29672. node.loc);
  29673. contentRenderFn.body = processChildrenAsStatement(node, context);
  29674. context.pushStatement(createCallExpression(context.helper(SSR_RENDER_TELEPORT), [
  29675. `_push`,
  29676. contentRenderFn,
  29677. target,
  29678. disabled,
  29679. `_parent`
  29680. ]));
  29681. }
  29682. const wipMap = new WeakMap();
  29683. // phase 1
  29684. function ssrTransformSuspense(node, context) {
  29685. return () => {
  29686. if (node.children.length) {
  29687. const wipEntry = {
  29688. slotsExp: null,
  29689. wipSlots: []
  29690. };
  29691. wipMap.set(node, wipEntry);
  29692. wipEntry.slotsExp = buildSlots(node, context, (_props, children, loc) => {
  29693. const fn = createFunctionExpression([], undefined, // no return, assign body later
  29694. true, // newline
  29695. false, // suspense slots are not treated as normal slots
  29696. loc);
  29697. wipEntry.wipSlots.push({
  29698. fn,
  29699. children
  29700. });
  29701. return fn;
  29702. }).slots;
  29703. }
  29704. };
  29705. }
  29706. // phase 2
  29707. function ssrProcessSuspense(node, context) {
  29708. // complete wip slots with ssr code
  29709. const wipEntry = wipMap.get(node);
  29710. if (!wipEntry) {
  29711. return;
  29712. }
  29713. const { slotsExp, wipSlots } = wipEntry;
  29714. for (let i = 0; i < wipSlots.length; i++) {
  29715. const slot = wipSlots[i];
  29716. slot.fn.body = processChildrenAsStatement(slot, context);
  29717. }
  29718. // _push(ssrRenderSuspense(slots))
  29719. context.pushStatement(createCallExpression(context.helper(SSR_RENDER_SUSPENSE), [
  29720. `_push`,
  29721. slotsExp
  29722. ]));
  29723. }
  29724. // for directives with children overwrite (e.g. v-html & v-text), we need to
  29725. // store the raw children so that they can be added in the 2nd pass.
  29726. const rawChildrenMap = new WeakMap();
  29727. const ssrTransformElement = (node, context) => {
  29728. if (node.type !== 1 /* NodeTypes.ELEMENT */ ||
  29729. node.tagType !== 0 /* ElementTypes.ELEMENT */) {
  29730. return;
  29731. }
  29732. return function ssrPostTransformElement() {
  29733. // element
  29734. // generate the template literal representing the open tag.
  29735. const openTag = [`<${node.tag}`];
  29736. // some tags need to be passed to runtime for special checks
  29737. const needTagForRuntime = node.tag === 'textarea' || node.tag.indexOf('-') > 0;
  29738. // v-bind="obj", v-bind:[key] and custom directives can potentially
  29739. // overwrite other static attrs and can affect final rendering result,
  29740. // so when they are present we need to bail out to full `renderAttrs`
  29741. const hasDynamicVBind = hasDynamicKeyVBind(node);
  29742. const hasCustomDir = node.props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ && !isBuiltInDirective(p.name));
  29743. const needMergeProps = hasDynamicVBind || hasCustomDir;
  29744. if (needMergeProps) {
  29745. const { props, directives } = buildProps(node, context, node.props, false /* isComponent */, false /* isDynamicComponent */, true /* ssr */);
  29746. if (props || directives.length) {
  29747. const mergedProps = buildSSRProps(props, directives, context);
  29748. const propsExp = createCallExpression(context.helper(SSR_RENDER_ATTRS), [mergedProps]);
  29749. if (node.tag === 'textarea') {
  29750. const existingText = node.children[0];
  29751. // If interpolation, this is dynamic <textarea> content, potentially
  29752. // injected by v-model and takes higher priority than v-bind value
  29753. if (!existingText || existingText.type !== 5 /* NodeTypes.INTERPOLATION */) {
  29754. // <textarea> with dynamic v-bind. We don't know if the final props
  29755. // will contain .value, so we will have to do something special:
  29756. // assign the merged props to a temp variable, and check whether
  29757. // it contains value (if yes, render is as children).
  29758. const tempId = `_temp${context.temps++}`;
  29759. propsExp.arguments = [
  29760. createAssignmentExpression(createSimpleExpression(tempId, false), mergedProps)
  29761. ];
  29762. rawChildrenMap.set(node, createCallExpression(context.helper(SSR_INTERPOLATE), [
  29763. createConditionalExpression(createSimpleExpression(`"value" in ${tempId}`, false), createSimpleExpression(`${tempId}.value`, false), createSimpleExpression(existingText ? existingText.content : ``, true), false)
  29764. ]));
  29765. }
  29766. }
  29767. else if (node.tag === 'input') {
  29768. // <input v-bind="obj" v-model>
  29769. // we need to determine the props to render for the dynamic v-model
  29770. // and merge it with the v-bind expression.
  29771. const vModel = findVModel(node);
  29772. if (vModel) {
  29773. // 1. save the props (san v-model) in a temp variable
  29774. const tempId = `_temp${context.temps++}`;
  29775. const tempExp = createSimpleExpression(tempId, false);
  29776. propsExp.arguments = [
  29777. createSequenceExpression([
  29778. createAssignmentExpression(tempExp, mergedProps),
  29779. createCallExpression(context.helper(MERGE_PROPS), [
  29780. tempExp,
  29781. createCallExpression(context.helper(SSR_GET_DYNAMIC_MODEL_PROPS), [
  29782. tempExp,
  29783. vModel.exp // model
  29784. ])
  29785. ])
  29786. ])
  29787. ];
  29788. }
  29789. }
  29790. if (needTagForRuntime) {
  29791. propsExp.arguments.push(`"${node.tag}"`);
  29792. }
  29793. openTag.push(propsExp);
  29794. }
  29795. }
  29796. // book keeping static/dynamic class merging.
  29797. let dynamicClassBinding = undefined;
  29798. let staticClassBinding = undefined;
  29799. // all style bindings are converted to dynamic by transformStyle.
  29800. // but we need to make sure to merge them.
  29801. let dynamicStyleBinding = undefined;
  29802. for (let i = 0; i < node.props.length; i++) {
  29803. const prop = node.props[i];
  29804. // ignore true-value/false-value on input
  29805. if (node.tag === 'input' && isTrueFalseValue(prop)) {
  29806. continue;
  29807. }
  29808. // special cases with children override
  29809. if (prop.type === 7 /* NodeTypes.DIRECTIVE */) {
  29810. if (prop.name === 'html' && prop.exp) {
  29811. rawChildrenMap.set(node, prop.exp);
  29812. }
  29813. else if (prop.name === 'text' && prop.exp) {
  29814. node.children = [createInterpolation(prop.exp, prop.loc)];
  29815. }
  29816. else if (prop.name === 'slot') {
  29817. context.onError(createCompilerError(40 /* ErrorCodes.X_V_SLOT_MISPLACED */, prop.loc));
  29818. }
  29819. else if (isTextareaWithValue(node, prop) && prop.exp) {
  29820. if (!needMergeProps) {
  29821. node.children = [createInterpolation(prop.exp, prop.loc)];
  29822. }
  29823. }
  29824. else if (!needMergeProps && prop.name !== 'on') {
  29825. // Directive transforms.
  29826. const directiveTransform = context.directiveTransforms[prop.name];
  29827. if (directiveTransform) {
  29828. const { props, ssrTagParts } = directiveTransform(prop, node, context);
  29829. if (ssrTagParts) {
  29830. openTag.push(...ssrTagParts);
  29831. }
  29832. for (let j = 0; j < props.length; j++) {
  29833. const { key, value } = props[j];
  29834. if (isStaticExp(key)) {
  29835. let attrName = key.content;
  29836. // static key attr
  29837. if (attrName === 'key' || attrName === 'ref') {
  29838. continue;
  29839. }
  29840. if (attrName === 'class') {
  29841. openTag.push(` class="`, (dynamicClassBinding = createCallExpression(context.helper(SSR_RENDER_CLASS), [value])), `"`);
  29842. }
  29843. else if (attrName === 'style') {
  29844. if (dynamicStyleBinding) {
  29845. // already has style binding, merge into it.
  29846. mergeCall(dynamicStyleBinding, value);
  29847. }
  29848. else {
  29849. openTag.push(` style="`, (dynamicStyleBinding = createCallExpression(context.helper(SSR_RENDER_STYLE), [value])), `"`);
  29850. }
  29851. }
  29852. else {
  29853. attrName =
  29854. node.tag.indexOf('-') > 0
  29855. ? attrName // preserve raw name on custom elements
  29856. : propsToAttrMap[attrName] || attrName.toLowerCase();
  29857. if (isBooleanAttr(attrName)) {
  29858. openTag.push(createConditionalExpression(createCallExpression(context.helper(SSR_INCLUDE_BOOLEAN_ATTR), [value]), createSimpleExpression(' ' + attrName, true), createSimpleExpression('', true), false /* no newline */));
  29859. }
  29860. else if (isSSRSafeAttrName(attrName)) {
  29861. openTag.push(createCallExpression(context.helper(SSR_RENDER_ATTR), [
  29862. key,
  29863. value
  29864. ]));
  29865. }
  29866. else {
  29867. context.onError(createSSRCompilerError(62 /* SSRErrorCodes.X_SSR_UNSAFE_ATTR_NAME */, key.loc));
  29868. }
  29869. }
  29870. }
  29871. else {
  29872. // dynamic key attr
  29873. // this branch is only encountered for custom directive
  29874. // transforms that returns properties with dynamic keys
  29875. const args = [key, value];
  29876. if (needTagForRuntime) {
  29877. args.push(`"${node.tag}"`);
  29878. }
  29879. openTag.push(createCallExpression(context.helper(SSR_RENDER_DYNAMIC_ATTR), args));
  29880. }
  29881. }
  29882. }
  29883. }
  29884. }
  29885. else {
  29886. // special case: value on <textarea>
  29887. if (node.tag === 'textarea' && prop.name === 'value' && prop.value) {
  29888. rawChildrenMap.set(node, escapeHtml(prop.value.content));
  29889. }
  29890. else if (!needMergeProps) {
  29891. if (prop.name === 'key' || prop.name === 'ref') {
  29892. continue;
  29893. }
  29894. // static prop
  29895. if (prop.name === 'class' && prop.value) {
  29896. staticClassBinding = JSON.stringify(prop.value.content);
  29897. }
  29898. openTag.push(` ${prop.name}` +
  29899. (prop.value ? `="${escapeHtml(prop.value.content)}"` : ``));
  29900. }
  29901. }
  29902. }
  29903. // handle co-existence of dynamic + static class bindings
  29904. if (dynamicClassBinding && staticClassBinding) {
  29905. mergeCall(dynamicClassBinding, staticClassBinding);
  29906. removeStaticBinding(openTag, 'class');
  29907. }
  29908. if (context.scopeId) {
  29909. openTag.push(` ${context.scopeId}`);
  29910. }
  29911. node.ssrCodegenNode = createTemplateLiteral(openTag);
  29912. };
  29913. };
  29914. function buildSSRProps(props, directives, context) {
  29915. let mergePropsArgs = [];
  29916. if (props) {
  29917. if (props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  29918. // already a mergeProps call
  29919. mergePropsArgs = props.arguments;
  29920. }
  29921. else {
  29922. mergePropsArgs.push(props);
  29923. }
  29924. }
  29925. if (directives.length) {
  29926. for (const dir of directives) {
  29927. mergePropsArgs.push(createCallExpression(context.helper(SSR_GET_DIRECTIVE_PROPS), [
  29928. `_ctx`,
  29929. ...buildDirectiveArgs(dir, context).elements
  29930. ]));
  29931. }
  29932. }
  29933. return mergePropsArgs.length > 1
  29934. ? createCallExpression(context.helper(MERGE_PROPS), mergePropsArgs)
  29935. : mergePropsArgs[0];
  29936. }
  29937. function isTrueFalseValue(prop) {
  29938. if (prop.type === 7 /* NodeTypes.DIRECTIVE */) {
  29939. return (prop.name === 'bind' &&
  29940. prop.arg &&
  29941. isStaticExp(prop.arg) &&
  29942. (prop.arg.content === 'true-value' || prop.arg.content === 'false-value'));
  29943. }
  29944. else {
  29945. return prop.name === 'true-value' || prop.name === 'false-value';
  29946. }
  29947. }
  29948. function isTextareaWithValue(node, prop) {
  29949. return !!(node.tag === 'textarea' &&
  29950. prop.name === 'bind' &&
  29951. isStaticArgOf(prop.arg, 'value'));
  29952. }
  29953. function mergeCall(call, arg) {
  29954. const existing = call.arguments[0];
  29955. if (existing.type === 17 /* NodeTypes.JS_ARRAY_EXPRESSION */) {
  29956. existing.elements.push(arg);
  29957. }
  29958. else {
  29959. call.arguments[0] = createArrayExpression([existing, arg]);
  29960. }
  29961. }
  29962. function removeStaticBinding(tag, binding) {
  29963. const regExp = new RegExp(`^ ${binding}=".+"$`);
  29964. const i = tag.findIndex(e => typeof e === 'string' && regExp.test(e));
  29965. if (i > -1) {
  29966. tag.splice(i, 1);
  29967. }
  29968. }
  29969. function findVModel(node) {
  29970. return node.props.find(p => p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'model' && p.exp);
  29971. }
  29972. function ssrProcessElement(node, context) {
  29973. const isVoidTag = context.options.isVoidTag || NO;
  29974. const elementsToAdd = node.ssrCodegenNode.elements;
  29975. for (let j = 0; j < elementsToAdd.length; j++) {
  29976. context.pushStringPart(elementsToAdd[j]);
  29977. }
  29978. // Handle slot scopeId
  29979. if (context.withSlotScopeId) {
  29980. context.pushStringPart(createSimpleExpression(`_scopeId`, false));
  29981. }
  29982. // close open tag
  29983. context.pushStringPart(`>`);
  29984. const rawChildren = rawChildrenMap.get(node);
  29985. if (rawChildren) {
  29986. context.pushStringPart(rawChildren);
  29987. }
  29988. else if (node.children.length) {
  29989. processChildren(node, context);
  29990. }
  29991. if (!isVoidTag(node.tag)) {
  29992. // push closing tag
  29993. context.pushStringPart(`</${node.tag}>`);
  29994. }
  29995. }
  29996. const wipMap$1 = new WeakMap();
  29997. // phase 1: build props
  29998. function ssrTransformTransitionGroup(node, context) {
  29999. return () => {
  30000. const tag = findProp(node, 'tag');
  30001. if (tag) {
  30002. const otherProps = node.props.filter(p => p !== tag);
  30003. const { props, directives } = buildProps(node, context, otherProps, true /* isComponent */, false /* isDynamicComponent */, true /* ssr (skip event listeners) */);
  30004. let propsExp = null;
  30005. if (props || directives.length) {
  30006. propsExp = createCallExpression(context.helper(SSR_RENDER_ATTRS), [
  30007. buildSSRProps(props, directives, context)
  30008. ]);
  30009. }
  30010. wipMap$1.set(node, {
  30011. tag,
  30012. propsExp
  30013. });
  30014. }
  30015. };
  30016. }
  30017. // phase 2: process children
  30018. function ssrProcessTransitionGroup(node, context) {
  30019. const entry = wipMap$1.get(node);
  30020. if (entry) {
  30021. const { tag, propsExp } = entry;
  30022. if (tag.type === 7 /* NodeTypes.DIRECTIVE */) {
  30023. // dynamic :tag
  30024. context.pushStringPart(`<`);
  30025. context.pushStringPart(tag.exp);
  30026. if (propsExp) {
  30027. context.pushStringPart(propsExp);
  30028. }
  30029. context.pushStringPart(`>`);
  30030. processChildren(node, context, false,
  30031. /**
  30032. * TransitionGroup has the special runtime behavior of flattening and
  30033. * concatenating all children into a single fragment (in order for them to
  30034. * be patched using the same key map) so we need to account for that here
  30035. * by disabling nested fragment wrappers from being generated.
  30036. */
  30037. true);
  30038. context.pushStringPart(`</`);
  30039. context.pushStringPart(tag.exp);
  30040. context.pushStringPart(`>`);
  30041. }
  30042. else {
  30043. // static tag
  30044. context.pushStringPart(`<${tag.value.content}`);
  30045. if (propsExp) {
  30046. context.pushStringPart(propsExp);
  30047. }
  30048. context.pushStringPart(`>`);
  30049. processChildren(node, context, false, true);
  30050. context.pushStringPart(`</${tag.value.content}>`);
  30051. }
  30052. }
  30053. else {
  30054. // fragment
  30055. processChildren(node, context, true, true);
  30056. }
  30057. }
  30058. // We need to construct the slot functions in the 1st pass to ensure proper
  30059. // scope tracking, but the children of each slot cannot be processed until
  30060. // the 2nd pass, so we store the WIP slot functions in a weakMap during the 1st
  30061. // pass and complete them in the 2nd pass.
  30062. const wipMap$2 = new WeakMap();
  30063. const WIP_SLOT = Symbol();
  30064. const componentTypeMap = new WeakMap();
  30065. // ssr component transform is done in two phases:
  30066. // In phase 1. we use `buildSlot` to analyze the children of the component into
  30067. // WIP slot functions (it must be done in phase 1 because `buildSlot` relies on
  30068. // the core transform context).
  30069. // In phase 2. we convert the WIP slots from phase 1 into ssr-specific codegen
  30070. // nodes.
  30071. const ssrTransformComponent = (node, context) => {
  30072. if (node.type !== 1 /* NodeTypes.ELEMENT */ ||
  30073. node.tagType !== 1 /* ElementTypes.COMPONENT */) {
  30074. return;
  30075. }
  30076. const component = resolveComponentType(node, context, true /* ssr */);
  30077. const isDynamicComponent = isObject(component) && component.callee === RESOLVE_DYNAMIC_COMPONENT;
  30078. componentTypeMap.set(node, component);
  30079. if (isSymbol(component)) {
  30080. if (component === SUSPENSE) {
  30081. return ssrTransformSuspense(node, context);
  30082. }
  30083. if (component === TRANSITION_GROUP) {
  30084. return ssrTransformTransitionGroup(node, context);
  30085. }
  30086. return; // other built-in components: fallthrough
  30087. }
  30088. // Build the fallback vnode-based branch for the component's slots.
  30089. // We need to clone the node into a fresh copy and use the buildSlots' logic
  30090. // to get access to the children of each slot. We then compile them with
  30091. // a child transform pipeline using vnode-based transforms (instead of ssr-
  30092. // based ones), and save the result branch (a ReturnStatement) in an array.
  30093. // The branch is retrieved when processing slots again in ssr mode.
  30094. const vnodeBranches = [];
  30095. const clonedNode = clone(node);
  30096. return function ssrPostTransformComponent() {
  30097. // Using the cloned node, build the normal VNode-based branches (for
  30098. // fallback in case the child is render-fn based). Store them in an array
  30099. // for later use.
  30100. if (clonedNode.children.length) {
  30101. buildSlots(clonedNode, context, (props, children) => {
  30102. vnodeBranches.push(createVNodeSlotBranch(props, children, context));
  30103. return createFunctionExpression(undefined);
  30104. });
  30105. }
  30106. let propsExp = `null`;
  30107. if (node.props.length) {
  30108. // note we are not passing ssr: true here because for components, v-on
  30109. // handlers should still be passed
  30110. const { props, directives } = buildProps(node, context, undefined, true, isDynamicComponent);
  30111. if (props || directives.length) {
  30112. propsExp = buildSSRProps(props, directives, context);
  30113. }
  30114. }
  30115. const wipEntries = [];
  30116. wipMap$2.set(node, wipEntries);
  30117. const buildSSRSlotFn = (props, children, loc) => {
  30118. const param0 = (props && stringifyExpression(props)) || `_`;
  30119. const fn = createFunctionExpression([param0, `_push`, `_parent`, `_scopeId`], undefined, // no return, assign body later
  30120. true, // newline
  30121. true, // isSlot
  30122. loc);
  30123. wipEntries.push({
  30124. type: WIP_SLOT,
  30125. fn,
  30126. children,
  30127. // also collect the corresponding vnode branch built earlier
  30128. vnodeBranch: vnodeBranches[wipEntries.length]
  30129. });
  30130. return fn;
  30131. };
  30132. const slots = node.children.length
  30133. ? buildSlots(node, context, buildSSRSlotFn).slots
  30134. : `null`;
  30135. if (typeof component !== 'string') {
  30136. // dynamic component that resolved to a `resolveDynamicComponent` call
  30137. // expression - since the resolved result may be a plain element (string)
  30138. // or a VNode, handle it with `renderVNode`.
  30139. node.ssrCodegenNode = createCallExpression(context.helper(SSR_RENDER_VNODE), [
  30140. `_push`,
  30141. createCallExpression(context.helper(CREATE_VNODE), [
  30142. component,
  30143. propsExp,
  30144. slots
  30145. ]),
  30146. `_parent`
  30147. ]);
  30148. }
  30149. else {
  30150. node.ssrCodegenNode = createCallExpression(context.helper(SSR_RENDER_COMPONENT), [component, propsExp, slots, `_parent`]);
  30151. }
  30152. };
  30153. };
  30154. function ssrProcessComponent(node, context, parent) {
  30155. const component = componentTypeMap.get(node);
  30156. if (!node.ssrCodegenNode) {
  30157. // this is a built-in component that fell-through.
  30158. if (component === TELEPORT) {
  30159. return ssrProcessTeleport(node, context);
  30160. }
  30161. else if (component === SUSPENSE) {
  30162. return ssrProcessSuspense(node, context);
  30163. }
  30164. else if (component === TRANSITION_GROUP) {
  30165. return ssrProcessTransitionGroup(node, context);
  30166. }
  30167. else {
  30168. // real fall-through: Transition / KeepAlive
  30169. // just render its children.
  30170. // #5352: if is at root level of a slot, push an empty string.
  30171. // this does not affect the final output, but avoids all-comment slot
  30172. // content of being treated as empty by ssrRenderSlot().
  30173. if (parent.type === WIP_SLOT) {
  30174. context.pushStringPart(``);
  30175. }
  30176. // #5351: filter out comment children inside transition
  30177. if (component === TRANSITION) {
  30178. node.children = node.children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */);
  30179. }
  30180. processChildren(node, context);
  30181. }
  30182. }
  30183. else {
  30184. // finish up slot function expressions from the 1st pass.
  30185. const wipEntries = wipMap$2.get(node) || [];
  30186. for (let i = 0; i < wipEntries.length; i++) {
  30187. const { fn, vnodeBranch } = wipEntries[i];
  30188. // For each slot, we generate two branches: one SSR-optimized branch and
  30189. // one normal vnode-based branch. The branches are taken based on the
  30190. // presence of the 2nd `_push` argument (which is only present if the slot
  30191. // is called by `_ssrRenderSlot`.
  30192. fn.body = createIfStatement(createSimpleExpression(`_push`, false), processChildrenAsStatement(wipEntries[i], context, false, true /* withSlotScopeId */), vnodeBranch);
  30193. }
  30194. // component is inside a slot, inherit slot scope Id
  30195. if (context.withSlotScopeId) {
  30196. node.ssrCodegenNode.arguments.push(`_scopeId`);
  30197. }
  30198. if (typeof component === 'string') {
  30199. // static component
  30200. context.pushStatement(createCallExpression(`_push`, [node.ssrCodegenNode]));
  30201. }
  30202. else {
  30203. // dynamic component (`resolveDynamicComponent` call)
  30204. // the codegen node is a `renderVNode` call
  30205. context.pushStatement(node.ssrCodegenNode);
  30206. }
  30207. }
  30208. }
  30209. const rawOptionsMap = new WeakMap();
  30210. const [baseNodeTransforms, baseDirectiveTransforms] = getBaseTransformPreset(true);
  30211. const vnodeNodeTransforms = [...baseNodeTransforms, ...DOMNodeTransforms];
  30212. const vnodeDirectiveTransforms = Object.assign(Object.assign({}, baseDirectiveTransforms), DOMDirectiveTransforms);
  30213. function createVNodeSlotBranch(props, children, parentContext) {
  30214. // apply a sub-transform using vnode-based transforms.
  30215. const rawOptions = rawOptionsMap.get(parentContext.root);
  30216. const subOptions = Object.assign(Object.assign({}, rawOptions), {
  30217. // overwrite with vnode-based transforms
  30218. nodeTransforms: [
  30219. ...vnodeNodeTransforms,
  30220. ...(rawOptions.nodeTransforms || [])
  30221. ], directiveTransforms: Object.assign(Object.assign({}, vnodeDirectiveTransforms), (rawOptions.directiveTransforms || {})) });
  30222. // wrap the children with a wrapper template for proper children treatment.
  30223. const wrapperNode = {
  30224. type: 1 /* NodeTypes.ELEMENT */,
  30225. ns: 0 /* Namespaces.HTML */,
  30226. tag: 'template',
  30227. tagType: 3 /* ElementTypes.TEMPLATE */,
  30228. isSelfClosing: false,
  30229. // important: provide v-slot="props" on the wrapper for proper
  30230. // scope analysis
  30231. props: [
  30232. {
  30233. type: 7 /* NodeTypes.DIRECTIVE */,
  30234. name: 'slot',
  30235. exp: props,
  30236. arg: undefined,
  30237. modifiers: [],
  30238. loc: locStub
  30239. }
  30240. ],
  30241. children,
  30242. loc: locStub,
  30243. codegenNode: undefined
  30244. };
  30245. subTransform(wrapperNode, subOptions, parentContext);
  30246. return createReturnStatement(children);
  30247. }
  30248. function subTransform(node, options, parentContext) {
  30249. const childRoot = createRoot([node]);
  30250. const childContext = createTransformContext(childRoot, options);
  30251. // this sub transform is for vnode fallback branch so it should be handled
  30252. // like normal render functions
  30253. childContext.ssr = false;
  30254. // inherit parent scope analysis state
  30255. childContext.scopes = Object.assign({}, parentContext.scopes);
  30256. childContext.identifiers = Object.assign({}, parentContext.identifiers);
  30257. childContext.imports = parentContext.imports;
  30258. // traverse
  30259. traverseNode(childRoot, childContext);
  30260. ['helpers', 'components', 'directives'].forEach(key => {
  30261. childContext[key].forEach((value, helperKey) => {
  30262. if (key === 'helpers') {
  30263. const parentCount = parentContext.helpers.get(helperKey);
  30264. if (parentCount === undefined) {
  30265. parentContext.helpers.set(helperKey, value);
  30266. }
  30267. else {
  30268. parentContext.helpers.set(helperKey, value + parentCount);
  30269. }
  30270. }
  30271. else {
  30272. parentContext[key].add(value);
  30273. }
  30274. });
  30275. });
  30276. // imports/hoists are not merged because:
  30277. // - imports are only used for asset urls and should be consistent between
  30278. // node/client branches
  30279. // - hoists are not enabled for the client branch here
  30280. }
  30281. function clone(v) {
  30282. if (isArray(v)) {
  30283. return v.map(clone);
  30284. }
  30285. else if (isObject(v)) {
  30286. const res = {};
  30287. for (const key in v) {
  30288. res[key] = clone(v[key]);
  30289. }
  30290. return res;
  30291. }
  30292. else {
  30293. return v;
  30294. }
  30295. }
  30296. // Because SSR codegen output is completely different from client-side output
  30297. // (e.g. multiple elements can be concatenated into a single template literal
  30298. // instead of each getting a corresponding call), we need to apply an extra
  30299. // transform pass to convert the template AST into a fresh JS AST before
  30300. // passing it to codegen.
  30301. function ssrCodegenTransform(ast, options) {
  30302. const context = createSSRTransformContext(ast, options);
  30303. // inject SFC <style> CSS variables
  30304. // we do this instead of inlining the expression to ensure the vars are
  30305. // only resolved once per render
  30306. if (options.ssrCssVars) {
  30307. const cssContext = createTransformContext(createRoot([]), options);
  30308. const varsExp = processExpression(createSimpleExpression(options.ssrCssVars, false), cssContext);
  30309. context.body.push(createCompoundExpression([`const _cssVars = { style: `, varsExp, `}`]));
  30310. Array.from(cssContext.helpers.keys()).forEach(helper => {
  30311. if (!ast.helpers.includes(helper))
  30312. ast.helpers.push(helper);
  30313. });
  30314. }
  30315. const isFragment = ast.children.length > 1 && ast.children.some(c => !isText(c));
  30316. processChildren(ast, context, isFragment);
  30317. ast.codegenNode = createBlockStatement(context.body);
  30318. // Finalize helpers.
  30319. // We need to separate helpers imported from 'vue' vs. '@vue/server-renderer'
  30320. ast.ssrHelpers = Array.from(new Set([...ast.helpers.filter(h => h in ssrHelpers), ...context.helpers]));
  30321. ast.helpers = ast.helpers.filter(h => !(h in ssrHelpers));
  30322. }
  30323. function createSSRTransformContext(root, options, helpers = new Set(), withSlotScopeId = false) {
  30324. const body = [];
  30325. let currentString = null;
  30326. return {
  30327. root,
  30328. options,
  30329. body,
  30330. helpers,
  30331. withSlotScopeId,
  30332. onError: options.onError ||
  30333. (e => {
  30334. throw e;
  30335. }),
  30336. helper(name) {
  30337. helpers.add(name);
  30338. return name;
  30339. },
  30340. pushStringPart(part) {
  30341. if (!currentString) {
  30342. const currentCall = createCallExpression(`_push`);
  30343. body.push(currentCall);
  30344. currentString = createTemplateLiteral([]);
  30345. currentCall.arguments.push(currentString);
  30346. }
  30347. const bufferedElements = currentString.elements;
  30348. const lastItem = bufferedElements[bufferedElements.length - 1];
  30349. if (isString(part) && isString(lastItem)) {
  30350. bufferedElements[bufferedElements.length - 1] += part;
  30351. }
  30352. else {
  30353. bufferedElements.push(part);
  30354. }
  30355. },
  30356. pushStatement(statement) {
  30357. // close current string
  30358. currentString = null;
  30359. body.push(statement);
  30360. }
  30361. };
  30362. }
  30363. function createChildContext(parent, withSlotScopeId = parent.withSlotScopeId) {
  30364. // ensure child inherits parent helpers
  30365. return createSSRTransformContext(parent.root, parent.options, parent.helpers, withSlotScopeId);
  30366. }
  30367. function processChildren(parent, context, asFragment = false, disableNestedFragments = false) {
  30368. if (asFragment) {
  30369. context.pushStringPart(`<!--[-->`);
  30370. }
  30371. const { children } = parent;
  30372. for (let i = 0; i < children.length; i++) {
  30373. const child = children[i];
  30374. switch (child.type) {
  30375. case 1 /* NodeTypes.ELEMENT */:
  30376. switch (child.tagType) {
  30377. case 0 /* ElementTypes.ELEMENT */:
  30378. ssrProcessElement(child, context);
  30379. break;
  30380. case 1 /* ElementTypes.COMPONENT */:
  30381. ssrProcessComponent(child, context, parent);
  30382. break;
  30383. case 2 /* ElementTypes.SLOT */:
  30384. ssrProcessSlotOutlet(child, context);
  30385. break;
  30386. case 3 /* ElementTypes.TEMPLATE */:
  30387. // TODO
  30388. break;
  30389. default:
  30390. context.onError(createSSRCompilerError(64 /* SSRErrorCodes.X_SSR_INVALID_AST_NODE */, child.loc));
  30391. // make sure we exhaust all possible types
  30392. const exhaustiveCheck = child;
  30393. return exhaustiveCheck;
  30394. }
  30395. break;
  30396. case 2 /* NodeTypes.TEXT */:
  30397. context.pushStringPart(escapeHtml(child.content));
  30398. break;
  30399. case 3 /* NodeTypes.COMMENT */:
  30400. // no need to escape comment here because the AST can only
  30401. // contain valid comments.
  30402. context.pushStringPart(`<!--${child.content}-->`);
  30403. break;
  30404. case 5 /* NodeTypes.INTERPOLATION */:
  30405. context.pushStringPart(createCallExpression(context.helper(SSR_INTERPOLATE), [child.content]));
  30406. break;
  30407. case 9 /* NodeTypes.IF */:
  30408. ssrProcessIf(child, context, disableNestedFragments);
  30409. break;
  30410. case 11 /* NodeTypes.FOR */:
  30411. ssrProcessFor(child, context, disableNestedFragments);
  30412. break;
  30413. case 10 /* NodeTypes.IF_BRANCH */:
  30414. // no-op - handled by ssrProcessIf
  30415. break;
  30416. case 12 /* NodeTypes.TEXT_CALL */:
  30417. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  30418. // no-op - these two types can never appear as template child node since
  30419. // `transformText` is not used during SSR compile.
  30420. break;
  30421. default:
  30422. context.onError(createSSRCompilerError(64 /* SSRErrorCodes.X_SSR_INVALID_AST_NODE */, child.loc));
  30423. // make sure we exhaust all possible types
  30424. const exhaustiveCheck = child;
  30425. return exhaustiveCheck;
  30426. }
  30427. }
  30428. if (asFragment) {
  30429. context.pushStringPart(`<!--]-->`);
  30430. }
  30431. }
  30432. function processChildrenAsStatement(parent, parentContext, asFragment = false, withSlotScopeId = parentContext.withSlotScopeId) {
  30433. const childContext = createChildContext(parentContext, withSlotScopeId);
  30434. processChildren(parent, childContext, asFragment);
  30435. return createBlockStatement(childContext.body);
  30436. }
  30437. const ssrTransformModel = (dir, node, context) => {
  30438. const model = dir.exp;
  30439. function checkDuplicatedValue() {
  30440. const value = findProp(node, 'value');
  30441. if (value) {
  30442. context.onError(createDOMCompilerError(58 /* DOMErrorCodes.X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
  30443. }
  30444. }
  30445. if (node.tagType === 0 /* ElementTypes.ELEMENT */) {
  30446. const res = { props: [] };
  30447. const defaultProps = [
  30448. // default value binding for text type inputs
  30449. createObjectProperty(`value`, model)
  30450. ];
  30451. if (node.tag === 'input') {
  30452. const type = findProp(node, 'type');
  30453. if (type) {
  30454. const value = findValueBinding(node);
  30455. if (type.type === 7 /* NodeTypes.DIRECTIVE */) {
  30456. // dynamic type
  30457. res.ssrTagParts = [
  30458. createCallExpression(context.helper(SSR_RENDER_DYNAMIC_MODEL), [
  30459. type.exp,
  30460. model,
  30461. value
  30462. ])
  30463. ];
  30464. }
  30465. else if (type.value) {
  30466. // static type
  30467. switch (type.value.content) {
  30468. case 'radio':
  30469. res.props = [
  30470. createObjectProperty(`checked`, createCallExpression(context.helper(SSR_LOOSE_EQUAL), [
  30471. model,
  30472. value
  30473. ]))
  30474. ];
  30475. break;
  30476. case 'checkbox':
  30477. const trueValueBinding = findProp(node, 'true-value');
  30478. if (trueValueBinding) {
  30479. const trueValue = trueValueBinding.type === 6 /* NodeTypes.ATTRIBUTE */
  30480. ? JSON.stringify(trueValueBinding.value.content)
  30481. : trueValueBinding.exp;
  30482. res.props = [
  30483. createObjectProperty(`checked`, createCallExpression(context.helper(SSR_LOOSE_EQUAL), [
  30484. model,
  30485. trueValue
  30486. ]))
  30487. ];
  30488. }
  30489. else {
  30490. res.props = [
  30491. createObjectProperty(`checked`, createConditionalExpression(createCallExpression(`Array.isArray`, [model]), createCallExpression(context.helper(SSR_LOOSE_CONTAIN), [
  30492. model,
  30493. value
  30494. ]), model))
  30495. ];
  30496. }
  30497. break;
  30498. case 'file':
  30499. context.onError(createDOMCompilerError(57 /* DOMErrorCodes.X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
  30500. break;
  30501. default:
  30502. checkDuplicatedValue();
  30503. res.props = defaultProps;
  30504. break;
  30505. }
  30506. }
  30507. }
  30508. else if (hasDynamicKeyVBind(node)) ;
  30509. else {
  30510. // text type
  30511. checkDuplicatedValue();
  30512. res.props = defaultProps;
  30513. }
  30514. }
  30515. else if (node.tag === 'textarea') {
  30516. checkDuplicatedValue();
  30517. node.children = [createInterpolation(model, model.loc)];
  30518. }
  30519. else if (node.tag === 'select') ;
  30520. else {
  30521. context.onError(createDOMCompilerError(55 /* DOMErrorCodes.X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
  30522. }
  30523. return res;
  30524. }
  30525. else {
  30526. // component v-model
  30527. return transformModel(dir, node, context);
  30528. }
  30529. };
  30530. function findValueBinding(node) {
  30531. const valueBinding = findProp(node, 'value');
  30532. return valueBinding
  30533. ? valueBinding.type === 7 /* NodeTypes.DIRECTIVE */
  30534. ? valueBinding.exp
  30535. : createSimpleExpression(valueBinding.value.content, true)
  30536. : createSimpleExpression(`null`, false);
  30537. }
  30538. const ssrTransformShow = (dir, node, context) => {
  30539. if (!dir.exp) {
  30540. context.onError(createDOMCompilerError(59 /* DOMErrorCodes.X_V_SHOW_NO_EXPRESSION */));
  30541. }
  30542. return {
  30543. props: [
  30544. createObjectProperty(`style`, createConditionalExpression(dir.exp, createSimpleExpression(`null`, false), createObjectExpression([
  30545. createObjectProperty(`display`, createSimpleExpression(`none`, true))
  30546. ]), false /* no newline */))
  30547. ]
  30548. };
  30549. };
  30550. const filterChild = (node) => node.children.filter(n => n.type !== 3 /* NodeTypes.COMMENT */);
  30551. const hasSingleChild = (node) => filterChild(node).length === 1;
  30552. const ssrInjectFallthroughAttrs = (node, context) => {
  30553. // _attrs is provided as a function argument.
  30554. // mark it as a known identifier so that it doesn't get prefixed by
  30555. // transformExpression.
  30556. if (node.type === 0 /* NodeTypes.ROOT */) {
  30557. context.identifiers._attrs = 1;
  30558. }
  30559. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  30560. node.tagType === 1 /* ElementTypes.COMPONENT */ &&
  30561. (isBuiltInType(node.tag, 'Transition') ||
  30562. isBuiltInType(node.tag, 'KeepAlive'))) {
  30563. const rootChildren = filterChild(context.root);
  30564. if (rootChildren.length === 1 && rootChildren[0] === node) {
  30565. if (hasSingleChild(node)) {
  30566. injectFallthroughAttrs(node.children[0]);
  30567. }
  30568. return;
  30569. }
  30570. }
  30571. const parent = context.parent;
  30572. if (!parent || parent.type !== 0 /* NodeTypes.ROOT */) {
  30573. return;
  30574. }
  30575. if (node.type === 10 /* NodeTypes.IF_BRANCH */ && hasSingleChild(node)) {
  30576. // detect cases where the parent v-if is not the only root level node
  30577. let hasEncounteredIf = false;
  30578. for (const c of filterChild(parent)) {
  30579. if (c.type === 9 /* NodeTypes.IF */ ||
  30580. (c.type === 1 /* NodeTypes.ELEMENT */ && findDir(c, 'if'))) {
  30581. // multiple root v-if
  30582. if (hasEncounteredIf)
  30583. return;
  30584. hasEncounteredIf = true;
  30585. }
  30586. else if (
  30587. // node before v-if
  30588. !hasEncounteredIf ||
  30589. // non else nodes
  30590. !(c.type === 1 /* NodeTypes.ELEMENT */ && findDir(c, /else/, true))) {
  30591. return;
  30592. }
  30593. }
  30594. injectFallthroughAttrs(node.children[0]);
  30595. }
  30596. else if (hasSingleChild(parent)) {
  30597. injectFallthroughAttrs(node);
  30598. }
  30599. };
  30600. function injectFallthroughAttrs(node) {
  30601. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  30602. (node.tagType === 0 /* ElementTypes.ELEMENT */ ||
  30603. node.tagType === 1 /* ElementTypes.COMPONENT */) &&
  30604. !findDir(node, 'for')) {
  30605. node.props.push({
  30606. type: 7 /* NodeTypes.DIRECTIVE */,
  30607. name: 'bind',
  30608. arg: undefined,
  30609. exp: createSimpleExpression(`_attrs`, false),
  30610. modifiers: [],
  30611. loc: locStub
  30612. });
  30613. }
  30614. }
  30615. const ssrInjectCssVars = (node, context) => {
  30616. if (!context.ssrCssVars) {
  30617. return;
  30618. }
  30619. // _cssVars is initialized once per render function
  30620. // the code is injected in ssrCodegenTransform when creating the
  30621. // ssr transform context
  30622. if (node.type === 0 /* NodeTypes.ROOT */) {
  30623. context.identifiers._cssVars = 1;
  30624. }
  30625. const parent = context.parent;
  30626. if (!parent || parent.type !== 0 /* NodeTypes.ROOT */) {
  30627. return;
  30628. }
  30629. if (node.type === 10 /* NodeTypes.IF_BRANCH */) {
  30630. for (const child of node.children) {
  30631. injectCssVars(child);
  30632. }
  30633. }
  30634. else {
  30635. injectCssVars(node);
  30636. }
  30637. };
  30638. function injectCssVars(node) {
  30639. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  30640. (node.tagType === 0 /* ElementTypes.ELEMENT */ ||
  30641. node.tagType === 1 /* ElementTypes.COMPONENT */) &&
  30642. !findDir(node, 'for')) {
  30643. if (isBuiltInType(node.tag, 'Suspense')) {
  30644. for (const child of node.children) {
  30645. if (child.type === 1 /* NodeTypes.ELEMENT */ &&
  30646. child.tagType === 3 /* ElementTypes.TEMPLATE */) {
  30647. // suspense slot
  30648. child.children.forEach(injectCssVars);
  30649. }
  30650. else {
  30651. injectCssVars(child);
  30652. }
  30653. }
  30654. }
  30655. else {
  30656. node.props.push({
  30657. type: 7 /* NodeTypes.DIRECTIVE */,
  30658. name: 'bind',
  30659. arg: undefined,
  30660. exp: createSimpleExpression(`_cssVars`, false),
  30661. modifiers: [],
  30662. loc: locStub
  30663. });
  30664. }
  30665. }
  30666. }
  30667. function compile$1(template, options = {}) {
  30668. options = Object.assign(Object.assign(Object.assign({}, options), parserOptions), { ssr: true, inSSR: true, scopeId: options.mode === 'function' ? null : options.scopeId,
  30669. // always prefix since compiler-ssr doesn't have size concern
  30670. prefixIdentifiers: true,
  30671. // disable optimizations that are unnecessary for ssr
  30672. cacheHandlers: false, hoistStatic: false });
  30673. const ast = baseParse(template, options);
  30674. // Save raw options for AST. This is needed when performing sub-transforms
  30675. // on slot vnode branches.
  30676. rawOptionsMap.set(ast, options);
  30677. transform(ast, Object.assign(Object.assign({}, options), { hoistStatic: false, nodeTransforms: [
  30678. ssrTransformIf,
  30679. ssrTransformFor,
  30680. trackVForSlotScopes,
  30681. transformExpression,
  30682. ssrTransformSlotOutlet,
  30683. ssrInjectFallthroughAttrs,
  30684. ssrInjectCssVars,
  30685. ssrTransformElement,
  30686. ssrTransformComponent,
  30687. trackSlotScopes,
  30688. transformStyle,
  30689. ...(options.nodeTransforms || []) // user transforms
  30690. ], directiveTransforms: Object.assign({
  30691. // reusing core v-bind
  30692. bind: transformBind, on: transformOn,
  30693. // model and show has dedicated SSR handling
  30694. model: ssrTransformModel, show: ssrTransformShow,
  30695. // the following are ignored during SSR
  30696. // on: noopDirectiveTransform,
  30697. cloak: noopDirectiveTransform, once: noopDirectiveTransform, memo: noopDirectiveTransform }, (options.directiveTransforms || {}) // user transforms
  30698. ) }));
  30699. // traverse the template AST and convert into SSR codegen AST
  30700. // by replacing ast.codegenNode.
  30701. ssrCodegenTransform(ast, options);
  30702. return generate(ast, options);
  30703. }
  30704. var CompilerSSR = /*#__PURE__*/Object.freeze({
  30705. __proto__: null,
  30706. compile: compile$1
  30707. });
  30708. var _polyfillNode_fs = {};
  30709. var _polyfillNode_fs$1 = /*#__PURE__*/Object.freeze({
  30710. __proto__: null,
  30711. 'default': _polyfillNode_fs
  30712. });
  30713. var _fs = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_fs$1);
  30714. var _path = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_path);
  30715. var require$$0 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_util$1);
  30716. const hasWarned = {};
  30717. function warnOnce(msg) {
  30718. const isNodeProd = typeof process !== 'undefined' && ({}).NODE_ENV === 'production';
  30719. if (!isNodeProd && !false && !hasWarned[msg]) {
  30720. hasWarned[msg] = true;
  30721. warn(msg);
  30722. }
  30723. }
  30724. function warn(msg) {
  30725. console.warn(`\x1b[1m\x1b[33m[@vue/compiler-sfc]\x1b[0m\x1b[33m ${msg}\x1b[0m\n`);
  30726. }
  30727. function preprocess({ source, filename, preprocessOptions }, preprocessor) {
  30728. // Consolidate exposes a callback based API, but the callback is in fact
  30729. // called synchronously for most templating engines. In our case, we have to
  30730. // expose a synchronous API so that it is usable in Jest transforms (which
  30731. // have to be sync because they are applied via Node.js require hooks)
  30732. let res = '';
  30733. let err = null;
  30734. preprocessor.render(source, Object.assign({ filename }, preprocessOptions), (_err, _res) => {
  30735. if (_err)
  30736. err = _err;
  30737. res = _res;
  30738. });
  30739. if (err)
  30740. throw err;
  30741. return res;
  30742. }
  30743. function compileTemplate(options) {
  30744. const { preprocessLang, preprocessCustomRequire } = options;
  30745. if (preprocessLang &&
  30746. !preprocessCustomRequire) {
  30747. throw new Error(`[@vue/compiler-sfc] Template preprocessing in the browser build must ` +
  30748. `provide the \`preprocessCustomRequire\` option to return the in-browser ` +
  30749. `version of the preprocessor in the shape of { render(): string }.`);
  30750. }
  30751. const preprocessor = preprocessLang
  30752. ? preprocessCustomRequire
  30753. ? preprocessCustomRequire(preprocessLang)
  30754. : undefined
  30755. : false;
  30756. if (preprocessor) {
  30757. try {
  30758. return doCompileTemplate(Object.assign(Object.assign({}, options), { source: preprocess(options, preprocessor) }));
  30759. }
  30760. catch (e) {
  30761. return {
  30762. code: `export default function render() {}`,
  30763. source: options.source,
  30764. tips: [],
  30765. errors: [e]
  30766. };
  30767. }
  30768. }
  30769. else if (preprocessLang) {
  30770. return {
  30771. code: `export default function render() {}`,
  30772. source: options.source,
  30773. tips: [
  30774. `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
  30775. ],
  30776. errors: [
  30777. `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
  30778. ]
  30779. };
  30780. }
  30781. else {
  30782. return doCompileTemplate(options);
  30783. }
  30784. }
  30785. function doCompileTemplate({ filename, id, scoped, slotted, inMap, source, ssr = false, ssrCssVars, isProd = false, compiler = ssr ? CompilerSSR : CompilerDOM, compilerOptions = {}, transformAssetUrls }) {
  30786. const errors = [];
  30787. const warnings = [];
  30788. let nodeTransforms = [];
  30789. if (isObject(transformAssetUrls)) {
  30790. const assetOptions = normalizeOptions(transformAssetUrls);
  30791. nodeTransforms = [
  30792. createAssetUrlTransformWithOptions(assetOptions),
  30793. createSrcsetTransformWithOptions(assetOptions)
  30794. ];
  30795. }
  30796. else if (transformAssetUrls !== false) {
  30797. nodeTransforms = [transformAssetUrl, transformSrcset];
  30798. }
  30799. if (ssr && !ssrCssVars) {
  30800. warnOnce(`compileTemplate is called with \`ssr: true\` but no ` +
  30801. `corresponding \`cssVars\` option.\`.`);
  30802. }
  30803. if (!id) {
  30804. warnOnce(`compileTemplate now requires the \`id\` option.\`.`);
  30805. id = '';
  30806. }
  30807. const shortId = id.replace(/^data-v-/, '');
  30808. const longId = `data-v-${shortId}`;
  30809. 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
  30810. ? genCssVarsFromList(ssrCssVars, shortId, isProd, true)
  30811. : '', scopeId: scoped ? longId : undefined, slotted, sourceMap: true }, compilerOptions), { nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []), filename, onError: e => errors.push(e), onWarn: w => warnings.push(w) }));
  30812. // inMap should be the map produced by ./parse.ts which is a simple line-only
  30813. // mapping. If it is present, we need to adjust the final map and errors to
  30814. // reflect the original line numbers.
  30815. if (inMap) {
  30816. if (map) {
  30817. map = mapLines(inMap, map);
  30818. }
  30819. if (errors.length) {
  30820. patchErrors(errors, source, inMap);
  30821. }
  30822. }
  30823. const tips = warnings.map(w => {
  30824. let msg = w.message;
  30825. if (w.loc) {
  30826. msg += `\n${generateCodeFrame(source, w.loc.start.offset, w.loc.end.offset)}`;
  30827. }
  30828. return msg;
  30829. });
  30830. return { code, ast, preamble, source, errors, tips, map };
  30831. }
  30832. function mapLines(oldMap, newMap) {
  30833. if (!oldMap)
  30834. return newMap;
  30835. if (!newMap)
  30836. return oldMap;
  30837. const oldMapConsumer = new SourceMapConsumer$1(oldMap);
  30838. const newMapConsumer = new SourceMapConsumer$1(newMap);
  30839. const mergedMapGenerator = new SourceMapGenerator$2();
  30840. newMapConsumer.eachMapping(m => {
  30841. if (m.originalLine == null) {
  30842. return;
  30843. }
  30844. const origPosInOldMap = oldMapConsumer.originalPositionFor({
  30845. line: m.originalLine,
  30846. column: m.originalColumn
  30847. });
  30848. if (origPosInOldMap.source == null) {
  30849. return;
  30850. }
  30851. mergedMapGenerator.addMapping({
  30852. generated: {
  30853. line: m.generatedLine,
  30854. column: m.generatedColumn
  30855. },
  30856. original: {
  30857. line: origPosInOldMap.line,
  30858. // use current column, since the oldMap produced by @vue/compiler-sfc
  30859. // does not
  30860. column: m.originalColumn
  30861. },
  30862. source: origPosInOldMap.source,
  30863. name: origPosInOldMap.name
  30864. });
  30865. });
  30866. // source-map's type definition is incomplete
  30867. const generator = mergedMapGenerator;
  30868. oldMapConsumer.sources.forEach((sourceFile) => {
  30869. generator._sources.add(sourceFile);
  30870. const sourceContent = oldMapConsumer.sourceContentFor(sourceFile);
  30871. if (sourceContent != null) {
  30872. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  30873. }
  30874. });
  30875. generator._sourceRoot = oldMap.sourceRoot;
  30876. generator._file = oldMap.file;
  30877. return generator.toJSON();
  30878. }
  30879. function patchErrors(errors, source, inMap) {
  30880. const originalSource = inMap.sourcesContent[0];
  30881. const offset = originalSource.indexOf(source);
  30882. const lineOffset = originalSource.slice(0, offset).split(/\r?\n/).length - 1;
  30883. errors.forEach(err => {
  30884. if (err.loc) {
  30885. err.loc.start.line += lineOffset;
  30886. err.loc.start.offset += offset;
  30887. if (err.loc.end !== err.loc.start) {
  30888. err.loc.end.line += lineOffset;
  30889. err.loc.end.offset += offset;
  30890. }
  30891. }
  30892. });
  30893. }
  30894. const defaultExportRE = /((?:^|\n|;)\s*)export(\s*)default/;
  30895. const namedDefaultExportRE = /((?:^|\n|;)\s*)export(.+)(?:as)?(\s*)default/s;
  30896. const exportDefaultClassRE = /((?:^|\n|;)\s*)export\s+default\s+class\s+([\w$]+)/;
  30897. /**
  30898. * Utility for rewriting `export default` in a script block into a variable
  30899. * declaration so that we can inject things into it
  30900. */
  30901. function rewriteDefault(input, as, parserPlugins) {
  30902. if (!hasDefaultExport(input)) {
  30903. return input + `\nconst ${as} = {}`;
  30904. }
  30905. let replaced;
  30906. const classMatch = input.match(exportDefaultClassRE);
  30907. if (classMatch) {
  30908. replaced =
  30909. input.replace(exportDefaultClassRE, '$1class $2') +
  30910. `\nconst ${as} = ${classMatch[2]}`;
  30911. }
  30912. else {
  30913. replaced = input.replace(defaultExportRE, `$1const ${as} =`);
  30914. }
  30915. if (!hasDefaultExport(replaced)) {
  30916. return replaced;
  30917. }
  30918. // if the script somehow still contains `default export`, it probably has
  30919. // multi-line comments or template strings. fallback to a full parse.
  30920. const s = new MagicString(input);
  30921. const ast = parse_1(input, {
  30922. sourceType: 'module',
  30923. plugins: parserPlugins
  30924. }).program.body;
  30925. ast.forEach(node => {
  30926. if (node.type === 'ExportDefaultDeclaration') {
  30927. if (node.declaration.type === 'ClassDeclaration') {
  30928. s.overwrite(node.start, node.declaration.id.start, `class `);
  30929. s.append(`\nconst ${as} = ${node.declaration.id.name}`);
  30930. }
  30931. else {
  30932. s.overwrite(node.start, node.declaration.start, `const ${as} = `);
  30933. }
  30934. }
  30935. if (node.type === 'ExportNamedDeclaration') {
  30936. for (const specifier of node.specifiers) {
  30937. if (specifier.type === 'ExportSpecifier' &&
  30938. specifier.exported.type === 'Identifier' &&
  30939. specifier.exported.name === 'default') {
  30940. if (node.source) {
  30941. if (specifier.local.name === 'default') {
  30942. const end = specifierEnd(input, specifier.local.end, node.end);
  30943. s.prepend(`import { default as __VUE_DEFAULT__ } from '${node.source.value}'\n`);
  30944. s.overwrite(specifier.start, end, ``);
  30945. s.append(`\nconst ${as} = __VUE_DEFAULT__`);
  30946. continue;
  30947. }
  30948. else {
  30949. const end = specifierEnd(input, specifier.exported.end, node.end);
  30950. s.prepend(`import { ${input.slice(specifier.local.start, specifier.local.end)} } from '${node.source.value}'\n`);
  30951. s.overwrite(specifier.start, end, ``);
  30952. s.append(`\nconst ${as} = ${specifier.local.name}`);
  30953. continue;
  30954. }
  30955. }
  30956. const end = specifierEnd(input, specifier.end, node.end);
  30957. s.overwrite(specifier.start, end, ``);
  30958. s.append(`\nconst ${as} = ${specifier.local.name}`);
  30959. }
  30960. }
  30961. }
  30962. });
  30963. return s.toString();
  30964. }
  30965. function hasDefaultExport(input) {
  30966. return defaultExportRE.test(input) || namedDefaultExportRE.test(input);
  30967. }
  30968. function specifierEnd(input, end, nodeEnd) {
  30969. // export { default , foo } ...
  30970. let hasCommas = false;
  30971. let oldEnd = end;
  30972. while (end < nodeEnd) {
  30973. if (/\s/.test(input.charAt(end))) {
  30974. end++;
  30975. }
  30976. else if (input.charAt(end) === ',') {
  30977. end++;
  30978. hasCommas = true;
  30979. break;
  30980. }
  30981. else if (input.charAt(end) === '}') {
  30982. break;
  30983. }
  30984. }
  30985. return hasCommas ? end : oldEnd;
  30986. }
  30987. const CONVERT_SYMBOL = '$';
  30988. const ESCAPE_SYMBOL = '$$';
  30989. const IMPORT_SOURCE = 'vue/macros';
  30990. const shorthands = ['ref', 'computed', 'shallowRef', 'toRef', 'customRef'];
  30991. const transformCheckRE = /[^\w]\$(?:\$|ref|computed|shallowRef)?\s*(\(|\<)/;
  30992. function shouldTransform(src) {
  30993. return transformCheckRE.test(src);
  30994. }
  30995. function transform$1(src, { filename, sourceMap, parserPlugins, importHelpersFrom = 'vue' } = {}) {
  30996. const plugins = parserPlugins || [];
  30997. if (filename) {
  30998. if (/\.tsx?$/.test(filename)) {
  30999. plugins.push('typescript');
  31000. }
  31001. if (filename.endsWith('x')) {
  31002. plugins.push('jsx');
  31003. }
  31004. }
  31005. const ast = parse_1(src, {
  31006. sourceType: 'module',
  31007. plugins
  31008. });
  31009. const s = new MagicString(src);
  31010. const res = transformAST(ast.program, s, 0);
  31011. // inject helper imports
  31012. if (res.importedHelpers.length) {
  31013. s.prepend(`import { ${res.importedHelpers
  31014. .map(h => `${h} as _${h}`)
  31015. .join(', ')} } from '${importHelpersFrom}'\n`);
  31016. }
  31017. return Object.assign(Object.assign({}, res), { code: s.toString(), map: sourceMap
  31018. ? s.generateMap({
  31019. source: filename,
  31020. hires: true,
  31021. includeContent: true
  31022. })
  31023. : null });
  31024. }
  31025. function transformAST(ast, s, offset = 0, knownRefs, knownProps) {
  31026. // TODO remove when out of experimental
  31027. warnExperimental();
  31028. const userImports = Object.create(null);
  31029. for (const node of ast.body) {
  31030. if (node.type !== 'ImportDeclaration')
  31031. continue;
  31032. walkImportDeclaration(node);
  31033. }
  31034. // macro import handling
  31035. let convertSymbol;
  31036. let escapeSymbol;
  31037. for (const { local, imported, source, specifier } of Object.values(userImports)) {
  31038. if (source === IMPORT_SOURCE) {
  31039. if (imported === ESCAPE_SYMBOL) {
  31040. escapeSymbol = local;
  31041. }
  31042. else if (imported === CONVERT_SYMBOL) {
  31043. convertSymbol = local;
  31044. }
  31045. else if (imported !== local) {
  31046. error(`macro imports for ref-creating methods do not support aliasing.`, specifier);
  31047. }
  31048. }
  31049. }
  31050. // default symbol
  31051. if (!convertSymbol && !userImports[CONVERT_SYMBOL]) {
  31052. convertSymbol = CONVERT_SYMBOL;
  31053. }
  31054. if (!escapeSymbol && !userImports[ESCAPE_SYMBOL]) {
  31055. escapeSymbol = ESCAPE_SYMBOL;
  31056. }
  31057. const importedHelpers = new Set();
  31058. const rootScope = {};
  31059. const scopeStack = [rootScope];
  31060. let currentScope = rootScope;
  31061. let escapeScope; // inside $$()
  31062. const excludedIds = new WeakSet();
  31063. const parentStack = [];
  31064. const propsLocalToPublicMap = Object.create(null);
  31065. if (knownRefs) {
  31066. for (const key of knownRefs) {
  31067. rootScope[key] = true;
  31068. }
  31069. }
  31070. if (knownProps) {
  31071. for (const key in knownProps) {
  31072. const { local } = knownProps[key];
  31073. rootScope[local] = 'prop';
  31074. propsLocalToPublicMap[local] = key;
  31075. }
  31076. }
  31077. function walkImportDeclaration(node) {
  31078. const source = node.source.value;
  31079. if (source === IMPORT_SOURCE) {
  31080. s.remove(node.start + offset, node.end + offset);
  31081. }
  31082. for (const specifier of node.specifiers) {
  31083. const local = specifier.local.name;
  31084. const imported = (specifier.type === 'ImportSpecifier' &&
  31085. specifier.imported.type === 'Identifier' &&
  31086. specifier.imported.name) ||
  31087. 'default';
  31088. userImports[local] = {
  31089. source,
  31090. local,
  31091. imported,
  31092. specifier
  31093. };
  31094. }
  31095. }
  31096. function isRefCreationCall(callee) {
  31097. if (!convertSymbol || currentScope[convertSymbol] !== undefined) {
  31098. return false;
  31099. }
  31100. if (callee === convertSymbol) {
  31101. return convertSymbol;
  31102. }
  31103. if (callee[0] === '$' && shorthands.includes(callee.slice(1))) {
  31104. return callee;
  31105. }
  31106. return false;
  31107. }
  31108. function error(msg, node) {
  31109. const e = new Error(msg);
  31110. e.node = node;
  31111. throw e;
  31112. }
  31113. function helper(msg) {
  31114. importedHelpers.add(msg);
  31115. return `_${msg}`;
  31116. }
  31117. function registerBinding(id, isRef = false) {
  31118. excludedIds.add(id);
  31119. if (currentScope) {
  31120. currentScope[id.name] = isRef;
  31121. }
  31122. else {
  31123. error('registerBinding called without active scope, something is wrong.', id);
  31124. }
  31125. }
  31126. const registerRefBinding = (id) => registerBinding(id, true);
  31127. let tempVarCount = 0;
  31128. function genTempVar() {
  31129. return `__$temp_${++tempVarCount}`;
  31130. }
  31131. function snip(node) {
  31132. return s.original.slice(node.start + offset, node.end + offset);
  31133. }
  31134. function walkScope(node, isRoot = false) {
  31135. for (const stmt of node.body) {
  31136. if (stmt.type === 'VariableDeclaration') {
  31137. walkVariableDeclaration(stmt, isRoot);
  31138. }
  31139. else if (stmt.type === 'FunctionDeclaration' ||
  31140. stmt.type === 'ClassDeclaration') {
  31141. if (stmt.declare || !stmt.id)
  31142. continue;
  31143. registerBinding(stmt.id);
  31144. }
  31145. else if ((stmt.type === 'ForOfStatement' || stmt.type === 'ForInStatement') &&
  31146. stmt.left.type === 'VariableDeclaration') {
  31147. walkVariableDeclaration(stmt.left);
  31148. }
  31149. else if (stmt.type === 'ExportNamedDeclaration' &&
  31150. stmt.declaration &&
  31151. stmt.declaration.type === 'VariableDeclaration') {
  31152. walkVariableDeclaration(stmt.declaration, isRoot);
  31153. }
  31154. else if (stmt.type === 'LabeledStatement' &&
  31155. stmt.body.type === 'VariableDeclaration') {
  31156. walkVariableDeclaration(stmt.body, isRoot);
  31157. }
  31158. }
  31159. }
  31160. function walkVariableDeclaration(stmt, isRoot = false) {
  31161. if (stmt.declare) {
  31162. return;
  31163. }
  31164. for (const decl of stmt.declarations) {
  31165. let refCall;
  31166. const isCall = decl.init &&
  31167. decl.init.type === 'CallExpression' &&
  31168. decl.init.callee.type === 'Identifier';
  31169. if (isCall &&
  31170. (refCall = isRefCreationCall(decl.init.callee.name))) {
  31171. processRefDeclaration(refCall, decl.id, decl.init);
  31172. }
  31173. else {
  31174. const isProps = isRoot && isCall && decl.init.callee.name === 'defineProps';
  31175. for (const id of extractIdentifiers(decl.id)) {
  31176. if (isProps) {
  31177. // for defineProps destructure, only exclude them since they
  31178. // are already passed in as knownProps
  31179. excludedIds.add(id);
  31180. }
  31181. else {
  31182. registerBinding(id);
  31183. }
  31184. }
  31185. }
  31186. }
  31187. }
  31188. function processRefDeclaration(method, id, call) {
  31189. excludedIds.add(call.callee);
  31190. if (method === convertSymbol) {
  31191. // $
  31192. // remove macro
  31193. s.remove(call.callee.start + offset, call.callee.end + offset);
  31194. if (id.type === 'Identifier') {
  31195. // single variable
  31196. registerRefBinding(id);
  31197. }
  31198. else if (id.type === 'ObjectPattern') {
  31199. processRefObjectPattern(id, call);
  31200. }
  31201. else if (id.type === 'ArrayPattern') {
  31202. processRefArrayPattern(id, call);
  31203. }
  31204. }
  31205. else {
  31206. // shorthands
  31207. if (id.type === 'Identifier') {
  31208. registerRefBinding(id);
  31209. // replace call
  31210. s.overwrite(call.start + offset, call.start + method.length + offset, helper(method.slice(1)));
  31211. }
  31212. else {
  31213. error(`${method}() cannot be used with destructure patterns.`, call);
  31214. }
  31215. }
  31216. }
  31217. function processRefObjectPattern(pattern, call, tempVar, path = []) {
  31218. if (!tempVar) {
  31219. tempVar = genTempVar();
  31220. // const { x } = $(useFoo()) --> const __$temp_1 = useFoo()
  31221. s.overwrite(pattern.start + offset, pattern.end + offset, tempVar);
  31222. }
  31223. let nameId;
  31224. for (const p of pattern.properties) {
  31225. let key;
  31226. let defaultValue;
  31227. if (p.type === 'ObjectProperty') {
  31228. if (p.key.start === p.value.start) {
  31229. // shorthand { foo }
  31230. nameId = p.key;
  31231. if (p.value.type === 'Identifier') {
  31232. // avoid shorthand value identifier from being processed
  31233. excludedIds.add(p.value);
  31234. }
  31235. else if (p.value.type === 'AssignmentPattern' &&
  31236. p.value.left.type === 'Identifier') {
  31237. // { foo = 1 }
  31238. excludedIds.add(p.value.left);
  31239. defaultValue = p.value.right;
  31240. }
  31241. }
  31242. else {
  31243. key = p.computed ? p.key : p.key.name;
  31244. if (p.value.type === 'Identifier') {
  31245. // { foo: bar }
  31246. nameId = p.value;
  31247. }
  31248. else if (p.value.type === 'ObjectPattern') {
  31249. processRefObjectPattern(p.value, call, tempVar, [...path, key]);
  31250. }
  31251. else if (p.value.type === 'ArrayPattern') {
  31252. processRefArrayPattern(p.value, call, tempVar, [...path, key]);
  31253. }
  31254. else if (p.value.type === 'AssignmentPattern') {
  31255. if (p.value.left.type === 'Identifier') {
  31256. // { foo: bar = 1 }
  31257. nameId = p.value.left;
  31258. defaultValue = p.value.right;
  31259. }
  31260. else if (p.value.left.type === 'ObjectPattern') {
  31261. processRefObjectPattern(p.value.left, call, tempVar, [
  31262. ...path,
  31263. [key, p.value.right]
  31264. ]);
  31265. }
  31266. else if (p.value.left.type === 'ArrayPattern') {
  31267. processRefArrayPattern(p.value.left, call, tempVar, [
  31268. ...path,
  31269. [key, p.value.right]
  31270. ]);
  31271. }
  31272. else ;
  31273. }
  31274. }
  31275. }
  31276. else {
  31277. // rest element { ...foo }
  31278. error(`reactivity destructure does not support rest elements.`, p);
  31279. }
  31280. if (nameId) {
  31281. registerRefBinding(nameId);
  31282. // inject toRef() after original replaced pattern
  31283. const source = pathToString(tempVar, path);
  31284. const keyStr = isString(key)
  31285. ? `'${key}'`
  31286. : key
  31287. ? snip(key)
  31288. : `'${nameId.name}'`;
  31289. const defaultStr = defaultValue ? `, ${snip(defaultValue)}` : ``;
  31290. s.appendLeft(call.end + offset, `,\n ${nameId.name} = ${helper('toRef')}(${source}, ${keyStr}${defaultStr})`);
  31291. }
  31292. }
  31293. if (nameId) {
  31294. s.appendLeft(call.end + offset, ';');
  31295. }
  31296. }
  31297. function processRefArrayPattern(pattern, call, tempVar, path = []) {
  31298. if (!tempVar) {
  31299. // const [x] = $(useFoo()) --> const __$temp_1 = useFoo()
  31300. tempVar = genTempVar();
  31301. s.overwrite(pattern.start + offset, pattern.end + offset, tempVar);
  31302. }
  31303. let nameId;
  31304. for (let i = 0; i < pattern.elements.length; i++) {
  31305. const e = pattern.elements[i];
  31306. if (!e)
  31307. continue;
  31308. let defaultValue;
  31309. if (e.type === 'Identifier') {
  31310. // [a] --> [__a]
  31311. nameId = e;
  31312. }
  31313. else if (e.type === 'AssignmentPattern') {
  31314. // [a = 1]
  31315. nameId = e.left;
  31316. defaultValue = e.right;
  31317. }
  31318. else if (e.type === 'RestElement') {
  31319. // [...a]
  31320. error(`reactivity destructure does not support rest elements.`, e);
  31321. }
  31322. else if (e.type === 'ObjectPattern') {
  31323. processRefObjectPattern(e, call, tempVar, [...path, i]);
  31324. }
  31325. else if (e.type === 'ArrayPattern') {
  31326. processRefArrayPattern(e, call, tempVar, [...path, i]);
  31327. }
  31328. if (nameId) {
  31329. registerRefBinding(nameId);
  31330. // inject toRef() after original replaced pattern
  31331. const source = pathToString(tempVar, path);
  31332. const defaultStr = defaultValue ? `, ${snip(defaultValue)}` : ``;
  31333. s.appendLeft(call.end + offset, `,\n ${nameId.name} = ${helper('toRef')}(${source}, ${i}${defaultStr})`);
  31334. }
  31335. }
  31336. if (nameId) {
  31337. s.appendLeft(call.end + offset, ';');
  31338. }
  31339. }
  31340. function pathToString(source, path) {
  31341. if (path.length) {
  31342. for (const seg of path) {
  31343. if (isArray(seg)) {
  31344. source = `(${source}${segToString(seg[0])} || ${snip(seg[1])})`;
  31345. }
  31346. else {
  31347. source += segToString(seg);
  31348. }
  31349. }
  31350. }
  31351. return source;
  31352. }
  31353. function segToString(seg) {
  31354. if (typeof seg === 'number') {
  31355. return `[${seg}]`;
  31356. }
  31357. else if (typeof seg === 'string') {
  31358. return `.${seg}`;
  31359. }
  31360. else {
  31361. return snip(seg);
  31362. }
  31363. }
  31364. function rewriteId(scope, id, parent, parentStack) {
  31365. if (hasOwn(scope, id.name)) {
  31366. const bindingType = scope[id.name];
  31367. if (bindingType) {
  31368. const isProp = bindingType === 'prop';
  31369. if (isStaticProperty(parent) && parent.shorthand) {
  31370. // let binding used in a property shorthand
  31371. // skip for destructure patterns
  31372. if (!parent.inPattern ||
  31373. isInDestructureAssignment(parent, parentStack)) {
  31374. if (isProp) {
  31375. if (escapeScope) {
  31376. // prop binding in $$()
  31377. // { prop } -> { prop: __props_prop }
  31378. registerEscapedPropBinding(id);
  31379. s.appendLeft(id.end + offset, `: __props_${propsLocalToPublicMap[id.name]}`);
  31380. }
  31381. else {
  31382. // { prop } -> { prop: __props.prop }
  31383. s.appendLeft(id.end + offset, `: ${genPropsAccessExp(propsLocalToPublicMap[id.name])}`);
  31384. }
  31385. }
  31386. else {
  31387. // { foo } -> { foo: foo.value }
  31388. s.appendLeft(id.end + offset, `: ${id.name}.value`);
  31389. }
  31390. }
  31391. }
  31392. else {
  31393. if (isProp) {
  31394. if (escapeScope) {
  31395. // x --> __props_x
  31396. registerEscapedPropBinding(id);
  31397. s.overwrite(id.start + offset, id.end + offset, `__props_${propsLocalToPublicMap[id.name]}`);
  31398. }
  31399. else {
  31400. // x --> __props.x
  31401. s.overwrite(id.start + offset, id.end + offset, genPropsAccessExp(propsLocalToPublicMap[id.name]));
  31402. }
  31403. }
  31404. else {
  31405. // x --> x.value
  31406. s.appendLeft(id.end + offset, '.value');
  31407. }
  31408. }
  31409. }
  31410. return true;
  31411. }
  31412. return false;
  31413. }
  31414. const propBindingRefs = {};
  31415. function registerEscapedPropBinding(id) {
  31416. if (!propBindingRefs.hasOwnProperty(id.name)) {
  31417. propBindingRefs[id.name] = true;
  31418. const publicKey = propsLocalToPublicMap[id.name];
  31419. s.prependRight(offset, `const __props_${publicKey} = ${helper(`toRef`)}(__props, '${publicKey}');\n`);
  31420. }
  31421. }
  31422. // check root scope first
  31423. walkScope(ast, true);
  31424. walk$1(ast, {
  31425. enter(node, parent) {
  31426. parent && parentStack.push(parent);
  31427. // function scopes
  31428. if (isFunctionType(node)) {
  31429. scopeStack.push((currentScope = {}));
  31430. walkFunctionParams(node, registerBinding);
  31431. if (node.body.type === 'BlockStatement') {
  31432. walkScope(node.body);
  31433. }
  31434. return;
  31435. }
  31436. // catch param
  31437. if (node.type === 'CatchClause') {
  31438. scopeStack.push((currentScope = {}));
  31439. if (node.param && node.param.type === 'Identifier') {
  31440. registerBinding(node.param);
  31441. }
  31442. walkScope(node.body);
  31443. return;
  31444. }
  31445. // non-function block scopes
  31446. if (node.type === 'BlockStatement' && !isFunctionType(parent)) {
  31447. scopeStack.push((currentScope = {}));
  31448. walkScope(node);
  31449. return;
  31450. }
  31451. // skip type nodes
  31452. if (parent &&
  31453. parent.type.startsWith('TS') &&
  31454. parent.type !== 'TSAsExpression' &&
  31455. parent.type !== 'TSNonNullExpression' &&
  31456. parent.type !== 'TSTypeAssertion') {
  31457. return this.skip();
  31458. }
  31459. if (node.type === 'Identifier' &&
  31460. // if inside $$(), skip unless this is a destructured prop binding
  31461. !(escapeScope && rootScope[node.name] !== 'prop') &&
  31462. isReferencedIdentifier(node, parent, parentStack) &&
  31463. !excludedIds.has(node)) {
  31464. // walk up the scope chain to check if id should be appended .value
  31465. let i = scopeStack.length;
  31466. while (i--) {
  31467. if (rewriteId(scopeStack[i], node, parent, parentStack)) {
  31468. return;
  31469. }
  31470. }
  31471. }
  31472. if (node.type === 'CallExpression' && node.callee.type === 'Identifier') {
  31473. const callee = node.callee.name;
  31474. const refCall = isRefCreationCall(callee);
  31475. if (refCall && (!parent || parent.type !== 'VariableDeclarator')) {
  31476. return error(`${refCall} can only be used as the initializer of ` +
  31477. `a variable declaration.`, node);
  31478. }
  31479. if (escapeSymbol &&
  31480. currentScope[escapeSymbol] === undefined &&
  31481. callee === escapeSymbol) {
  31482. s.remove(node.callee.start + offset, node.callee.end + offset);
  31483. escapeScope = node;
  31484. }
  31485. // TODO remove when out of experimental
  31486. if (callee === '$raw') {
  31487. error(`$raw() has been replaced by $$(). ` +
  31488. `See ${RFC_LINK} for latest updates.`, node);
  31489. }
  31490. if (callee === '$fromRef') {
  31491. error(`$fromRef() has been replaced by $(). ` +
  31492. `See ${RFC_LINK} for latest updates.`, node);
  31493. }
  31494. }
  31495. },
  31496. leave(node, parent) {
  31497. parent && parentStack.pop();
  31498. if ((node.type === 'BlockStatement' && !isFunctionType(parent)) ||
  31499. isFunctionType(node)) {
  31500. scopeStack.pop();
  31501. currentScope = scopeStack[scopeStack.length - 1] || null;
  31502. }
  31503. if (node === escapeScope) {
  31504. escapeScope = undefined;
  31505. }
  31506. }
  31507. });
  31508. return {
  31509. rootRefs: Object.keys(rootScope).filter(key => rootScope[key] === true),
  31510. importedHelpers: [...importedHelpers]
  31511. };
  31512. }
  31513. const RFC_LINK = `https://github.com/vuejs/rfcs/discussions/369`;
  31514. const hasWarned$1 = {};
  31515. function warnExperimental() {
  31516. // eslint-disable-next-line
  31517. if (typeof window !== 'undefined') {
  31518. return;
  31519. }
  31520. warnOnce$1(`Reactivity transform is an experimental feature.\n` +
  31521. `Experimental features may change behavior between patch versions.\n` +
  31522. `It is recommended to pin your vue dependencies to exact versions to avoid breakage.\n` +
  31523. `You can follow the proposal's status at ${RFC_LINK}.`);
  31524. }
  31525. function warnOnce$1(msg) {
  31526. const isNodeProd = typeof process !== 'undefined' && ({}).NODE_ENV === 'production';
  31527. if (!isNodeProd && !false && !hasWarned$1[msg]) {
  31528. hasWarned$1[msg] = true;
  31529. warn$1(msg);
  31530. }
  31531. }
  31532. function warn$1(msg) {
  31533. console.warn(`\x1b[1m\x1b[33m[@vue/reactivity-transform]\x1b[0m\x1b[33m ${msg}\x1b[0m\n`);
  31534. }
  31535. // Special compiler macros
  31536. const DEFINE_PROPS = 'defineProps';
  31537. const DEFINE_EMITS = 'defineEmits';
  31538. const DEFINE_EXPOSE = 'defineExpose';
  31539. const WITH_DEFAULTS = 'withDefaults';
  31540. // constants
  31541. const DEFAULT_VAR = `__default__`;
  31542. const isBuiltInDir = makeMap(`once,memo,if,for,else,else-if,slot,text,html,on,bind,model,show,cloak,is`);
  31543. /**
  31544. * Compile `<script setup>`
  31545. * It requires the whole SFC descriptor because we need to handle and merge
  31546. * normal `<script>` + `<script setup>` if both are present.
  31547. */
  31548. function compileScript(sfc, options) {
  31549. var _a;
  31550. let { script, scriptSetup, source, filename } = sfc;
  31551. // feature flags
  31552. // TODO remove support for deprecated options when out of experimental
  31553. const enableReactivityTransform = !!options.reactivityTransform ||
  31554. !!options.refSugar ||
  31555. !!options.refTransform;
  31556. const enablePropsTransform = !!options.reactivityTransform || !!options.propsDestructureTransform;
  31557. const isProd = !!options.isProd;
  31558. const genSourceMap = options.sourceMap !== false;
  31559. let refBindings;
  31560. if (!options.id) {
  31561. warnOnce(`compileScript now requires passing the \`id\` option.\n` +
  31562. `Upgrade your vite or vue-loader version for compatibility with ` +
  31563. `the latest experimental proposals.`);
  31564. }
  31565. const scopeId = options.id ? options.id.replace(/^data-v-/, '') : '';
  31566. const cssVars = sfc.cssVars;
  31567. const scriptLang = script && script.lang;
  31568. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  31569. const isTS = scriptLang === 'ts' ||
  31570. scriptLang === 'tsx' ||
  31571. scriptSetupLang === 'ts' ||
  31572. scriptSetupLang === 'tsx';
  31573. // resolve parser plugins
  31574. const plugins = [];
  31575. if (!isTS || scriptLang === 'tsx' || scriptSetupLang === 'tsx') {
  31576. plugins.push('jsx');
  31577. }
  31578. else {
  31579. // If don't match the case of adding jsx, should remove the jsx from the babelParserPlugins
  31580. if (options.babelParserPlugins)
  31581. options.babelParserPlugins = options.babelParserPlugins.filter(n => n !== 'jsx');
  31582. }
  31583. if (options.babelParserPlugins)
  31584. plugins.push(...options.babelParserPlugins);
  31585. if (isTS) {
  31586. plugins.push('typescript');
  31587. if (!plugins.includes('decorators')) {
  31588. plugins.push('decorators-legacy');
  31589. }
  31590. }
  31591. if (!scriptSetup) {
  31592. if (!script) {
  31593. throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`);
  31594. }
  31595. if (scriptLang && !isTS && scriptLang !== 'jsx') {
  31596. // do not process non js/ts script blocks
  31597. return script;
  31598. }
  31599. try {
  31600. let content = script.content;
  31601. let map = script.map;
  31602. const scriptAst = parse_1(content, {
  31603. plugins,
  31604. sourceType: 'module'
  31605. }).program;
  31606. const bindings = analyzeScriptBindings(scriptAst.body);
  31607. if (enableReactivityTransform && shouldTransform(content)) {
  31608. const s = new MagicString(source);
  31609. const startOffset = script.loc.start.offset;
  31610. const endOffset = script.loc.end.offset;
  31611. const { importedHelpers } = transformAST(scriptAst, s, startOffset);
  31612. if (importedHelpers.length) {
  31613. s.prepend(`import { ${importedHelpers
  31614. .map(h => `${h} as _${h}`)
  31615. .join(', ')} } from 'vue'\n`);
  31616. }
  31617. s.remove(0, startOffset);
  31618. s.remove(endOffset, source.length);
  31619. content = s.toString();
  31620. if (genSourceMap) {
  31621. map = s.generateMap({
  31622. source: filename,
  31623. hires: true,
  31624. includeContent: true
  31625. });
  31626. }
  31627. }
  31628. if (cssVars.length) {
  31629. content = rewriteDefault(content, DEFAULT_VAR, plugins);
  31630. content += genNormalScriptCssVarsCode(cssVars, bindings, scopeId, isProd);
  31631. content += `\nexport default ${DEFAULT_VAR}`;
  31632. }
  31633. return Object.assign(Object.assign({}, script), { content,
  31634. map,
  31635. bindings, scriptAst: scriptAst.body });
  31636. }
  31637. catch (e) {
  31638. // silently fallback if parse fails since user may be using custom
  31639. // babel syntax
  31640. return script;
  31641. }
  31642. }
  31643. if (script && scriptLang !== scriptSetupLang) {
  31644. throw new Error(`[@vue/compiler-sfc] <script> and <script setup> must have the same ` +
  31645. `language type.`);
  31646. }
  31647. if (scriptSetupLang && !isTS && scriptSetupLang !== 'jsx') {
  31648. // do not process non js/ts script blocks
  31649. return scriptSetup;
  31650. }
  31651. // metadata that needs to be returned
  31652. const bindingMetadata = {};
  31653. const helperImports = new Set();
  31654. const userImports = Object.create(null);
  31655. const scriptBindings = Object.create(null);
  31656. const setupBindings = Object.create(null);
  31657. let defaultExport;
  31658. let hasDefinePropsCall = false;
  31659. let hasDefineEmitCall = false;
  31660. let hasDefineExposeCall = false;
  31661. let hasDefaultExportName = false;
  31662. let hasDefaultExportRender = false;
  31663. let propsRuntimeDecl;
  31664. let propsRuntimeDefaults;
  31665. let propsDestructureDecl;
  31666. let propsDestructureRestId;
  31667. let propsTypeDecl;
  31668. let propsTypeDeclRaw;
  31669. let propsIdentifier;
  31670. let emitsRuntimeDecl;
  31671. let emitsTypeDecl;
  31672. let emitsTypeDeclRaw;
  31673. let emitIdentifier;
  31674. let hasAwait = false;
  31675. let hasInlinedSsrRenderFn = false;
  31676. // props/emits declared via types
  31677. const typeDeclaredProps = {};
  31678. const typeDeclaredEmits = new Set();
  31679. // record declared types for runtime props type generation
  31680. const declaredTypes = {};
  31681. // props destructure data
  31682. const propsDestructuredBindings = Object.create(null);
  31683. // magic-string state
  31684. const s = new MagicString(source);
  31685. const startOffset = scriptSetup.loc.start.offset;
  31686. const endOffset = scriptSetup.loc.end.offset;
  31687. const scriptStartOffset = script && script.loc.start.offset;
  31688. const scriptEndOffset = script && script.loc.end.offset;
  31689. function helper(key) {
  31690. helperImports.add(key);
  31691. return `_${key}`;
  31692. }
  31693. function parse(input, options, offset) {
  31694. try {
  31695. return parse_1(input, options).program;
  31696. }
  31697. catch (e) {
  31698. e.message = `[@vue/compiler-sfc] ${e.message}\n\n${sfc.filename}\n${generateCodeFrame(source, e.pos + offset, e.pos + offset + 1)}`;
  31699. throw e;
  31700. }
  31701. }
  31702. function error(msg, node, end = node.end + startOffset) {
  31703. throw new Error(`[@vue/compiler-sfc] ${msg}\n\n${sfc.filename}\n${generateCodeFrame(source, node.start + startOffset, end)}`);
  31704. }
  31705. function hoistNode(node) {
  31706. const start = node.start + startOffset;
  31707. let end = node.end + startOffset;
  31708. // locate comment
  31709. if (node.trailingComments && node.trailingComments.length > 0) {
  31710. const lastCommentNode = node.trailingComments[node.trailingComments.length - 1];
  31711. end = lastCommentNode.end + startOffset;
  31712. }
  31713. // locate the end of whitespace between this statement and the next
  31714. while (end <= source.length) {
  31715. if (!/\s/.test(source.charAt(end))) {
  31716. break;
  31717. }
  31718. end++;
  31719. }
  31720. s.move(start, end, 0);
  31721. }
  31722. function registerUserImport(source, local, imported, isType, isFromSetup, needTemplateUsageCheck) {
  31723. // template usage check is only needed in non-inline mode, so we can skip
  31724. // the work if inlineTemplate is true.
  31725. let isUsedInTemplate = needTemplateUsageCheck;
  31726. if (needTemplateUsageCheck &&
  31727. isTS &&
  31728. sfc.template &&
  31729. !sfc.template.src &&
  31730. !sfc.template.lang) {
  31731. isUsedInTemplate = isImportUsed(local, sfc);
  31732. }
  31733. userImports[local] = {
  31734. isType,
  31735. imported: imported || 'default',
  31736. local,
  31737. source,
  31738. isFromSetup,
  31739. isUsedInTemplate
  31740. };
  31741. }
  31742. function processDefineProps(node, declId) {
  31743. if (!isCallOf(node, DEFINE_PROPS)) {
  31744. return false;
  31745. }
  31746. if (hasDefinePropsCall) {
  31747. error(`duplicate ${DEFINE_PROPS}() call`, node);
  31748. }
  31749. hasDefinePropsCall = true;
  31750. propsRuntimeDecl = node.arguments[0];
  31751. // call has type parameters - infer runtime types from it
  31752. if (node.typeParameters) {
  31753. if (propsRuntimeDecl) {
  31754. error(`${DEFINE_PROPS}() cannot accept both type and non-type arguments ` +
  31755. `at the same time. Use one or the other.`, node);
  31756. }
  31757. propsTypeDeclRaw = node.typeParameters.params[0];
  31758. propsTypeDecl = resolveQualifiedType(propsTypeDeclRaw, node => node.type === 'TSTypeLiteral');
  31759. if (!propsTypeDecl) {
  31760. error(`type argument passed to ${DEFINE_PROPS}() must be a literal type, ` +
  31761. `or a reference to an interface or literal type.`, propsTypeDeclRaw);
  31762. }
  31763. }
  31764. if (declId) {
  31765. if (enablePropsTransform && declId.type === 'ObjectPattern') {
  31766. propsDestructureDecl = declId;
  31767. // props destructure - handle compilation sugar
  31768. for (const prop of declId.properties) {
  31769. if (prop.type === 'ObjectProperty') {
  31770. const propKey = resolveObjectKey(prop.key, prop.computed);
  31771. if (!propKey) {
  31772. error(`${DEFINE_PROPS}() destructure cannot use computed key.`, prop.key);
  31773. }
  31774. if (prop.value.type === 'AssignmentPattern') {
  31775. // default value { foo = 123 }
  31776. const { left, right } = prop.value;
  31777. if (left.type !== 'Identifier') {
  31778. error(`${DEFINE_PROPS}() destructure does not support nested patterns.`, left);
  31779. }
  31780. // store default value
  31781. propsDestructuredBindings[propKey] = {
  31782. local: left.name,
  31783. default: right
  31784. };
  31785. }
  31786. else if (prop.value.type === 'Identifier') {
  31787. // simple destructure
  31788. propsDestructuredBindings[propKey] = {
  31789. local: prop.value.name
  31790. };
  31791. }
  31792. else {
  31793. error(`${DEFINE_PROPS}() destructure does not support nested patterns.`, prop.value);
  31794. }
  31795. }
  31796. else {
  31797. // rest spread
  31798. propsDestructureRestId = prop.argument.name;
  31799. }
  31800. }
  31801. }
  31802. else {
  31803. propsIdentifier = scriptSetup.content.slice(declId.start, declId.end);
  31804. }
  31805. }
  31806. return true;
  31807. }
  31808. function processWithDefaults(node, declId) {
  31809. if (!isCallOf(node, WITH_DEFAULTS)) {
  31810. return false;
  31811. }
  31812. if (processDefineProps(node.arguments[0], declId)) {
  31813. if (propsRuntimeDecl) {
  31814. error(`${WITH_DEFAULTS} can only be used with type-based ` +
  31815. `${DEFINE_PROPS} declaration.`, node);
  31816. }
  31817. if (propsDestructureDecl) {
  31818. error(`${WITH_DEFAULTS}() is unnecessary when using destructure with ${DEFINE_PROPS}().\n` +
  31819. `Prefer using destructure default values, e.g. const { foo = 1 } = defineProps(...).`, node.callee);
  31820. }
  31821. propsRuntimeDefaults = node.arguments[1];
  31822. if (!propsRuntimeDefaults ||
  31823. propsRuntimeDefaults.type !== 'ObjectExpression') {
  31824. error(`The 2nd argument of ${WITH_DEFAULTS} must be an object literal.`, propsRuntimeDefaults || node);
  31825. }
  31826. }
  31827. else {
  31828. error(`${WITH_DEFAULTS}' first argument must be a ${DEFINE_PROPS} call.`, node.arguments[0] || node);
  31829. }
  31830. return true;
  31831. }
  31832. function processDefineEmits(node, declId) {
  31833. if (!isCallOf(node, DEFINE_EMITS)) {
  31834. return false;
  31835. }
  31836. if (hasDefineEmitCall) {
  31837. error(`duplicate ${DEFINE_EMITS}() call`, node);
  31838. }
  31839. hasDefineEmitCall = true;
  31840. emitsRuntimeDecl = node.arguments[0];
  31841. if (node.typeParameters) {
  31842. if (emitsRuntimeDecl) {
  31843. error(`${DEFINE_EMITS}() cannot accept both type and non-type arguments ` +
  31844. `at the same time. Use one or the other.`, node);
  31845. }
  31846. emitsTypeDeclRaw = node.typeParameters.params[0];
  31847. emitsTypeDecl = resolveQualifiedType(emitsTypeDeclRaw, node => node.type === 'TSFunctionType' || node.type === 'TSTypeLiteral');
  31848. if (!emitsTypeDecl) {
  31849. error(`type argument passed to ${DEFINE_EMITS}() must be a function type, ` +
  31850. `a literal type with call signatures, or a reference to the above types.`, emitsTypeDeclRaw);
  31851. }
  31852. }
  31853. if (declId) {
  31854. emitIdentifier =
  31855. declId.type === 'Identifier'
  31856. ? declId.name
  31857. : scriptSetup.content.slice(declId.start, declId.end);
  31858. }
  31859. return true;
  31860. }
  31861. function getAstBody() {
  31862. return scriptAst
  31863. ? [...scriptSetupAst.body, ...scriptAst.body]
  31864. : scriptSetupAst.body;
  31865. }
  31866. function resolveExtendsType(node, qualifier, cache = []) {
  31867. if (node.type === 'TSInterfaceDeclaration' && node.extends) {
  31868. node.extends.forEach(extend => {
  31869. if (extend.type === 'TSExpressionWithTypeArguments' &&
  31870. extend.expression.type === 'Identifier') {
  31871. const body = getAstBody();
  31872. for (const node of body) {
  31873. const qualified = isQualifiedType(node, qualifier, extend.expression.name);
  31874. if (qualified) {
  31875. cache.push(qualified);
  31876. resolveExtendsType(node, qualifier, cache);
  31877. return cache;
  31878. }
  31879. }
  31880. }
  31881. });
  31882. }
  31883. return cache;
  31884. }
  31885. function isQualifiedType(node, qualifier, refName) {
  31886. if (node.type === 'TSInterfaceDeclaration' && node.id.name === refName) {
  31887. return node.body;
  31888. }
  31889. else if (node.type === 'TSTypeAliasDeclaration' &&
  31890. node.id.name === refName &&
  31891. qualifier(node.typeAnnotation)) {
  31892. return node.typeAnnotation;
  31893. }
  31894. else if (node.type === 'ExportNamedDeclaration' && node.declaration) {
  31895. return isQualifiedType(node.declaration, qualifier, refName);
  31896. }
  31897. }
  31898. // filter all extends types to keep the override declaration
  31899. function filterExtendsType(extendsTypes, bodies) {
  31900. extendsTypes.forEach(extend => {
  31901. const body = extend.body;
  31902. body.forEach(newBody => {
  31903. if (newBody.type === 'TSPropertySignature' &&
  31904. newBody.key.type === 'Identifier') {
  31905. const name = newBody.key.name;
  31906. const hasOverride = bodies.some(seenBody => seenBody.type === 'TSPropertySignature' &&
  31907. seenBody.key.type === 'Identifier' &&
  31908. seenBody.key.name === name);
  31909. if (!hasOverride)
  31910. bodies.push(newBody);
  31911. }
  31912. });
  31913. });
  31914. }
  31915. function resolveQualifiedType(node, qualifier) {
  31916. if (qualifier(node)) {
  31917. return node;
  31918. }
  31919. if (node.type === 'TSTypeReference' &&
  31920. node.typeName.type === 'Identifier') {
  31921. const refName = node.typeName.name;
  31922. const body = getAstBody();
  31923. for (const node of body) {
  31924. let qualified = isQualifiedType(node, qualifier, refName);
  31925. if (qualified) {
  31926. const extendsTypes = resolveExtendsType(node, qualifier);
  31927. if (extendsTypes.length) {
  31928. const bodies = [...qualified.body];
  31929. filterExtendsType(extendsTypes, bodies);
  31930. qualified.body = bodies;
  31931. }
  31932. return qualified;
  31933. }
  31934. }
  31935. }
  31936. }
  31937. function processDefineExpose(node) {
  31938. if (isCallOf(node, DEFINE_EXPOSE)) {
  31939. if (hasDefineExposeCall) {
  31940. error(`duplicate ${DEFINE_EXPOSE}() call`, node);
  31941. }
  31942. hasDefineExposeCall = true;
  31943. return true;
  31944. }
  31945. return false;
  31946. }
  31947. function checkInvalidScopeReference(node, method) {
  31948. if (!node)
  31949. return;
  31950. walkIdentifiers(node, id => {
  31951. if (setupBindings[id.name]) {
  31952. error(`\`${method}()\` in <script setup> cannot reference locally ` +
  31953. `declared variables because it will be hoisted outside of the ` +
  31954. `setup() function. If your component options require initialization ` +
  31955. `in the module scope, use a separate normal <script> to export ` +
  31956. `the options instead.`, id);
  31957. }
  31958. });
  31959. }
  31960. /**
  31961. * await foo()
  31962. * -->
  31963. * ;(
  31964. * ([__temp,__restore] = withAsyncContext(() => foo())),
  31965. * await __temp,
  31966. * __restore()
  31967. * )
  31968. *
  31969. * const a = await foo()
  31970. * -->
  31971. * const a = (
  31972. * ([__temp, __restore] = withAsyncContext(() => foo())),
  31973. * __temp = await __temp,
  31974. * __restore(),
  31975. * __temp
  31976. * )
  31977. */
  31978. function processAwait(node, needSemi, isStatement) {
  31979. const argumentStart = node.argument.extra && node.argument.extra.parenthesized
  31980. ? node.argument.extra.parenStart
  31981. : node.argument.start;
  31982. const argumentStr = source.slice(argumentStart + startOffset, node.argument.end + startOffset);
  31983. const containsNestedAwait = /\bawait\b/.test(argumentStr);
  31984. s.overwrite(node.start + startOffset, argumentStart + startOffset, `${needSemi ? `;` : ``}(\n ([__temp,__restore] = ${helper(`withAsyncContext`)}(${containsNestedAwait ? `async ` : ``}() => `);
  31985. s.appendLeft(node.end + startOffset, `)),\n ${isStatement ? `` : `__temp = `}await __temp,\n __restore()${isStatement ? `` : `,\n __temp`}\n)`);
  31986. }
  31987. /**
  31988. * check defaults. If the default object is an object literal with only
  31989. * static properties, we can directly generate more optimized default
  31990. * declarations. Otherwise we will have to fallback to runtime merging.
  31991. */
  31992. function hasStaticWithDefaults() {
  31993. return (propsRuntimeDefaults &&
  31994. propsRuntimeDefaults.type === 'ObjectExpression' &&
  31995. propsRuntimeDefaults.properties.every(node => (node.type === 'ObjectProperty' &&
  31996. (!node.computed || node.key.type.endsWith('Literal'))) ||
  31997. node.type === 'ObjectMethod'));
  31998. }
  31999. function genRuntimeProps(props) {
  32000. const keys = Object.keys(props);
  32001. if (!keys.length) {
  32002. return ``;
  32003. }
  32004. const hasStaticDefaults = hasStaticWithDefaults();
  32005. const scriptSetupSource = scriptSetup.content;
  32006. let propsDecls = `{
  32007. ${keys
  32008. .map(key => {
  32009. let defaultString;
  32010. const destructured = genDestructuredDefaultValue(key);
  32011. if (destructured) {
  32012. defaultString = `default: ${destructured}`;
  32013. }
  32014. else if (hasStaticDefaults) {
  32015. const prop = propsRuntimeDefaults.properties.find(node => {
  32016. if (node.type === 'SpreadElement')
  32017. return false;
  32018. return resolveObjectKey(node.key, node.computed) === key;
  32019. });
  32020. if (prop) {
  32021. if (prop.type === 'ObjectProperty') {
  32022. // prop has corresponding static default value
  32023. defaultString = `default: ${scriptSetupSource.slice(prop.value.start, prop.value.end)}`;
  32024. }
  32025. else {
  32026. defaultString = `${prop.async ? 'async ' : ''}${prop.kind !== 'method' ? `${prop.kind} ` : ''}default() ${scriptSetupSource.slice(prop.body.start, prop.body.end)}`;
  32027. }
  32028. }
  32029. }
  32030. const { type, required } = props[key];
  32031. if (!isProd) {
  32032. return `${key}: { type: ${toRuntimeTypeString(type)}, required: ${required}${defaultString ? `, ${defaultString}` : ``} }`;
  32033. }
  32034. else if (type.some(el => el === 'Boolean' || (defaultString && el === 'Function'))) {
  32035. // #4783 production: if boolean or defaultString and function exists, should keep the type.
  32036. return `${key}: { type: ${toRuntimeTypeString(type)}${defaultString ? `, ${defaultString}` : ``} }`;
  32037. }
  32038. else {
  32039. // production: checks are useless
  32040. return `${key}: ${defaultString ? `{ ${defaultString} }` : 'null'}`;
  32041. }
  32042. })
  32043. .join(',\n ')}\n }`;
  32044. if (propsRuntimeDefaults && !hasStaticDefaults) {
  32045. propsDecls = `${helper('mergeDefaults')}(${propsDecls}, ${source.slice(propsRuntimeDefaults.start + startOffset, propsRuntimeDefaults.end + startOffset)})`;
  32046. }
  32047. return `\n props: ${propsDecls},`;
  32048. }
  32049. function genDestructuredDefaultValue(key) {
  32050. const destructured = propsDestructuredBindings[key];
  32051. if (destructured && destructured.default) {
  32052. const value = scriptSetup.content.slice(destructured.default.start, destructured.default.end);
  32053. const isLiteral = destructured.default.type.endsWith('Literal');
  32054. return isLiteral ? value : `() => (${value})`;
  32055. }
  32056. }
  32057. function genSetupPropsType(node) {
  32058. const scriptSetupSource = scriptSetup.content;
  32059. if (hasStaticWithDefaults()) {
  32060. // if withDefaults() is used, we need to remove the optional flags
  32061. // on props that have default values
  32062. let res = `{ `;
  32063. const members = node.type === 'TSTypeLiteral' ? node.members : node.body;
  32064. for (const m of members) {
  32065. if ((m.type === 'TSPropertySignature' ||
  32066. m.type === 'TSMethodSignature') &&
  32067. m.typeAnnotation &&
  32068. m.key.type === 'Identifier') {
  32069. if (propsRuntimeDefaults.properties.some(p => {
  32070. if (p.type === 'SpreadElement')
  32071. return false;
  32072. return (resolveObjectKey(p.key, p.computed) ===
  32073. m.key.name);
  32074. })) {
  32075. res +=
  32076. m.key.name +
  32077. (m.type === 'TSMethodSignature' ? '()' : '') +
  32078. scriptSetupSource.slice(m.typeAnnotation.start, m.typeAnnotation.end) +
  32079. ', ';
  32080. }
  32081. else {
  32082. res +=
  32083. scriptSetupSource.slice(m.start, m.typeAnnotation.end) + `, `;
  32084. }
  32085. }
  32086. }
  32087. return (res.length ? res.slice(0, -2) : res) + ` }`;
  32088. }
  32089. else {
  32090. return scriptSetupSource.slice(node.start, node.end);
  32091. }
  32092. }
  32093. // 0. parse both <script> and <script setup> blocks
  32094. const scriptAst = script &&
  32095. parse(script.content, {
  32096. plugins,
  32097. sourceType: 'module'
  32098. }, scriptStartOffset);
  32099. const scriptSetupAst = parse(scriptSetup.content, {
  32100. plugins: [
  32101. ...plugins,
  32102. // allow top level await but only inside <script setup>
  32103. 'topLevelAwait'
  32104. ],
  32105. sourceType: 'module'
  32106. }, startOffset);
  32107. // 1.1 walk import delcarations of <script>
  32108. if (scriptAst) {
  32109. for (const node of scriptAst.body) {
  32110. if (node.type === 'ImportDeclaration') {
  32111. // record imports for dedupe
  32112. for (const specifier of node.specifiers) {
  32113. const imported = specifier.type === 'ImportSpecifier' &&
  32114. specifier.imported.type === 'Identifier' &&
  32115. specifier.imported.name;
  32116. registerUserImport(node.source.value, specifier.local.name, imported, node.importKind === 'type' ||
  32117. (specifier.type === 'ImportSpecifier' &&
  32118. specifier.importKind === 'type'), false, !options.inlineTemplate);
  32119. }
  32120. }
  32121. }
  32122. }
  32123. // 1.2 walk import declarations of <script setup>
  32124. for (const node of scriptSetupAst.body) {
  32125. if (node.type === 'ImportDeclaration') {
  32126. // import declarations are moved to top
  32127. hoistNode(node);
  32128. // dedupe imports
  32129. let removed = 0;
  32130. const removeSpecifier = (i) => {
  32131. const removeLeft = i > removed;
  32132. removed++;
  32133. const current = node.specifiers[i];
  32134. const next = node.specifiers[i + 1];
  32135. s.remove(removeLeft
  32136. ? node.specifiers[i - 1].end + startOffset
  32137. : current.start + startOffset, next && !removeLeft
  32138. ? next.start + startOffset
  32139. : current.end + startOffset);
  32140. };
  32141. for (let i = 0; i < node.specifiers.length; i++) {
  32142. const specifier = node.specifiers[i];
  32143. const local = specifier.local.name;
  32144. let imported = specifier.type === 'ImportSpecifier' &&
  32145. specifier.imported.type === 'Identifier' &&
  32146. specifier.imported.name;
  32147. if (specifier.type === 'ImportNamespaceSpecifier') {
  32148. imported = '*';
  32149. }
  32150. const source = node.source.value;
  32151. const existing = userImports[local];
  32152. if (source === 'vue' &&
  32153. (imported === DEFINE_PROPS ||
  32154. imported === DEFINE_EMITS ||
  32155. imported === DEFINE_EXPOSE)) {
  32156. warnOnce(`\`${imported}\` is a compiler macro and no longer needs to be imported.`);
  32157. removeSpecifier(i);
  32158. }
  32159. else if (existing) {
  32160. if (existing.source === source && existing.imported === imported) {
  32161. // already imported in <script setup>, dedupe
  32162. removeSpecifier(i);
  32163. }
  32164. else {
  32165. error(`different imports aliased to same local name.`, specifier);
  32166. }
  32167. }
  32168. else {
  32169. registerUserImport(source, local, imported, node.importKind === 'type' ||
  32170. (specifier.type === 'ImportSpecifier' &&
  32171. specifier.importKind === 'type'), true, !options.inlineTemplate);
  32172. }
  32173. }
  32174. if (node.specifiers.length && removed === node.specifiers.length) {
  32175. s.remove(node.start + startOffset, node.end + startOffset);
  32176. }
  32177. }
  32178. }
  32179. // 1.3 resolve possible user import alias of `ref` and `reactive`
  32180. const vueImportAliases = {};
  32181. for (const key in userImports) {
  32182. const { source, imported, local } = userImports[key];
  32183. if (source === 'vue')
  32184. vueImportAliases[imported] = local;
  32185. }
  32186. // 2.1 process normal <script> body
  32187. if (script && scriptAst) {
  32188. for (const node of scriptAst.body) {
  32189. if (node.type === 'ExportDefaultDeclaration') {
  32190. // export default
  32191. defaultExport = node;
  32192. // check if user has manually specified `name` or 'render` option in
  32193. // export default
  32194. // if has name, skip name inference
  32195. // if has render and no template, generate return object instead of
  32196. // empty render function (#4980)
  32197. let optionProperties;
  32198. if (defaultExport.declaration.type === 'ObjectExpression') {
  32199. optionProperties = defaultExport.declaration.properties;
  32200. }
  32201. else if (defaultExport.declaration.type === 'CallExpression' &&
  32202. defaultExport.declaration.arguments[0].type === 'ObjectExpression') {
  32203. optionProperties = defaultExport.declaration.arguments[0].properties;
  32204. }
  32205. if (optionProperties) {
  32206. for (const s of optionProperties) {
  32207. if (s.type === 'ObjectProperty' &&
  32208. s.key.type === 'Identifier' &&
  32209. s.key.name === 'name') {
  32210. hasDefaultExportName = true;
  32211. }
  32212. if ((s.type === 'ObjectMethod' || s.type === 'ObjectProperty') &&
  32213. s.key.type === 'Identifier' &&
  32214. s.key.name === 'render') {
  32215. // TODO warn when we provide a better way to do it?
  32216. hasDefaultExportRender = true;
  32217. }
  32218. }
  32219. }
  32220. // export default { ... } --> const __default__ = { ... }
  32221. const start = node.start + scriptStartOffset;
  32222. const end = node.declaration.start + scriptStartOffset;
  32223. s.overwrite(start, end, `const ${DEFAULT_VAR} = `);
  32224. }
  32225. else if (node.type === 'ExportNamedDeclaration') {
  32226. const defaultSpecifier = node.specifiers.find(s => s.exported.type === 'Identifier' && s.exported.name === 'default');
  32227. if (defaultSpecifier) {
  32228. defaultExport = node;
  32229. // 1. remove specifier
  32230. if (node.specifiers.length > 1) {
  32231. s.remove(defaultSpecifier.start + scriptStartOffset, defaultSpecifier.end + scriptStartOffset);
  32232. }
  32233. else {
  32234. s.remove(node.start + scriptStartOffset, node.end + scriptStartOffset);
  32235. }
  32236. if (node.source) {
  32237. // export { x as default } from './x'
  32238. // rewrite to `import { x as __default__ } from './x'` and
  32239. // add to top
  32240. s.prepend(`import { ${defaultSpecifier.local.name} as ${DEFAULT_VAR} } from '${node.source.value}'\n`);
  32241. }
  32242. else {
  32243. // export { x as default }
  32244. // rewrite to `const __default__ = x` and move to end
  32245. s.appendLeft(scriptEndOffset, `\nconst ${DEFAULT_VAR} = ${defaultSpecifier.local.name}\n`);
  32246. }
  32247. }
  32248. if (node.declaration) {
  32249. walkDeclaration(node.declaration, scriptBindings, vueImportAliases);
  32250. }
  32251. }
  32252. else if ((node.type === 'VariableDeclaration' ||
  32253. node.type === 'FunctionDeclaration' ||
  32254. node.type === 'ClassDeclaration' ||
  32255. node.type === 'TSEnumDeclaration') &&
  32256. !node.declare) {
  32257. walkDeclaration(node, scriptBindings, vueImportAliases);
  32258. }
  32259. }
  32260. // apply reactivity transform
  32261. if (enableReactivityTransform && shouldTransform(script.content)) {
  32262. const { rootRefs, importedHelpers } = transformAST(scriptAst, s, scriptStartOffset);
  32263. refBindings = rootRefs;
  32264. for (const h of importedHelpers) {
  32265. helperImports.add(h);
  32266. }
  32267. }
  32268. // <script> after <script setup>
  32269. // we need to move the block up so that `const __default__` is
  32270. // declared before being used in the actual component definition
  32271. if (scriptStartOffset > startOffset) {
  32272. // if content doesn't end with newline, add one
  32273. if (!/\n$/.test(script.content.trim())) {
  32274. s.appendLeft(scriptEndOffset, `\n`);
  32275. }
  32276. s.move(scriptStartOffset, scriptEndOffset, 0);
  32277. }
  32278. }
  32279. // 2.2 process <script setup> body
  32280. for (const node of scriptSetupAst.body) {
  32281. // (Dropped) `ref: x` bindings
  32282. // TODO remove when out of experimental
  32283. if (node.type === 'LabeledStatement' &&
  32284. node.label.name === 'ref' &&
  32285. node.body.type === 'ExpressionStatement') {
  32286. error(`ref sugar using the label syntax was an experimental proposal and ` +
  32287. `has been dropped based on community feedback. Please check out ` +
  32288. `the new proposal at https://github.com/vuejs/rfcs/discussions/369`, node);
  32289. }
  32290. if (node.type === 'ExpressionStatement') {
  32291. // process `defineProps` and `defineEmit(s)` calls
  32292. if (processDefineProps(node.expression) ||
  32293. processDefineEmits(node.expression) ||
  32294. processWithDefaults(node.expression)) {
  32295. s.remove(node.start + startOffset, node.end + startOffset);
  32296. }
  32297. else if (processDefineExpose(node.expression)) {
  32298. // defineExpose({}) -> expose({})
  32299. const callee = node.expression.callee;
  32300. s.overwrite(callee.start + startOffset, callee.end + startOffset, 'expose');
  32301. }
  32302. }
  32303. if (node.type === 'VariableDeclaration' && !node.declare) {
  32304. const total = node.declarations.length;
  32305. let left = total;
  32306. for (let i = 0; i < total; i++) {
  32307. const decl = node.declarations[i];
  32308. if (decl.init) {
  32309. // defineProps / defineEmits
  32310. const isDefineProps = processDefineProps(decl.init, decl.id) ||
  32311. processWithDefaults(decl.init, decl.id);
  32312. const isDefineEmits = processDefineEmits(decl.init, decl.id);
  32313. if (isDefineProps || isDefineEmits) {
  32314. if (left === 1) {
  32315. s.remove(node.start + startOffset, node.end + startOffset);
  32316. }
  32317. else {
  32318. let start = decl.start + startOffset;
  32319. let end = decl.end + startOffset;
  32320. if (i === 0) {
  32321. // first one, locate the start of the next
  32322. end = node.declarations[i + 1].start + startOffset;
  32323. }
  32324. else {
  32325. // not first one, locate the end of the prev
  32326. start = node.declarations[i - 1].end + startOffset;
  32327. }
  32328. s.remove(start, end);
  32329. left--;
  32330. }
  32331. }
  32332. }
  32333. }
  32334. }
  32335. // walk declarations to record declared bindings
  32336. if ((node.type === 'VariableDeclaration' ||
  32337. node.type === 'FunctionDeclaration' ||
  32338. node.type === 'ClassDeclaration') &&
  32339. !node.declare) {
  32340. walkDeclaration(node, setupBindings, vueImportAliases);
  32341. }
  32342. // walk statements & named exports / variable declarations for top level
  32343. // await
  32344. if ((node.type === 'VariableDeclaration' && !node.declare) ||
  32345. node.type.endsWith('Statement')) {
  32346. const scope = [scriptSetupAst.body];
  32347. walk$1(node, {
  32348. enter(child, parent) {
  32349. if (isFunctionType(child)) {
  32350. this.skip();
  32351. }
  32352. if (child.type === 'BlockStatement') {
  32353. scope.push(child.body);
  32354. }
  32355. if (child.type === 'AwaitExpression') {
  32356. hasAwait = true;
  32357. // if the await expression is an expression statement and
  32358. // - is in the root scope
  32359. // - or is not the first statement in a nested block scope
  32360. // then it needs a semicolon before the generated code.
  32361. const currentScope = scope[scope.length - 1];
  32362. const needsSemi = currentScope.some((n, i) => {
  32363. return ((scope.length === 1 || i > 0) &&
  32364. n.type === 'ExpressionStatement' &&
  32365. n.start === child.start);
  32366. });
  32367. processAwait(child, needsSemi, parent.type === 'ExpressionStatement');
  32368. }
  32369. },
  32370. exit(node) {
  32371. if (node.type === 'BlockStatement')
  32372. scope.pop();
  32373. }
  32374. });
  32375. }
  32376. if ((node.type === 'ExportNamedDeclaration' && node.exportKind !== 'type') ||
  32377. node.type === 'ExportAllDeclaration' ||
  32378. node.type === 'ExportDefaultDeclaration') {
  32379. error(`<script setup> cannot contain ES module exports. ` +
  32380. `If you are using a previous version of <script setup>, please ` +
  32381. `consult the updated RFC at https://github.com/vuejs/rfcs/pull/227.`, node);
  32382. }
  32383. if (isTS) {
  32384. // runtime enum
  32385. if (node.type === 'TSEnumDeclaration') {
  32386. registerBinding(setupBindings, node.id, "setup-const" /* BindingTypes.SETUP_CONST */);
  32387. }
  32388. // move all Type declarations to outer scope
  32389. if (node.type.startsWith('TS') ||
  32390. (node.type === 'ExportNamedDeclaration' &&
  32391. node.exportKind === 'type') ||
  32392. (node.type === 'VariableDeclaration' && node.declare)) {
  32393. recordType(node, declaredTypes);
  32394. hoistNode(node);
  32395. }
  32396. }
  32397. }
  32398. // 3. Apply reactivity transform
  32399. if ((enableReactivityTransform &&
  32400. // normal <script> had ref bindings that maybe used in <script setup>
  32401. (refBindings || shouldTransform(scriptSetup.content))) ||
  32402. propsDestructureDecl) {
  32403. const { rootRefs, importedHelpers } = transformAST(scriptSetupAst, s, startOffset, refBindings, propsDestructuredBindings);
  32404. refBindings = refBindings ? [...refBindings, ...rootRefs] : rootRefs;
  32405. for (const h of importedHelpers) {
  32406. helperImports.add(h);
  32407. }
  32408. }
  32409. // 4. extract runtime props/emits code from setup context type
  32410. if (propsTypeDecl) {
  32411. extractRuntimeProps(propsTypeDecl, typeDeclaredProps, declaredTypes);
  32412. }
  32413. if (emitsTypeDecl) {
  32414. extractRuntimeEmits(emitsTypeDecl, typeDeclaredEmits);
  32415. }
  32416. // 5. check useOptions args to make sure it doesn't reference setup scope
  32417. // variables
  32418. checkInvalidScopeReference(propsRuntimeDecl, DEFINE_PROPS);
  32419. checkInvalidScopeReference(propsRuntimeDefaults, DEFINE_PROPS);
  32420. checkInvalidScopeReference(propsDestructureDecl, DEFINE_PROPS);
  32421. checkInvalidScopeReference(emitsRuntimeDecl, DEFINE_EMITS);
  32422. // 6. remove non-script content
  32423. if (script) {
  32424. if (startOffset < scriptStartOffset) {
  32425. // <script setup> before <script>
  32426. s.remove(0, startOffset);
  32427. s.remove(endOffset, scriptStartOffset);
  32428. s.remove(scriptEndOffset, source.length);
  32429. }
  32430. else {
  32431. // <script> before <script setup>
  32432. s.remove(0, scriptStartOffset);
  32433. s.remove(scriptEndOffset, startOffset);
  32434. s.remove(endOffset, source.length);
  32435. }
  32436. }
  32437. else {
  32438. // only <script setup>
  32439. s.remove(0, startOffset);
  32440. s.remove(endOffset, source.length);
  32441. }
  32442. // 7. analyze binding metadata
  32443. if (scriptAst) {
  32444. Object.assign(bindingMetadata, analyzeScriptBindings(scriptAst.body));
  32445. }
  32446. if (propsRuntimeDecl) {
  32447. for (const key of getObjectOrArrayExpressionKeys(propsRuntimeDecl)) {
  32448. bindingMetadata[key] = "props" /* BindingTypes.PROPS */;
  32449. }
  32450. }
  32451. for (const key in typeDeclaredProps) {
  32452. bindingMetadata[key] = "props" /* BindingTypes.PROPS */;
  32453. }
  32454. // props aliases
  32455. if (propsDestructureDecl) {
  32456. if (propsDestructureRestId) {
  32457. bindingMetadata[propsDestructureRestId] =
  32458. "setup-reactive-const" /* BindingTypes.SETUP_REACTIVE_CONST */;
  32459. }
  32460. for (const key in propsDestructuredBindings) {
  32461. const { local } = propsDestructuredBindings[key];
  32462. if (local !== key) {
  32463. bindingMetadata[local] = "props-aliased" /* BindingTypes.PROPS_ALIASED */;
  32464. (bindingMetadata.__propsAliases ||
  32465. (bindingMetadata.__propsAliases = {}))[local] = key;
  32466. }
  32467. }
  32468. }
  32469. for (const [key, { isType, imported, source }] of Object.entries(userImports)) {
  32470. if (isType)
  32471. continue;
  32472. bindingMetadata[key] =
  32473. imported === '*' ||
  32474. (imported === 'default' && source.endsWith('.vue')) ||
  32475. source === 'vue'
  32476. ? "setup-const" /* BindingTypes.SETUP_CONST */
  32477. : "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */;
  32478. }
  32479. for (const key in scriptBindings) {
  32480. bindingMetadata[key] = scriptBindings[key];
  32481. }
  32482. for (const key in setupBindings) {
  32483. bindingMetadata[key] = setupBindings[key];
  32484. }
  32485. // known ref bindings
  32486. if (refBindings) {
  32487. for (const key of refBindings) {
  32488. bindingMetadata[key] = "setup-ref" /* BindingTypes.SETUP_REF */;
  32489. }
  32490. }
  32491. // 8. inject `useCssVars` calls
  32492. if (cssVars.length &&
  32493. // no need to do this when targeting SSR
  32494. !(options.inlineTemplate && ((_a = options.templateOptions) === null || _a === void 0 ? void 0 : _a.ssr))) {
  32495. helperImports.add(CSS_VARS_HELPER);
  32496. helperImports.add('unref');
  32497. s.prependRight(startOffset, `\n${genCssVarsCode(cssVars, bindingMetadata, scopeId, isProd)}\n`);
  32498. }
  32499. // 9. finalize setup() argument signature
  32500. let args = `__props`;
  32501. if (propsTypeDecl) {
  32502. // mark as any and only cast on assignment
  32503. // since the user defined complex types may be incompatible with the
  32504. // inferred type from generated runtime declarations
  32505. args += `: any`;
  32506. }
  32507. // inject user assignment of props
  32508. // we use a default __props so that template expressions referencing props
  32509. // can use it directly
  32510. if (propsIdentifier) {
  32511. s.prependLeft(startOffset, `\nconst ${propsIdentifier} = __props${propsTypeDecl ? ` as ${genSetupPropsType(propsTypeDecl)}` : ``};\n`);
  32512. }
  32513. if (propsDestructureRestId) {
  32514. s.prependLeft(startOffset, `\nconst ${propsDestructureRestId} = ${helper(`createPropsRestProxy`)}(__props, ${JSON.stringify(Object.keys(propsDestructuredBindings))});\n`);
  32515. }
  32516. // inject temp variables for async context preservation
  32517. if (hasAwait) {
  32518. const any = isTS ? `: any` : ``;
  32519. s.prependLeft(startOffset, `\nlet __temp${any}, __restore${any}\n`);
  32520. }
  32521. const destructureElements = hasDefineExposeCall || !options.inlineTemplate ? [`expose`] : [];
  32522. if (emitIdentifier) {
  32523. destructureElements.push(emitIdentifier === `emit` ? `emit` : `emit: ${emitIdentifier}`);
  32524. }
  32525. if (destructureElements.length) {
  32526. args += `, { ${destructureElements.join(', ')} }`;
  32527. if (emitsTypeDecl) {
  32528. args += `: { emit: (${scriptSetup.content.slice(emitsTypeDecl.start, emitsTypeDecl.end)}), expose: any, slots: any, attrs: any }`;
  32529. }
  32530. }
  32531. // 10. generate return statement
  32532. let returned;
  32533. if (!options.inlineTemplate || (!sfc.template && hasDefaultExportRender)) {
  32534. // non-inline mode, or has manual render in normal <script>
  32535. // return bindings from script and script setup
  32536. const allBindings = Object.assign(Object.assign({}, scriptBindings), setupBindings);
  32537. for (const key in userImports) {
  32538. if (!userImports[key].isType && userImports[key].isUsedInTemplate) {
  32539. allBindings[key] = true;
  32540. }
  32541. }
  32542. returned = `{ `;
  32543. for (const key in allBindings) {
  32544. if (allBindings[key] === true &&
  32545. userImports[key].source !== 'vue' &&
  32546. !userImports[key].source.endsWith('.vue')) {
  32547. // generate getter for import bindings
  32548. // skip vue imports since we know they will never change
  32549. returned += `get ${key}() { return ${key} }, `;
  32550. }
  32551. else if (bindingMetadata[key] === "setup-let" /* BindingTypes.SETUP_LET */) {
  32552. // local let binding, also add setter
  32553. const setArg = key === 'v' ? `_v` : `v`;
  32554. returned +=
  32555. `get ${key}() { return ${key} }, ` +
  32556. `set ${key}(${setArg}) { ${key} = ${setArg} }, `;
  32557. }
  32558. else {
  32559. returned += `${key}, `;
  32560. }
  32561. }
  32562. returned = returned.replace(/, $/, '') + ` }`;
  32563. }
  32564. else {
  32565. // inline mode
  32566. if (sfc.template && !sfc.template.src) {
  32567. if (options.templateOptions && options.templateOptions.ssr) {
  32568. hasInlinedSsrRenderFn = true;
  32569. }
  32570. // inline render function mode - we are going to compile the template and
  32571. // inline it right here
  32572. 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 &&
  32573. options.templateOptions.compilerOptions)), { inline: true, isTS,
  32574. bindingMetadata }) }));
  32575. if (tips.length) {
  32576. tips.forEach(warnOnce);
  32577. }
  32578. const err = errors[0];
  32579. if (typeof err === 'string') {
  32580. throw new Error(err);
  32581. }
  32582. else if (err) {
  32583. if (err.loc) {
  32584. err.message +=
  32585. `\n\n` +
  32586. sfc.filename +
  32587. '\n' +
  32588. generateCodeFrame(source, err.loc.start.offset, err.loc.end.offset) +
  32589. `\n`;
  32590. }
  32591. throw err;
  32592. }
  32593. if (preamble) {
  32594. s.prepend(preamble);
  32595. }
  32596. // avoid duplicated unref import
  32597. // as this may get injected by the render function preamble OR the
  32598. // css vars codegen
  32599. if (ast && ast.helpers.includes(UNREF)) {
  32600. helperImports.delete('unref');
  32601. }
  32602. returned = code;
  32603. }
  32604. else {
  32605. returned = `() => {}`;
  32606. }
  32607. }
  32608. if (!options.inlineTemplate && !false) {
  32609. // in non-inline mode, the `__isScriptSetup: true` flag is used by
  32610. // componentPublicInstance proxy to allow properties that start with $ or _
  32611. s.appendRight(endOffset, `\nconst __returned__ = ${returned}\n` +
  32612. `Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })\n` +
  32613. `return __returned__` +
  32614. `\n}\n\n`);
  32615. }
  32616. else {
  32617. s.appendRight(endOffset, `\nreturn ${returned}\n}\n\n`);
  32618. }
  32619. // 11. finalize default export
  32620. let runtimeOptions = ``;
  32621. if (!hasDefaultExportName && filename && filename !== DEFAULT_FILENAME) {
  32622. const match = filename.match(/([^/\\]+)\.\w+$/);
  32623. if (match) {
  32624. runtimeOptions += `\n __name: '${match[1]}',`;
  32625. }
  32626. }
  32627. if (hasInlinedSsrRenderFn) {
  32628. runtimeOptions += `\n __ssrInlineRender: true,`;
  32629. }
  32630. if (propsRuntimeDecl) {
  32631. let declCode = scriptSetup.content
  32632. .slice(propsRuntimeDecl.start, propsRuntimeDecl.end)
  32633. .trim();
  32634. if (propsDestructureDecl) {
  32635. const defaults = [];
  32636. for (const key in propsDestructuredBindings) {
  32637. const d = genDestructuredDefaultValue(key);
  32638. if (d)
  32639. defaults.push(`${key}: ${d}`);
  32640. }
  32641. if (defaults.length) {
  32642. declCode = `${helper(`mergeDefaults`)}(${declCode}, {\n ${defaults.join(',\n ')}\n})`;
  32643. }
  32644. }
  32645. runtimeOptions += `\n props: ${declCode},`;
  32646. }
  32647. else if (propsTypeDecl) {
  32648. runtimeOptions += genRuntimeProps(typeDeclaredProps);
  32649. }
  32650. if (emitsRuntimeDecl) {
  32651. runtimeOptions += `\n emits: ${scriptSetup.content
  32652. .slice(emitsRuntimeDecl.start, emitsRuntimeDecl.end)
  32653. .trim()},`;
  32654. }
  32655. else if (emitsTypeDecl) {
  32656. runtimeOptions += genRuntimeEmits(typeDeclaredEmits);
  32657. }
  32658. // <script setup> components are closed by default. If the user did not
  32659. // explicitly call `defineExpose`, call expose() with no args.
  32660. const exposeCall = hasDefineExposeCall || options.inlineTemplate ? `` : ` expose();\n`;
  32661. // wrap setup code with function.
  32662. if (isTS) {
  32663. // for TS, make sure the exported type is still valid type with
  32664. // correct props information
  32665. // we have to use object spread for types to be merged properly
  32666. // user's TS setting should compile it down to proper targets
  32667. // export default defineComponent({ ...__default__, ... })
  32668. const def = defaultExport ? `\n ...${DEFAULT_VAR},` : ``;
  32669. s.prependLeft(startOffset, `\nexport default /*#__PURE__*/${helper(`defineComponent`)}({${def}${runtimeOptions}\n ${hasAwait ? `async ` : ``}setup(${args}) {\n${exposeCall}`);
  32670. s.appendRight(endOffset, `})`);
  32671. }
  32672. else {
  32673. if (defaultExport) {
  32674. // without TS, can't rely on rest spread, so we use Object.assign
  32675. // export default Object.assign(__default__, { ... })
  32676. s.prependLeft(startOffset, `\nexport default /*#__PURE__*/Object.assign(${DEFAULT_VAR}, {${runtimeOptions}\n ` +
  32677. `${hasAwait ? `async ` : ``}setup(${args}) {\n${exposeCall}`);
  32678. s.appendRight(endOffset, `})`);
  32679. }
  32680. else {
  32681. s.prependLeft(startOffset, `\nexport default {${runtimeOptions}\n ` +
  32682. `${hasAwait ? `async ` : ``}setup(${args}) {\n${exposeCall}`);
  32683. s.appendRight(endOffset, `}`);
  32684. }
  32685. }
  32686. // 12. finalize Vue helper imports
  32687. if (helperImports.size > 0) {
  32688. s.prepend(`import { ${[...helperImports]
  32689. .map(h => `${h} as _${h}`)
  32690. .join(', ')} } from 'vue'\n`);
  32691. }
  32692. s.trim();
  32693. return Object.assign(Object.assign({}, scriptSetup), { bindings: bindingMetadata, imports: userImports, content: s.toString(), map: genSourceMap
  32694. ? s.generateMap({
  32695. source: filename,
  32696. hires: true,
  32697. includeContent: true
  32698. })
  32699. : undefined, scriptAst: scriptAst === null || scriptAst === void 0 ? void 0 : scriptAst.body, scriptSetupAst: scriptSetupAst === null || scriptSetupAst === void 0 ? void 0 : scriptSetupAst.body });
  32700. }
  32701. function registerBinding(bindings, node, type) {
  32702. bindings[node.name] = type;
  32703. }
  32704. function walkDeclaration(node, bindings, userImportAliases) {
  32705. if (node.type === 'VariableDeclaration') {
  32706. const isConst = node.kind === 'const';
  32707. // export const foo = ...
  32708. for (const { id, init } of node.declarations) {
  32709. const isDefineCall = !!(isConst &&
  32710. isCallOf(init, c => c === DEFINE_PROPS || c === DEFINE_EMITS || c === WITH_DEFAULTS));
  32711. if (id.type === 'Identifier') {
  32712. let bindingType;
  32713. const userReactiveBinding = userImportAliases['reactive'];
  32714. if (isCallOf(init, userReactiveBinding)) {
  32715. // treat reactive() calls as let since it's meant to be mutable
  32716. bindingType = isConst
  32717. ? "setup-reactive-const" /* BindingTypes.SETUP_REACTIVE_CONST */
  32718. : "setup-let" /* BindingTypes.SETUP_LET */;
  32719. }
  32720. else if (
  32721. // if a declaration is a const literal, we can mark it so that
  32722. // the generated render fn code doesn't need to unref() it
  32723. isDefineCall ||
  32724. (isConst && canNeverBeRef(init, userReactiveBinding))) {
  32725. bindingType = isCallOf(init, DEFINE_PROPS)
  32726. ? "setup-reactive-const" /* BindingTypes.SETUP_REACTIVE_CONST */
  32727. : "setup-const" /* BindingTypes.SETUP_CONST */;
  32728. }
  32729. else if (isConst) {
  32730. if (isCallOf(init, userImportAliases['ref'])) {
  32731. bindingType = "setup-ref" /* BindingTypes.SETUP_REF */;
  32732. }
  32733. else {
  32734. bindingType = "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */;
  32735. }
  32736. }
  32737. else {
  32738. bindingType = "setup-let" /* BindingTypes.SETUP_LET */;
  32739. }
  32740. registerBinding(bindings, id, bindingType);
  32741. }
  32742. else {
  32743. if (isCallOf(init, DEFINE_PROPS)) {
  32744. // skip walking props destructure
  32745. return;
  32746. }
  32747. if (id.type === 'ObjectPattern') {
  32748. walkObjectPattern(id, bindings, isConst, isDefineCall);
  32749. }
  32750. else if (id.type === 'ArrayPattern') {
  32751. walkArrayPattern(id, bindings, isConst, isDefineCall);
  32752. }
  32753. }
  32754. }
  32755. }
  32756. else if (node.type === 'TSEnumDeclaration' ||
  32757. node.type === 'FunctionDeclaration' ||
  32758. node.type === 'ClassDeclaration') {
  32759. // export function foo() {} / export class Foo {}
  32760. // export declarations must be named.
  32761. bindings[node.id.name] = "setup-const" /* BindingTypes.SETUP_CONST */;
  32762. }
  32763. }
  32764. function walkObjectPattern(node, bindings, isConst, isDefineCall = false) {
  32765. for (const p of node.properties) {
  32766. if (p.type === 'ObjectProperty') {
  32767. if (p.key.type === 'Identifier' && p.key === p.value) {
  32768. // shorthand: const { x } = ...
  32769. const type = isDefineCall
  32770. ? "setup-const" /* BindingTypes.SETUP_CONST */
  32771. : isConst
  32772. ? "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */
  32773. : "setup-let" /* BindingTypes.SETUP_LET */;
  32774. registerBinding(bindings, p.key, type);
  32775. }
  32776. else {
  32777. walkPattern(p.value, bindings, isConst, isDefineCall);
  32778. }
  32779. }
  32780. else {
  32781. // ...rest
  32782. // argument can only be identifier when destructuring
  32783. const type = isConst ? "setup-const" /* BindingTypes.SETUP_CONST */ : "setup-let" /* BindingTypes.SETUP_LET */;
  32784. registerBinding(bindings, p.argument, type);
  32785. }
  32786. }
  32787. }
  32788. function walkArrayPattern(node, bindings, isConst, isDefineCall = false) {
  32789. for (const e of node.elements) {
  32790. e && walkPattern(e, bindings, isConst, isDefineCall);
  32791. }
  32792. }
  32793. function walkPattern(node, bindings, isConst, isDefineCall = false) {
  32794. if (node.type === 'Identifier') {
  32795. const type = isDefineCall
  32796. ? "setup-const" /* BindingTypes.SETUP_CONST */
  32797. : isConst
  32798. ? "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */
  32799. : "setup-let" /* BindingTypes.SETUP_LET */;
  32800. registerBinding(bindings, node, type);
  32801. }
  32802. else if (node.type === 'RestElement') {
  32803. // argument can only be identifier when destructuring
  32804. const type = isConst ? "setup-const" /* BindingTypes.SETUP_CONST */ : "setup-let" /* BindingTypes.SETUP_LET */;
  32805. registerBinding(bindings, node.argument, type);
  32806. }
  32807. else if (node.type === 'ObjectPattern') {
  32808. walkObjectPattern(node, bindings, isConst);
  32809. }
  32810. else if (node.type === 'ArrayPattern') {
  32811. walkArrayPattern(node, bindings, isConst);
  32812. }
  32813. else if (node.type === 'AssignmentPattern') {
  32814. if (node.left.type === 'Identifier') {
  32815. const type = isDefineCall
  32816. ? "setup-const" /* BindingTypes.SETUP_CONST */
  32817. : isConst
  32818. ? "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */
  32819. : "setup-let" /* BindingTypes.SETUP_LET */;
  32820. registerBinding(bindings, node.left, type);
  32821. }
  32822. else {
  32823. walkPattern(node.left, bindings, isConst);
  32824. }
  32825. }
  32826. }
  32827. function recordType(node, declaredTypes) {
  32828. if (node.type === 'TSInterfaceDeclaration') {
  32829. declaredTypes[node.id.name] = [`Object`];
  32830. }
  32831. else if (node.type === 'TSTypeAliasDeclaration') {
  32832. declaredTypes[node.id.name] = inferRuntimeType(node.typeAnnotation, declaredTypes);
  32833. }
  32834. else if (node.type === 'ExportNamedDeclaration' && node.declaration) {
  32835. recordType(node.declaration, declaredTypes);
  32836. }
  32837. }
  32838. function extractRuntimeProps(node, props, declaredTypes, isProd) {
  32839. const members = node.type === 'TSTypeLiteral' ? node.members : node.body;
  32840. for (const m of members) {
  32841. if ((m.type === 'TSPropertySignature' || m.type === 'TSMethodSignature') &&
  32842. m.key.type === 'Identifier') {
  32843. let type;
  32844. if (m.type === 'TSMethodSignature') {
  32845. type = ['Function'];
  32846. }
  32847. else if (m.typeAnnotation) {
  32848. type = inferRuntimeType(m.typeAnnotation.typeAnnotation, declaredTypes);
  32849. }
  32850. props[m.key.name] = {
  32851. key: m.key.name,
  32852. required: !m.optional,
  32853. type: type || [`null`]
  32854. };
  32855. }
  32856. }
  32857. }
  32858. function inferRuntimeType(node, declaredTypes) {
  32859. switch (node.type) {
  32860. case 'TSStringKeyword':
  32861. return ['String'];
  32862. case 'TSNumberKeyword':
  32863. return ['Number'];
  32864. case 'TSBooleanKeyword':
  32865. return ['Boolean'];
  32866. case 'TSObjectKeyword':
  32867. return ['Object'];
  32868. case 'TSTypeLiteral':
  32869. // TODO (nice to have) generate runtime property validation
  32870. return ['Object'];
  32871. case 'TSFunctionType':
  32872. return ['Function'];
  32873. case 'TSArrayType':
  32874. case 'TSTupleType':
  32875. // TODO (nice to have) generate runtime element type/length checks
  32876. return ['Array'];
  32877. case 'TSLiteralType':
  32878. switch (node.literal.type) {
  32879. case 'StringLiteral':
  32880. return ['String'];
  32881. case 'BooleanLiteral':
  32882. return ['Boolean'];
  32883. case 'NumericLiteral':
  32884. case 'BigIntLiteral':
  32885. return ['Number'];
  32886. default:
  32887. return [`null`];
  32888. }
  32889. case 'TSTypeReference':
  32890. if (node.typeName.type === 'Identifier') {
  32891. if (declaredTypes[node.typeName.name]) {
  32892. return declaredTypes[node.typeName.name];
  32893. }
  32894. switch (node.typeName.name) {
  32895. case 'Array':
  32896. case 'Function':
  32897. case 'Object':
  32898. case 'Set':
  32899. case 'Map':
  32900. case 'WeakSet':
  32901. case 'WeakMap':
  32902. case 'Date':
  32903. case 'Promise':
  32904. return [node.typeName.name];
  32905. case 'Record':
  32906. case 'Partial':
  32907. case 'Readonly':
  32908. case 'Pick':
  32909. case 'Omit':
  32910. case 'Exclude':
  32911. case 'Extract':
  32912. case 'Required':
  32913. case 'InstanceType':
  32914. return ['Object'];
  32915. }
  32916. }
  32917. return [`null`];
  32918. case 'TSParenthesizedType':
  32919. return inferRuntimeType(node.typeAnnotation, declaredTypes);
  32920. case 'TSUnionType':
  32921. return [
  32922. ...new Set([].concat(...node.types.map(t => inferRuntimeType(t, declaredTypes))))
  32923. ];
  32924. case 'TSIntersectionType':
  32925. return ['Object'];
  32926. case 'TSSymbolKeyword':
  32927. return ['Symbol'];
  32928. default:
  32929. return [`null`]; // no runtime check
  32930. }
  32931. }
  32932. function toRuntimeTypeString(types) {
  32933. return types.length > 1 ? `[${types.join(', ')}]` : types[0];
  32934. }
  32935. function extractRuntimeEmits(node, emits) {
  32936. if (node.type === 'TSTypeLiteral' || node.type === 'TSInterfaceBody') {
  32937. const members = node.type === 'TSTypeLiteral' ? node.members : node.body;
  32938. for (let t of members) {
  32939. if (t.type === 'TSCallSignatureDeclaration') {
  32940. extractEventNames(t.parameters[0], emits);
  32941. }
  32942. }
  32943. return;
  32944. }
  32945. else {
  32946. extractEventNames(node.parameters[0], emits);
  32947. }
  32948. }
  32949. function extractEventNames(eventName, emits) {
  32950. if (eventName.type === 'Identifier' &&
  32951. eventName.typeAnnotation &&
  32952. eventName.typeAnnotation.type === 'TSTypeAnnotation') {
  32953. const typeNode = eventName.typeAnnotation.typeAnnotation;
  32954. if (typeNode.type === 'TSLiteralType') {
  32955. if (typeNode.literal.type !== 'UnaryExpression') {
  32956. emits.add(String(typeNode.literal.value));
  32957. }
  32958. }
  32959. else if (typeNode.type === 'TSUnionType') {
  32960. for (const t of typeNode.types) {
  32961. if (t.type === 'TSLiteralType' &&
  32962. t.literal.type !== 'UnaryExpression') {
  32963. emits.add(String(t.literal.value));
  32964. }
  32965. }
  32966. }
  32967. }
  32968. }
  32969. function genRuntimeEmits(emits) {
  32970. return emits.size
  32971. ? `\n emits: [${Array.from(emits)
  32972. .map(p => JSON.stringify(p))
  32973. .join(', ')}],`
  32974. : ``;
  32975. }
  32976. function isCallOf(node, test) {
  32977. return !!(node &&
  32978. test &&
  32979. node.type === 'CallExpression' &&
  32980. node.callee.type === 'Identifier' &&
  32981. (typeof test === 'string'
  32982. ? node.callee.name === test
  32983. : test(node.callee.name)));
  32984. }
  32985. function canNeverBeRef(node, userReactiveImport) {
  32986. if (isCallOf(node, userReactiveImport)) {
  32987. return true;
  32988. }
  32989. switch (node.type) {
  32990. case 'UnaryExpression':
  32991. case 'BinaryExpression':
  32992. case 'ArrayExpression':
  32993. case 'ObjectExpression':
  32994. case 'FunctionExpression':
  32995. case 'ArrowFunctionExpression':
  32996. case 'UpdateExpression':
  32997. case 'ClassExpression':
  32998. case 'TaggedTemplateExpression':
  32999. return true;
  33000. case 'SequenceExpression':
  33001. return canNeverBeRef(node.expressions[node.expressions.length - 1], userReactiveImport);
  33002. default:
  33003. if (node.type.endsWith('Literal')) {
  33004. return true;
  33005. }
  33006. return false;
  33007. }
  33008. }
  33009. /**
  33010. * Analyze bindings in normal `<script>`
  33011. * Note that `compileScriptSetup` already analyzes bindings as part of its
  33012. * compilation process so this should only be used on single `<script>` SFCs.
  33013. */
  33014. function analyzeScriptBindings(ast) {
  33015. for (const node of ast) {
  33016. if (node.type === 'ExportDefaultDeclaration' &&
  33017. node.declaration.type === 'ObjectExpression') {
  33018. return analyzeBindingsFromOptions(node.declaration);
  33019. }
  33020. }
  33021. return {};
  33022. }
  33023. function analyzeBindingsFromOptions(node) {
  33024. const bindings = {};
  33025. // #3270, #3275
  33026. // mark non-script-setup so we don't resolve components/directives from these
  33027. Object.defineProperty(bindings, '__isScriptSetup', {
  33028. enumerable: false,
  33029. value: false
  33030. });
  33031. for (const property of node.properties) {
  33032. if (property.type === 'ObjectProperty' &&
  33033. !property.computed &&
  33034. property.key.type === 'Identifier') {
  33035. // props
  33036. if (property.key.name === 'props') {
  33037. // props: ['foo']
  33038. // props: { foo: ... }
  33039. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  33040. bindings[key] = "props" /* BindingTypes.PROPS */;
  33041. }
  33042. }
  33043. // inject
  33044. else if (property.key.name === 'inject') {
  33045. // inject: ['foo']
  33046. // inject: { foo: {} }
  33047. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  33048. bindings[key] = "options" /* BindingTypes.OPTIONS */;
  33049. }
  33050. }
  33051. // computed & methods
  33052. else if (property.value.type === 'ObjectExpression' &&
  33053. (property.key.name === 'computed' || property.key.name === 'methods')) {
  33054. // methods: { foo() {} }
  33055. // computed: { foo() {} }
  33056. for (const key of getObjectExpressionKeys(property.value)) {
  33057. bindings[key] = "options" /* BindingTypes.OPTIONS */;
  33058. }
  33059. }
  33060. }
  33061. // setup & data
  33062. else if (property.type === 'ObjectMethod' &&
  33063. property.key.type === 'Identifier' &&
  33064. (property.key.name === 'setup' || property.key.name === 'data')) {
  33065. for (const bodyItem of property.body.body) {
  33066. // setup() {
  33067. // return {
  33068. // foo: null
  33069. // }
  33070. // }
  33071. if (bodyItem.type === 'ReturnStatement' &&
  33072. bodyItem.argument &&
  33073. bodyItem.argument.type === 'ObjectExpression') {
  33074. for (const key of getObjectExpressionKeys(bodyItem.argument)) {
  33075. bindings[key] =
  33076. property.key.name === 'setup'
  33077. ? "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */
  33078. : "data" /* BindingTypes.DATA */;
  33079. }
  33080. }
  33081. }
  33082. }
  33083. }
  33084. return bindings;
  33085. }
  33086. function getObjectExpressionKeys(node) {
  33087. const keys = [];
  33088. for (const prop of node.properties) {
  33089. if (prop.type === 'SpreadElement')
  33090. continue;
  33091. const key = resolveObjectKey(prop.key, prop.computed);
  33092. if (key)
  33093. keys.push(String(key));
  33094. }
  33095. return keys;
  33096. }
  33097. function getArrayExpressionKeys(node) {
  33098. const keys = [];
  33099. for (const element of node.elements) {
  33100. if (element && element.type === 'StringLiteral') {
  33101. keys.push(element.value);
  33102. }
  33103. }
  33104. return keys;
  33105. }
  33106. function getObjectOrArrayExpressionKeys(value) {
  33107. if (value.type === 'ArrayExpression') {
  33108. return getArrayExpressionKeys(value);
  33109. }
  33110. if (value.type === 'ObjectExpression') {
  33111. return getObjectExpressionKeys(value);
  33112. }
  33113. return [];
  33114. }
  33115. const templateUsageCheckCache = createCache();
  33116. function resolveTemplateUsageCheckString(sfc) {
  33117. const { content, ast } = sfc.template;
  33118. const cached = templateUsageCheckCache.get(content);
  33119. if (cached) {
  33120. return cached;
  33121. }
  33122. let code = '';
  33123. transform(createRoot([ast]), {
  33124. nodeTransforms: [
  33125. node => {
  33126. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  33127. if (!parserOptions.isNativeTag(node.tag) &&
  33128. !parserOptions.isBuiltInComponent(node.tag)) {
  33129. code += `,${camelize(node.tag)},${capitalize(camelize(node.tag))}`;
  33130. }
  33131. for (let i = 0; i < node.props.length; i++) {
  33132. const prop = node.props[i];
  33133. if (prop.type === 7 /* NodeTypes.DIRECTIVE */) {
  33134. if (!isBuiltInDir(prop.name)) {
  33135. code += `,v${capitalize(camelize(prop.name))}`;
  33136. }
  33137. if (prop.exp) {
  33138. code += `,${processExp(prop.exp.content, prop.name)}`;
  33139. }
  33140. }
  33141. }
  33142. }
  33143. else if (node.type === 5 /* NodeTypes.INTERPOLATION */) {
  33144. code += `,${processExp(node.content.content)}`;
  33145. }
  33146. }
  33147. ]
  33148. });
  33149. code += ';';
  33150. templateUsageCheckCache.set(content, code);
  33151. return code;
  33152. }
  33153. const forAliasRE$1 = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
  33154. function processExp(exp, dir) {
  33155. if (/ as\s+\w|<.*>|:/.test(exp)) {
  33156. if (dir === 'slot') {
  33157. exp = `(${exp})=>{}`;
  33158. }
  33159. else if (dir === 'on') {
  33160. exp = `()=>{return ${exp}}`;
  33161. }
  33162. else if (dir === 'for') {
  33163. const inMatch = exp.match(forAliasRE$1);
  33164. if (inMatch) {
  33165. const [, LHS, RHS] = inMatch;
  33166. return processExp(`(${LHS})=>{}`) + processExp(RHS);
  33167. }
  33168. }
  33169. let ret = '';
  33170. // has potential type cast or generic arguments that uses types
  33171. const ast = parseExpression_1(exp, { plugins: ['typescript'] });
  33172. walkIdentifiers(ast, node => {
  33173. ret += `,` + node.name;
  33174. });
  33175. return ret;
  33176. }
  33177. return stripStrings(exp);
  33178. }
  33179. function stripStrings(exp) {
  33180. return exp
  33181. .replace(/'[^']*'|"[^"]*"/g, '')
  33182. .replace(/`[^`]+`/g, stripTemplateString);
  33183. }
  33184. function stripTemplateString(str) {
  33185. const interpMatch = str.match(/\${[^}]+}/g);
  33186. if (interpMatch) {
  33187. return interpMatch.map(m => m.slice(2, -1)).join(',');
  33188. }
  33189. return '';
  33190. }
  33191. function isImportUsed(local, sfc) {
  33192. return new RegExp(
  33193. // #4274 escape $ since it's a special char in regex
  33194. // (and is the only regex special char that is valid in identifiers)
  33195. `[^\\w$_]${local.replace(/\$/g, '\\$')}[^\\w$_]`).test(resolveTemplateUsageCheckString(sfc));
  33196. }
  33197. /**
  33198. * Note: this comparison assumes the prev/next script are already identical,
  33199. * and only checks the special case where <script setup lang="ts"> unused import
  33200. * pruning result changes due to template changes.
  33201. */
  33202. function hmrShouldReload(prevImports, next) {
  33203. if (!next.scriptSetup ||
  33204. (next.scriptSetup.lang !== 'ts' && next.scriptSetup.lang !== 'tsx')) {
  33205. return false;
  33206. }
  33207. // for each previous import, check if its used status remain the same based on
  33208. // the next descriptor's template
  33209. for (const key in prevImports) {
  33210. // if an import was previous unused, but now is used, we need to force
  33211. // reload so that the script now includes that import.
  33212. if (!prevImports[key].isUsedInTemplate && isImportUsed(key, next)) {
  33213. return true;
  33214. }
  33215. }
  33216. return false;
  33217. }
  33218. function resolveObjectKey(node, computed) {
  33219. switch (node.type) {
  33220. case 'StringLiteral':
  33221. case 'NumericLiteral':
  33222. return node.value;
  33223. case 'Identifier':
  33224. if (!computed)
  33225. return node.name;
  33226. }
  33227. return undefined;
  33228. }
  33229. const DEFAULT_FILENAME = 'anonymous.vue';
  33230. const sourceToSFC = createCache();
  33231. function parse$4(source, { sourceMap = true, filename = DEFAULT_FILENAME, sourceRoot = '', pad = false, ignoreEmpty = true, compiler = CompilerDOM } = {}) {
  33232. const sourceKey = source + sourceMap + filename + sourceRoot + pad + compiler.parse;
  33233. const cache = sourceToSFC.get(sourceKey);
  33234. if (cache) {
  33235. return cache;
  33236. }
  33237. const descriptor = {
  33238. filename,
  33239. source,
  33240. template: null,
  33241. script: null,
  33242. scriptSetup: null,
  33243. styles: [],
  33244. customBlocks: [],
  33245. cssVars: [],
  33246. slotted: false,
  33247. shouldForceReload: prevImports => hmrShouldReload(prevImports, descriptor)
  33248. };
  33249. const errors = [];
  33250. const ast = compiler.parse(source, {
  33251. // there are no components at SFC parsing level
  33252. isNativeTag: () => true,
  33253. // preserve all whitespaces
  33254. isPreTag: () => true,
  33255. getTextMode: ({ tag, props }, parent) => {
  33256. // all top level elements except <template> are parsed as raw text
  33257. // containers
  33258. if ((!parent && tag !== 'template') ||
  33259. // <template lang="xxx"> should also be treated as raw text
  33260. (tag === 'template' &&
  33261. props.some(p => p.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  33262. p.name === 'lang' &&
  33263. p.value &&
  33264. p.value.content &&
  33265. p.value.content !== 'html'))) {
  33266. return 2 /* TextModes.RAWTEXT */;
  33267. }
  33268. else {
  33269. return 0 /* TextModes.DATA */;
  33270. }
  33271. },
  33272. onError: e => {
  33273. errors.push(e);
  33274. }
  33275. });
  33276. ast.children.forEach(node => {
  33277. if (node.type !== 1 /* NodeTypes.ELEMENT */) {
  33278. return;
  33279. }
  33280. // we only want to keep the nodes that are not empty (when the tag is not a template)
  33281. if (ignoreEmpty &&
  33282. node.tag !== 'template' &&
  33283. isEmpty(node) &&
  33284. !hasSrc(node)) {
  33285. return;
  33286. }
  33287. switch (node.tag) {
  33288. case 'template':
  33289. if (!descriptor.template) {
  33290. const templateBlock = (descriptor.template = createBlock(node, source, false));
  33291. templateBlock.ast = node;
  33292. // warn against 2.x <template functional>
  33293. if (templateBlock.attrs.functional) {
  33294. const err = new SyntaxError(`<template functional> is no longer supported in Vue 3, since ` +
  33295. `functional components no longer have significant performance ` +
  33296. `difference from stateful ones. Just use a normal <template> ` +
  33297. `instead.`);
  33298. err.loc = node.props.find(p => p.name === 'functional').loc;
  33299. errors.push(err);
  33300. }
  33301. }
  33302. else {
  33303. errors.push(createDuplicateBlockError(node));
  33304. }
  33305. break;
  33306. case 'script':
  33307. const scriptBlock = createBlock(node, source, pad);
  33308. const isSetup = !!scriptBlock.attrs.setup;
  33309. if (isSetup && !descriptor.scriptSetup) {
  33310. descriptor.scriptSetup = scriptBlock;
  33311. break;
  33312. }
  33313. if (!isSetup && !descriptor.script) {
  33314. descriptor.script = scriptBlock;
  33315. break;
  33316. }
  33317. errors.push(createDuplicateBlockError(node, isSetup));
  33318. break;
  33319. case 'style':
  33320. const styleBlock = createBlock(node, source, pad);
  33321. if (styleBlock.attrs.vars) {
  33322. errors.push(new SyntaxError(`<style vars> has been replaced by a new proposal: ` +
  33323. `https://github.com/vuejs/rfcs/pull/231`));
  33324. }
  33325. descriptor.styles.push(styleBlock);
  33326. break;
  33327. default:
  33328. descriptor.customBlocks.push(createBlock(node, source, pad));
  33329. break;
  33330. }
  33331. });
  33332. if (!descriptor.template && !descriptor.script && !descriptor.scriptSetup) {
  33333. errors.push(new SyntaxError(`At least one <template> or <script> is required in a single file component.`));
  33334. }
  33335. if (descriptor.scriptSetup) {
  33336. if (descriptor.scriptSetup.src) {
  33337. errors.push(new SyntaxError(`<script setup> cannot use the "src" attribute because ` +
  33338. `its syntax will be ambiguous outside of the component.`));
  33339. descriptor.scriptSetup = null;
  33340. }
  33341. if (descriptor.script && descriptor.script.src) {
  33342. errors.push(new SyntaxError(`<script> cannot use the "src" attribute when <script setup> is ` +
  33343. `also present because they must be processed together.`));
  33344. descriptor.script = null;
  33345. }
  33346. }
  33347. if (sourceMap) {
  33348. const genMap = (block) => {
  33349. if (block && !block.src) {
  33350. block.map = generateSourceMap(filename, source, block.content, sourceRoot, !pad || block.type === 'template' ? block.loc.start.line - 1 : 0);
  33351. }
  33352. };
  33353. genMap(descriptor.template);
  33354. genMap(descriptor.script);
  33355. descriptor.styles.forEach(genMap);
  33356. descriptor.customBlocks.forEach(genMap);
  33357. }
  33358. // parse CSS vars
  33359. descriptor.cssVars = parseCssVars(descriptor);
  33360. // check if the SFC uses :slotted
  33361. const slottedRE = /(?:::v-|:)slotted\(/;
  33362. descriptor.slotted = descriptor.styles.some(s => s.scoped && slottedRE.test(s.content));
  33363. const result = {
  33364. descriptor,
  33365. errors
  33366. };
  33367. sourceToSFC.set(sourceKey, result);
  33368. return result;
  33369. }
  33370. function createDuplicateBlockError(node, isScriptSetup = false) {
  33371. const err = new SyntaxError(`Single file component can contain only one <${node.tag}${isScriptSetup ? ` setup` : ``}> element`);
  33372. err.loc = node.loc;
  33373. return err;
  33374. }
  33375. function createBlock(node, source, pad) {
  33376. const type = node.tag;
  33377. let { start, end } = node.loc;
  33378. let content = '';
  33379. if (node.children.length) {
  33380. start = node.children[0].loc.start;
  33381. end = node.children[node.children.length - 1].loc.end;
  33382. content = source.slice(start.offset, end.offset);
  33383. }
  33384. else {
  33385. const offset = node.loc.source.indexOf(`</`);
  33386. if (offset > -1) {
  33387. start = {
  33388. line: start.line,
  33389. column: start.column + offset,
  33390. offset: start.offset + offset
  33391. };
  33392. }
  33393. end = Object.assign({}, start);
  33394. }
  33395. const loc = {
  33396. source: content,
  33397. start,
  33398. end
  33399. };
  33400. const attrs = {};
  33401. const block = {
  33402. type,
  33403. content,
  33404. loc,
  33405. attrs
  33406. };
  33407. if (pad) {
  33408. block.content = padContent(source, block, pad) + block.content;
  33409. }
  33410. node.props.forEach(p => {
  33411. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  33412. attrs[p.name] = p.value ? p.value.content || true : true;
  33413. if (p.name === 'lang') {
  33414. block.lang = p.value && p.value.content;
  33415. }
  33416. else if (p.name === 'src') {
  33417. block.src = p.value && p.value.content;
  33418. }
  33419. else if (type === 'style') {
  33420. if (p.name === 'scoped') {
  33421. block.scoped = true;
  33422. }
  33423. else if (p.name === 'module') {
  33424. block.module = attrs[p.name];
  33425. }
  33426. }
  33427. else if (type === 'script' && p.name === 'setup') {
  33428. block.setup = attrs.setup;
  33429. }
  33430. }
  33431. });
  33432. return block;
  33433. }
  33434. const splitRE = /\r?\n/g;
  33435. const emptyRE = /^(?:\/\/)?\s*$/;
  33436. const replaceRE = /./g;
  33437. function generateSourceMap(filename, source, generated, sourceRoot, lineOffset) {
  33438. const map = new SourceMapGenerator$2({
  33439. file: filename.replace(/\\/g, '/'),
  33440. sourceRoot: sourceRoot.replace(/\\/g, '/')
  33441. });
  33442. map.setSourceContent(filename, source);
  33443. generated.split(splitRE).forEach((line, index) => {
  33444. if (!emptyRE.test(line)) {
  33445. const originalLine = index + 1 + lineOffset;
  33446. const generatedLine = index + 1;
  33447. for (let i = 0; i < line.length; i++) {
  33448. if (!/\s/.test(line[i])) {
  33449. map.addMapping({
  33450. source: filename,
  33451. original: {
  33452. line: originalLine,
  33453. column: i
  33454. },
  33455. generated: {
  33456. line: generatedLine,
  33457. column: i
  33458. }
  33459. });
  33460. }
  33461. }
  33462. }
  33463. });
  33464. return JSON.parse(map.toString());
  33465. }
  33466. function padContent(content, block, pad) {
  33467. content = content.slice(0, block.loc.start.offset);
  33468. if (pad === 'space') {
  33469. return content.replace(replaceRE, ' ');
  33470. }
  33471. else {
  33472. const offset = content.split(splitRE).length;
  33473. const padChar = block.type === 'script' && !block.lang ? '//\n' : '\n';
  33474. return Array(offset).join(padChar);
  33475. }
  33476. }
  33477. function hasSrc(node) {
  33478. return node.props.some(p => {
  33479. if (p.type !== 6 /* NodeTypes.ATTRIBUTE */) {
  33480. return false;
  33481. }
  33482. return p.name === 'src';
  33483. });
  33484. }
  33485. /**
  33486. * Returns true if the node has no children
  33487. * once the empty text nodes (trimmed content) have been filtered out.
  33488. */
  33489. function isEmpty(node) {
  33490. for (let i = 0; i < node.children.length; i++) {
  33491. const child = node.children[i];
  33492. if (child.type !== 2 /* NodeTypes.TEXT */ || child.content.trim() !== '') {
  33493. return false;
  33494. }
  33495. }
  33496. return true;
  33497. }
  33498. // MIT lisence
  33499. // from https://github.com/substack/tty-browserify/blob/1ba769a6429d242f36226538835b4034bf6b7886/index.js
  33500. function isatty() {
  33501. return false;
  33502. }
  33503. function ReadStream() {
  33504. throw new Error('tty.ReadStream is not implemented');
  33505. }
  33506. function WriteStream() {
  33507. throw new Error('tty.ReadStream is not implemented');
  33508. }
  33509. var _polyfillNode_tty = {
  33510. isatty: isatty,
  33511. ReadStream: ReadStream,
  33512. WriteStream: WriteStream
  33513. };
  33514. var _polyfillNode_tty$1 = /*#__PURE__*/Object.freeze({
  33515. __proto__: null,
  33516. isatty: isatty,
  33517. ReadStream: ReadStream,
  33518. WriteStream: WriteStream,
  33519. 'default': _polyfillNode_tty
  33520. });
  33521. var tty = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_tty$1);
  33522. let isColorSupported =
  33523. !("NO_COLOR" in ({}) || browser$1.argv.includes("--no-color")) &&
  33524. ("FORCE_COLOR" in ({}) ||
  33525. browser$1.argv.includes("--color") ||
  33526. "" === "win32" ||
  33527. (tty.isatty(1) && ({}).TERM !== "dumb") ||
  33528. "CI" in ({}));
  33529. let formatter =
  33530. (open, close, replace = open) =>
  33531. input => {
  33532. let string = "" + input;
  33533. let index = string.indexOf(close, open.length);
  33534. return ~index
  33535. ? open + replaceClose(string, close, replace, index) + close
  33536. : open + string + close
  33537. };
  33538. let replaceClose = (string, close, replace, index) => {
  33539. let start = string.substring(0, index) + replace;
  33540. let end = string.substring(index + close.length);
  33541. let nextIndex = end.indexOf(close);
  33542. return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end
  33543. };
  33544. let createColors = (enabled = isColorSupported) => ({
  33545. isColorSupported: enabled,
  33546. reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String,
  33547. bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String,
  33548. dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String,
  33549. italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String,
  33550. underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String,
  33551. inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String,
  33552. hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String,
  33553. strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String,
  33554. black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String,
  33555. red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String,
  33556. green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String,
  33557. yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String,
  33558. blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String,
  33559. magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String,
  33560. cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String,
  33561. white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String,
  33562. gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String,
  33563. bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String,
  33564. bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String,
  33565. bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String,
  33566. bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String,
  33567. bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String,
  33568. bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String,
  33569. bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String,
  33570. bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String,
  33571. });
  33572. var picocolors = createColors();
  33573. var createColors_1 = createColors;
  33574. picocolors.createColors = createColors_1;
  33575. const SINGLE_QUOTE = "'".charCodeAt(0);
  33576. const DOUBLE_QUOTE = '"'.charCodeAt(0);
  33577. const BACKSLASH = '\\'.charCodeAt(0);
  33578. const SLASH = '/'.charCodeAt(0);
  33579. const NEWLINE = '\n'.charCodeAt(0);
  33580. const SPACE = ' '.charCodeAt(0);
  33581. const FEED = '\f'.charCodeAt(0);
  33582. const TAB = '\t'.charCodeAt(0);
  33583. const CR = '\r'.charCodeAt(0);
  33584. const OPEN_SQUARE = '['.charCodeAt(0);
  33585. const CLOSE_SQUARE = ']'.charCodeAt(0);
  33586. const OPEN_PARENTHESES = '('.charCodeAt(0);
  33587. const CLOSE_PARENTHESES = ')'.charCodeAt(0);
  33588. const OPEN_CURLY = '{'.charCodeAt(0);
  33589. const CLOSE_CURLY = '}'.charCodeAt(0);
  33590. const SEMICOLON = ';'.charCodeAt(0);
  33591. const ASTERISK = '*'.charCodeAt(0);
  33592. const COLON = ':'.charCodeAt(0);
  33593. const AT = '@'.charCodeAt(0);
  33594. const RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g;
  33595. const RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g;
  33596. const RE_BAD_BRACKET = /.[\n"'(/\\]/;
  33597. const RE_HEX_ESCAPE = /[\da-f]/i;
  33598. var tokenize = function tokenizer(input, options = {}) {
  33599. let css = input.css.valueOf();
  33600. let ignore = options.ignoreErrors;
  33601. let code, next, quote, content, escape;
  33602. let escaped, escapePos, prev, n, currentToken;
  33603. let length = css.length;
  33604. let pos = 0;
  33605. let buffer = [];
  33606. let returned = [];
  33607. function position() {
  33608. return pos
  33609. }
  33610. function unclosed(what) {
  33611. throw input.error('Unclosed ' + what, pos)
  33612. }
  33613. function endOfFile() {
  33614. return returned.length === 0 && pos >= length
  33615. }
  33616. function nextToken(opts) {
  33617. if (returned.length) return returned.pop()
  33618. if (pos >= length) return
  33619. let ignoreUnclosed = opts ? opts.ignoreUnclosed : false;
  33620. code = css.charCodeAt(pos);
  33621. switch (code) {
  33622. case NEWLINE:
  33623. case SPACE:
  33624. case TAB:
  33625. case CR:
  33626. case FEED: {
  33627. next = pos;
  33628. do {
  33629. next += 1;
  33630. code = css.charCodeAt(next);
  33631. } while (
  33632. code === SPACE ||
  33633. code === NEWLINE ||
  33634. code === TAB ||
  33635. code === CR ||
  33636. code === FEED
  33637. )
  33638. currentToken = ['space', css.slice(pos, next)];
  33639. pos = next - 1;
  33640. break
  33641. }
  33642. case OPEN_SQUARE:
  33643. case CLOSE_SQUARE:
  33644. case OPEN_CURLY:
  33645. case CLOSE_CURLY:
  33646. case COLON:
  33647. case SEMICOLON:
  33648. case CLOSE_PARENTHESES: {
  33649. let controlChar = String.fromCharCode(code);
  33650. currentToken = [controlChar, controlChar, pos];
  33651. break
  33652. }
  33653. case OPEN_PARENTHESES: {
  33654. prev = buffer.length ? buffer.pop()[1] : '';
  33655. n = css.charCodeAt(pos + 1);
  33656. if (
  33657. prev === 'url' &&
  33658. n !== SINGLE_QUOTE &&
  33659. n !== DOUBLE_QUOTE &&
  33660. n !== SPACE &&
  33661. n !== NEWLINE &&
  33662. n !== TAB &&
  33663. n !== FEED &&
  33664. n !== CR
  33665. ) {
  33666. next = pos;
  33667. do {
  33668. escaped = false;
  33669. next = css.indexOf(')', next + 1);
  33670. if (next === -1) {
  33671. if (ignore || ignoreUnclosed) {
  33672. next = pos;
  33673. break
  33674. } else {
  33675. unclosed('bracket');
  33676. }
  33677. }
  33678. escapePos = next;
  33679. while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
  33680. escapePos -= 1;
  33681. escaped = !escaped;
  33682. }
  33683. } while (escaped)
  33684. currentToken = ['brackets', css.slice(pos, next + 1), pos, next];
  33685. pos = next;
  33686. } else {
  33687. next = css.indexOf(')', pos + 1);
  33688. content = css.slice(pos, next + 1);
  33689. if (next === -1 || RE_BAD_BRACKET.test(content)) {
  33690. currentToken = ['(', '(', pos];
  33691. } else {
  33692. currentToken = ['brackets', content, pos, next];
  33693. pos = next;
  33694. }
  33695. }
  33696. break
  33697. }
  33698. case SINGLE_QUOTE:
  33699. case DOUBLE_QUOTE: {
  33700. quote = code === SINGLE_QUOTE ? "'" : '"';
  33701. next = pos;
  33702. do {
  33703. escaped = false;
  33704. next = css.indexOf(quote, next + 1);
  33705. if (next === -1) {
  33706. if (ignore || ignoreUnclosed) {
  33707. next = pos + 1;
  33708. break
  33709. } else {
  33710. unclosed('string');
  33711. }
  33712. }
  33713. escapePos = next;
  33714. while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
  33715. escapePos -= 1;
  33716. escaped = !escaped;
  33717. }
  33718. } while (escaped)
  33719. currentToken = ['string', css.slice(pos, next + 1), pos, next];
  33720. pos = next;
  33721. break
  33722. }
  33723. case AT: {
  33724. RE_AT_END.lastIndex = pos + 1;
  33725. RE_AT_END.test(css);
  33726. if (RE_AT_END.lastIndex === 0) {
  33727. next = css.length - 1;
  33728. } else {
  33729. next = RE_AT_END.lastIndex - 2;
  33730. }
  33731. currentToken = ['at-word', css.slice(pos, next + 1), pos, next];
  33732. pos = next;
  33733. break
  33734. }
  33735. case BACKSLASH: {
  33736. next = pos;
  33737. escape = true;
  33738. while (css.charCodeAt(next + 1) === BACKSLASH) {
  33739. next += 1;
  33740. escape = !escape;
  33741. }
  33742. code = css.charCodeAt(next + 1);
  33743. if (
  33744. escape &&
  33745. code !== SLASH &&
  33746. code !== SPACE &&
  33747. code !== NEWLINE &&
  33748. code !== TAB &&
  33749. code !== CR &&
  33750. code !== FEED
  33751. ) {
  33752. next += 1;
  33753. if (RE_HEX_ESCAPE.test(css.charAt(next))) {
  33754. while (RE_HEX_ESCAPE.test(css.charAt(next + 1))) {
  33755. next += 1;
  33756. }
  33757. if (css.charCodeAt(next + 1) === SPACE) {
  33758. next += 1;
  33759. }
  33760. }
  33761. }
  33762. currentToken = ['word', css.slice(pos, next + 1), pos, next];
  33763. pos = next;
  33764. break
  33765. }
  33766. default: {
  33767. if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) {
  33768. next = css.indexOf('*/', pos + 2) + 1;
  33769. if (next === 0) {
  33770. if (ignore || ignoreUnclosed) {
  33771. next = css.length;
  33772. } else {
  33773. unclosed('comment');
  33774. }
  33775. }
  33776. currentToken = ['comment', css.slice(pos, next + 1), pos, next];
  33777. pos = next;
  33778. } else {
  33779. RE_WORD_END.lastIndex = pos + 1;
  33780. RE_WORD_END.test(css);
  33781. if (RE_WORD_END.lastIndex === 0) {
  33782. next = css.length - 1;
  33783. } else {
  33784. next = RE_WORD_END.lastIndex - 2;
  33785. }
  33786. currentToken = ['word', css.slice(pos, next + 1), pos, next];
  33787. buffer.push(currentToken);
  33788. pos = next;
  33789. }
  33790. break
  33791. }
  33792. }
  33793. pos++;
  33794. return currentToken
  33795. }
  33796. function back(token) {
  33797. returned.push(token);
  33798. }
  33799. return {
  33800. back,
  33801. nextToken,
  33802. endOfFile,
  33803. position
  33804. }
  33805. };
  33806. let Input;
  33807. function registerInput(dependant) {
  33808. Input = dependant;
  33809. }
  33810. const HIGHLIGHT_THEME = {
  33811. 'brackets': picocolors.cyan,
  33812. 'at-word': picocolors.cyan,
  33813. 'comment': picocolors.gray,
  33814. 'string': picocolors.green,
  33815. 'class': picocolors.yellow,
  33816. 'hash': picocolors.magenta,
  33817. 'call': picocolors.cyan,
  33818. '(': picocolors.cyan,
  33819. ')': picocolors.cyan,
  33820. '{': picocolors.yellow,
  33821. '}': picocolors.yellow,
  33822. '[': picocolors.yellow,
  33823. ']': picocolors.yellow,
  33824. ':': picocolors.yellow,
  33825. ';': picocolors.yellow
  33826. };
  33827. function getTokenType([type, value], processor) {
  33828. if (type === 'word') {
  33829. if (value[0] === '.') {
  33830. return 'class'
  33831. }
  33832. if (value[0] === '#') {
  33833. return 'hash'
  33834. }
  33835. }
  33836. if (!processor.endOfFile()) {
  33837. let next = processor.nextToken();
  33838. processor.back(next);
  33839. if (next[0] === 'brackets' || next[0] === '(') return 'call'
  33840. }
  33841. return type
  33842. }
  33843. function terminalHighlight(css) {
  33844. let processor = tokenize(new Input(css), { ignoreErrors: true });
  33845. let result = '';
  33846. while (!processor.endOfFile()) {
  33847. let token = processor.nextToken();
  33848. let color = HIGHLIGHT_THEME[getTokenType(token, processor)];
  33849. if (color) {
  33850. result += token[1]
  33851. .split(/\r?\n/)
  33852. .map(i => color(i))
  33853. .join('\n');
  33854. } else {
  33855. result += token[1];
  33856. }
  33857. }
  33858. return result
  33859. }
  33860. terminalHighlight.registerInput = registerInput;
  33861. var terminalHighlight_1 = terminalHighlight;
  33862. class CssSyntaxError extends Error {
  33863. constructor(message, line, column, source, file, plugin) {
  33864. super(message);
  33865. this.name = 'CssSyntaxError';
  33866. this.reason = message;
  33867. if (file) {
  33868. this.file = file;
  33869. }
  33870. if (source) {
  33871. this.source = source;
  33872. }
  33873. if (plugin) {
  33874. this.plugin = plugin;
  33875. }
  33876. if (typeof line !== 'undefined' && typeof column !== 'undefined') {
  33877. if (typeof line === 'number') {
  33878. this.line = line;
  33879. this.column = column;
  33880. } else {
  33881. this.line = line.line;
  33882. this.column = line.column;
  33883. this.endLine = column.line;
  33884. this.endColumn = column.column;
  33885. }
  33886. }
  33887. this.setMessage();
  33888. if (Error.captureStackTrace) {
  33889. Error.captureStackTrace(this, CssSyntaxError);
  33890. }
  33891. }
  33892. setMessage() {
  33893. this.message = this.plugin ? this.plugin + ': ' : '';
  33894. this.message += this.file ? this.file : '<css input>';
  33895. if (typeof this.line !== 'undefined') {
  33896. this.message += ':' + this.line + ':' + this.column;
  33897. }
  33898. this.message += ': ' + this.reason;
  33899. }
  33900. showSourceCode(color) {
  33901. if (!this.source) return ''
  33902. let css = this.source;
  33903. if (color == null) color = picocolors.isColorSupported;
  33904. if (terminalHighlight_1) {
  33905. if (color) css = terminalHighlight_1(css);
  33906. }
  33907. let lines = css.split(/\r?\n/);
  33908. let start = Math.max(this.line - 3, 0);
  33909. let end = Math.min(this.line + 2, lines.length);
  33910. let maxWidth = String(end).length;
  33911. let mark, aside;
  33912. if (color) {
  33913. let { bold, red, gray } = picocolors.createColors(true);
  33914. mark = text => bold(red(text));
  33915. aside = text => gray(text);
  33916. } else {
  33917. mark = aside = str => str;
  33918. }
  33919. return lines
  33920. .slice(start, end)
  33921. .map((line, index) => {
  33922. let number = start + 1 + index;
  33923. let gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | ';
  33924. if (number === this.line) {
  33925. let spacing =
  33926. aside(gutter.replace(/\d/g, ' ')) +
  33927. line.slice(0, this.column - 1).replace(/[^\t]/g, ' ');
  33928. return mark('>') + aside(gutter) + line + '\n ' + spacing + mark('^')
  33929. }
  33930. return ' ' + aside(gutter) + line
  33931. })
  33932. .join('\n')
  33933. }
  33934. toString() {
  33935. let code = this.showSourceCode();
  33936. if (code) {
  33937. code = '\n\n' + code + '\n';
  33938. }
  33939. return this.name + ': ' + this.message + code
  33940. }
  33941. }
  33942. var cssSyntaxError = CssSyntaxError;
  33943. CssSyntaxError.default = CssSyntaxError;
  33944. var isClean = Symbol('isClean');
  33945. var my = Symbol('my');
  33946. var symbols = {
  33947. isClean: isClean,
  33948. my: my
  33949. };
  33950. const DEFAULT_RAW = {
  33951. colon: ': ',
  33952. indent: ' ',
  33953. beforeDecl: '\n',
  33954. beforeRule: '\n',
  33955. beforeOpen: ' ',
  33956. beforeClose: '\n',
  33957. beforeComment: '\n',
  33958. after: '\n',
  33959. emptyBody: '',
  33960. commentLeft: ' ',
  33961. commentRight: ' ',
  33962. semicolon: false
  33963. };
  33964. function capitalize$1(str) {
  33965. return str[0].toUpperCase() + str.slice(1)
  33966. }
  33967. class Stringifier {
  33968. constructor(builder) {
  33969. this.builder = builder;
  33970. }
  33971. stringify(node, semicolon) {
  33972. /* c8 ignore start */
  33973. if (!this[node.type]) {
  33974. throw new Error(
  33975. 'Unknown AST node type ' +
  33976. node.type +
  33977. '. ' +
  33978. 'Maybe you need to change PostCSS stringifier.'
  33979. )
  33980. }
  33981. /* c8 ignore stop */
  33982. this[node.type](node, semicolon);
  33983. }
  33984. document(node) {
  33985. this.body(node);
  33986. }
  33987. root(node) {
  33988. this.body(node);
  33989. if (node.raws.after) this.builder(node.raws.after);
  33990. }
  33991. comment(node) {
  33992. let left = this.raw(node, 'left', 'commentLeft');
  33993. let right = this.raw(node, 'right', 'commentRight');
  33994. this.builder('/*' + left + node.text + right + '*/', node);
  33995. }
  33996. decl(node, semicolon) {
  33997. let between = this.raw(node, 'between', 'colon');
  33998. let string = node.prop + between + this.rawValue(node, 'value');
  33999. if (node.important) {
  34000. string += node.raws.important || ' !important';
  34001. }
  34002. if (semicolon) string += ';';
  34003. this.builder(string, node);
  34004. }
  34005. rule(node) {
  34006. this.block(node, this.rawValue(node, 'selector'));
  34007. if (node.raws.ownSemicolon) {
  34008. this.builder(node.raws.ownSemicolon, node, 'end');
  34009. }
  34010. }
  34011. atrule(node, semicolon) {
  34012. let name = '@' + node.name;
  34013. let params = node.params ? this.rawValue(node, 'params') : '';
  34014. if (typeof node.raws.afterName !== 'undefined') {
  34015. name += node.raws.afterName;
  34016. } else if (params) {
  34017. name += ' ';
  34018. }
  34019. if (node.nodes) {
  34020. this.block(node, name + params);
  34021. } else {
  34022. let end = (node.raws.between || '') + (semicolon ? ';' : '');
  34023. this.builder(name + params + end, node);
  34024. }
  34025. }
  34026. body(node) {
  34027. let last = node.nodes.length - 1;
  34028. while (last > 0) {
  34029. if (node.nodes[last].type !== 'comment') break
  34030. last -= 1;
  34031. }
  34032. let semicolon = this.raw(node, 'semicolon');
  34033. for (let i = 0; i < node.nodes.length; i++) {
  34034. let child = node.nodes[i];
  34035. let before = this.raw(child, 'before');
  34036. if (before) this.builder(before);
  34037. this.stringify(child, last !== i || semicolon);
  34038. }
  34039. }
  34040. block(node, start) {
  34041. let between = this.raw(node, 'between', 'beforeOpen');
  34042. this.builder(start + between + '{', node, 'start');
  34043. let after;
  34044. if (node.nodes && node.nodes.length) {
  34045. this.body(node);
  34046. after = this.raw(node, 'after');
  34047. } else {
  34048. after = this.raw(node, 'after', 'emptyBody');
  34049. }
  34050. if (after) this.builder(after);
  34051. this.builder('}', node, 'end');
  34052. }
  34053. raw(node, own, detect) {
  34054. let value;
  34055. if (!detect) detect = own;
  34056. // Already had
  34057. if (own) {
  34058. value = node.raws[own];
  34059. if (typeof value !== 'undefined') return value
  34060. }
  34061. let parent = node.parent;
  34062. if (detect === 'before') {
  34063. // Hack for first rule in CSS
  34064. if (!parent || (parent.type === 'root' && parent.first === node)) {
  34065. return ''
  34066. }
  34067. // `root` nodes in `document` should use only their own raws
  34068. if (parent && parent.type === 'document') {
  34069. return ''
  34070. }
  34071. }
  34072. // Floating child without parent
  34073. if (!parent) return DEFAULT_RAW[detect]
  34074. // Detect style by other nodes
  34075. let root = node.root();
  34076. if (!root.rawCache) root.rawCache = {};
  34077. if (typeof root.rawCache[detect] !== 'undefined') {
  34078. return root.rawCache[detect]
  34079. }
  34080. if (detect === 'before' || detect === 'after') {
  34081. return this.beforeAfter(node, detect)
  34082. } else {
  34083. let method = 'raw' + capitalize$1(detect);
  34084. if (this[method]) {
  34085. value = this[method](root, node);
  34086. } else {
  34087. root.walk(i => {
  34088. value = i.raws[own];
  34089. if (typeof value !== 'undefined') return false
  34090. });
  34091. }
  34092. }
  34093. if (typeof value === 'undefined') value = DEFAULT_RAW[detect];
  34094. root.rawCache[detect] = value;
  34095. return value
  34096. }
  34097. rawSemicolon(root) {
  34098. let value;
  34099. root.walk(i => {
  34100. if (i.nodes && i.nodes.length && i.last.type === 'decl') {
  34101. value = i.raws.semicolon;
  34102. if (typeof value !== 'undefined') return false
  34103. }
  34104. });
  34105. return value
  34106. }
  34107. rawEmptyBody(root) {
  34108. let value;
  34109. root.walk(i => {
  34110. if (i.nodes && i.nodes.length === 0) {
  34111. value = i.raws.after;
  34112. if (typeof value !== 'undefined') return false
  34113. }
  34114. });
  34115. return value
  34116. }
  34117. rawIndent(root) {
  34118. if (root.raws.indent) return root.raws.indent
  34119. let value;
  34120. root.walk(i => {
  34121. let p = i.parent;
  34122. if (p && p !== root && p.parent && p.parent === root) {
  34123. if (typeof i.raws.before !== 'undefined') {
  34124. let parts = i.raws.before.split('\n');
  34125. value = parts[parts.length - 1];
  34126. value = value.replace(/\S/g, '');
  34127. return false
  34128. }
  34129. }
  34130. });
  34131. return value
  34132. }
  34133. rawBeforeComment(root, node) {
  34134. let value;
  34135. root.walkComments(i => {
  34136. if (typeof i.raws.before !== 'undefined') {
  34137. value = i.raws.before;
  34138. if (value.includes('\n')) {
  34139. value = value.replace(/[^\n]+$/, '');
  34140. }
  34141. return false
  34142. }
  34143. });
  34144. if (typeof value === 'undefined') {
  34145. value = this.raw(node, null, 'beforeDecl');
  34146. } else if (value) {
  34147. value = value.replace(/\S/g, '');
  34148. }
  34149. return value
  34150. }
  34151. rawBeforeDecl(root, node) {
  34152. let value;
  34153. root.walkDecls(i => {
  34154. if (typeof i.raws.before !== 'undefined') {
  34155. value = i.raws.before;
  34156. if (value.includes('\n')) {
  34157. value = value.replace(/[^\n]+$/, '');
  34158. }
  34159. return false
  34160. }
  34161. });
  34162. if (typeof value === 'undefined') {
  34163. value = this.raw(node, null, 'beforeRule');
  34164. } else if (value) {
  34165. value = value.replace(/\S/g, '');
  34166. }
  34167. return value
  34168. }
  34169. rawBeforeRule(root) {
  34170. let value;
  34171. root.walk(i => {
  34172. if (i.nodes && (i.parent !== root || root.first !== i)) {
  34173. if (typeof i.raws.before !== 'undefined') {
  34174. value = i.raws.before;
  34175. if (value.includes('\n')) {
  34176. value = value.replace(/[^\n]+$/, '');
  34177. }
  34178. return false
  34179. }
  34180. }
  34181. });
  34182. if (value) value = value.replace(/\S/g, '');
  34183. return value
  34184. }
  34185. rawBeforeClose(root) {
  34186. let value;
  34187. root.walk(i => {
  34188. if (i.nodes && i.nodes.length > 0) {
  34189. if (typeof i.raws.after !== 'undefined') {
  34190. value = i.raws.after;
  34191. if (value.includes('\n')) {
  34192. value = value.replace(/[^\n]+$/, '');
  34193. }
  34194. return false
  34195. }
  34196. }
  34197. });
  34198. if (value) value = value.replace(/\S/g, '');
  34199. return value
  34200. }
  34201. rawBeforeOpen(root) {
  34202. let value;
  34203. root.walk(i => {
  34204. if (i.type !== 'decl') {
  34205. value = i.raws.between;
  34206. if (typeof value !== 'undefined') return false
  34207. }
  34208. });
  34209. return value
  34210. }
  34211. rawColon(root) {
  34212. let value;
  34213. root.walkDecls(i => {
  34214. if (typeof i.raws.between !== 'undefined') {
  34215. value = i.raws.between.replace(/[^\s:]/g, '');
  34216. return false
  34217. }
  34218. });
  34219. return value
  34220. }
  34221. beforeAfter(node, detect) {
  34222. let value;
  34223. if (node.type === 'decl') {
  34224. value = this.raw(node, null, 'beforeDecl');
  34225. } else if (node.type === 'comment') {
  34226. value = this.raw(node, null, 'beforeComment');
  34227. } else if (detect === 'before') {
  34228. value = this.raw(node, null, 'beforeRule');
  34229. } else {
  34230. value = this.raw(node, null, 'beforeClose');
  34231. }
  34232. let buf = node.parent;
  34233. let depth = 0;
  34234. while (buf && buf.type !== 'root') {
  34235. depth += 1;
  34236. buf = buf.parent;
  34237. }
  34238. if (value.includes('\n')) {
  34239. let indent = this.raw(node, null, 'indent');
  34240. if (indent.length) {
  34241. for (let step = 0; step < depth; step++) value += indent;
  34242. }
  34243. }
  34244. return value
  34245. }
  34246. rawValue(node, prop) {
  34247. let value = node[prop];
  34248. let raw = node.raws[prop];
  34249. if (raw && raw.value === value) {
  34250. return raw.raw
  34251. }
  34252. return value
  34253. }
  34254. }
  34255. var stringifier = Stringifier;
  34256. Stringifier.default = Stringifier;
  34257. function stringify$1(node, builder) {
  34258. let str = new stringifier(builder);
  34259. str.stringify(node);
  34260. }
  34261. var stringify_1 = stringify$1;
  34262. stringify$1.default = stringify$1;
  34263. let { isClean: isClean$1, my: my$1 } = symbols;
  34264. function cloneNode(obj, parent) {
  34265. let cloned = new obj.constructor();
  34266. for (let i in obj) {
  34267. if (!Object.prototype.hasOwnProperty.call(obj, i)) {
  34268. /* c8 ignore next 2 */
  34269. continue
  34270. }
  34271. if (i === 'proxyCache') continue
  34272. let value = obj[i];
  34273. let type = typeof value;
  34274. if (i === 'parent' && type === 'object') {
  34275. if (parent) cloned[i] = parent;
  34276. } else if (i === 'source') {
  34277. cloned[i] = value;
  34278. } else if (Array.isArray(value)) {
  34279. cloned[i] = value.map(j => cloneNode(j, cloned));
  34280. } else {
  34281. if (type === 'object' && value !== null) value = cloneNode(value);
  34282. cloned[i] = value;
  34283. }
  34284. }
  34285. return cloned
  34286. }
  34287. class Node$1 {
  34288. constructor(defaults = {}) {
  34289. this.raws = {};
  34290. this[isClean$1] = false;
  34291. this[my$1] = true;
  34292. for (let name in defaults) {
  34293. if (name === 'nodes') {
  34294. this.nodes = [];
  34295. for (let node of defaults[name]) {
  34296. if (typeof node.clone === 'function') {
  34297. this.append(node.clone());
  34298. } else {
  34299. this.append(node);
  34300. }
  34301. }
  34302. } else {
  34303. this[name] = defaults[name];
  34304. }
  34305. }
  34306. }
  34307. error(message, opts = {}) {
  34308. if (this.source) {
  34309. let { start, end } = this.rangeBy(opts);
  34310. return this.source.input.error(
  34311. message,
  34312. { line: start.line, column: start.column },
  34313. { line: end.line, column: end.column },
  34314. opts
  34315. )
  34316. }
  34317. return new cssSyntaxError(message)
  34318. }
  34319. warn(result, text, opts) {
  34320. let data = { node: this };
  34321. for (let i in opts) data[i] = opts[i];
  34322. return result.warn(text, data)
  34323. }
  34324. remove() {
  34325. if (this.parent) {
  34326. this.parent.removeChild(this);
  34327. }
  34328. this.parent = undefined;
  34329. return this
  34330. }
  34331. toString(stringifier = stringify_1) {
  34332. if (stringifier.stringify) stringifier = stringifier.stringify;
  34333. let result = '';
  34334. stringifier(this, i => {
  34335. result += i;
  34336. });
  34337. return result
  34338. }
  34339. assign(overrides = {}) {
  34340. for (let name in overrides) {
  34341. this[name] = overrides[name];
  34342. }
  34343. return this
  34344. }
  34345. clone(overrides = {}) {
  34346. let cloned = cloneNode(this);
  34347. for (let name in overrides) {
  34348. cloned[name] = overrides[name];
  34349. }
  34350. return cloned
  34351. }
  34352. cloneBefore(overrides = {}) {
  34353. let cloned = this.clone(overrides);
  34354. this.parent.insertBefore(this, cloned);
  34355. return cloned
  34356. }
  34357. cloneAfter(overrides = {}) {
  34358. let cloned = this.clone(overrides);
  34359. this.parent.insertAfter(this, cloned);
  34360. return cloned
  34361. }
  34362. replaceWith(...nodes) {
  34363. if (this.parent) {
  34364. let bookmark = this;
  34365. let foundSelf = false;
  34366. for (let node of nodes) {
  34367. if (node === this) {
  34368. foundSelf = true;
  34369. } else if (foundSelf) {
  34370. this.parent.insertAfter(bookmark, node);
  34371. bookmark = node;
  34372. } else {
  34373. this.parent.insertBefore(bookmark, node);
  34374. }
  34375. }
  34376. if (!foundSelf) {
  34377. this.remove();
  34378. }
  34379. }
  34380. return this
  34381. }
  34382. next() {
  34383. if (!this.parent) return undefined
  34384. let index = this.parent.index(this);
  34385. return this.parent.nodes[index + 1]
  34386. }
  34387. prev() {
  34388. if (!this.parent) return undefined
  34389. let index = this.parent.index(this);
  34390. return this.parent.nodes[index - 1]
  34391. }
  34392. before(add) {
  34393. this.parent.insertBefore(this, add);
  34394. return this
  34395. }
  34396. after(add) {
  34397. this.parent.insertAfter(this, add);
  34398. return this
  34399. }
  34400. root() {
  34401. let result = this;
  34402. while (result.parent && result.parent.type !== 'document') {
  34403. result = result.parent;
  34404. }
  34405. return result
  34406. }
  34407. raw(prop, defaultType) {
  34408. let str = new stringifier();
  34409. return str.raw(this, prop, defaultType)
  34410. }
  34411. cleanRaws(keepBetween) {
  34412. delete this.raws.before;
  34413. delete this.raws.after;
  34414. if (!keepBetween) delete this.raws.between;
  34415. }
  34416. toJSON(_, inputs) {
  34417. let fixed = {};
  34418. let emitInputs = inputs == null;
  34419. inputs = inputs || new Map();
  34420. let inputsNextIndex = 0;
  34421. for (let name in this) {
  34422. if (!Object.prototype.hasOwnProperty.call(this, name)) {
  34423. /* c8 ignore next 2 */
  34424. continue
  34425. }
  34426. if (name === 'parent' || name === 'proxyCache') continue
  34427. let value = this[name];
  34428. if (Array.isArray(value)) {
  34429. fixed[name] = value.map(i => {
  34430. if (typeof i === 'object' && i.toJSON) {
  34431. return i.toJSON(null, inputs)
  34432. } else {
  34433. return i
  34434. }
  34435. });
  34436. } else if (typeof value === 'object' && value.toJSON) {
  34437. fixed[name] = value.toJSON(null, inputs);
  34438. } else if (name === 'source') {
  34439. let inputId = inputs.get(value.input);
  34440. if (inputId == null) {
  34441. inputId = inputsNextIndex;
  34442. inputs.set(value.input, inputsNextIndex);
  34443. inputsNextIndex++;
  34444. }
  34445. fixed[name] = {
  34446. inputId,
  34447. start: value.start,
  34448. end: value.end
  34449. };
  34450. } else {
  34451. fixed[name] = value;
  34452. }
  34453. }
  34454. if (emitInputs) {
  34455. fixed.inputs = [...inputs.keys()].map(input => input.toJSON());
  34456. }
  34457. return fixed
  34458. }
  34459. positionInside(index) {
  34460. let string = this.toString();
  34461. let column = this.source.start.column;
  34462. let line = this.source.start.line;
  34463. for (let i = 0; i < index; i++) {
  34464. if (string[i] === '\n') {
  34465. column = 1;
  34466. line += 1;
  34467. } else {
  34468. column += 1;
  34469. }
  34470. }
  34471. return { line, column }
  34472. }
  34473. positionBy(opts) {
  34474. let pos = this.source.start;
  34475. if (opts.index) {
  34476. pos = this.positionInside(opts.index);
  34477. } else if (opts.word) {
  34478. let index = this.toString().indexOf(opts.word);
  34479. if (index !== -1) pos = this.positionInside(index);
  34480. }
  34481. return pos
  34482. }
  34483. rangeBy(opts) {
  34484. let start = {
  34485. line: this.source.start.line,
  34486. column: this.source.start.column
  34487. };
  34488. let end = this.source.end
  34489. ? {
  34490. line: this.source.end.line,
  34491. column: this.source.end.column + 1
  34492. }
  34493. : {
  34494. line: start.line,
  34495. column: start.column + 1
  34496. };
  34497. if (opts.word) {
  34498. let index = this.toString().indexOf(opts.word);
  34499. if (index !== -1) {
  34500. start = this.positionInside(index);
  34501. end = this.positionInside(index + opts.word.length);
  34502. }
  34503. } else {
  34504. if (opts.start) {
  34505. start = {
  34506. line: opts.start.line,
  34507. column: opts.start.column
  34508. };
  34509. } else if (opts.index) {
  34510. start = this.positionInside(opts.index);
  34511. }
  34512. if (opts.end) {
  34513. end = {
  34514. line: opts.end.line,
  34515. column: opts.end.column
  34516. };
  34517. } else if (opts.endIndex) {
  34518. end = this.positionInside(opts.endIndex);
  34519. } else if (opts.index) {
  34520. end = this.positionInside(opts.index + 1);
  34521. }
  34522. }
  34523. if (
  34524. end.line < start.line ||
  34525. (end.line === start.line && end.column <= start.column)
  34526. ) {
  34527. end = { line: start.line, column: start.column + 1 };
  34528. }
  34529. return { start, end }
  34530. }
  34531. getProxyProcessor() {
  34532. return {
  34533. set(node, prop, value) {
  34534. if (node[prop] === value) return true
  34535. node[prop] = value;
  34536. if (
  34537. prop === 'prop' ||
  34538. prop === 'value' ||
  34539. prop === 'name' ||
  34540. prop === 'params' ||
  34541. prop === 'important' ||
  34542. /* c8 ignore next */
  34543. prop === 'text'
  34544. ) {
  34545. node.markDirty();
  34546. }
  34547. return true
  34548. },
  34549. get(node, prop) {
  34550. if (prop === 'proxyOf') {
  34551. return node
  34552. } else if (prop === 'root') {
  34553. return () => node.root().toProxy()
  34554. } else {
  34555. return node[prop]
  34556. }
  34557. }
  34558. }
  34559. }
  34560. toProxy() {
  34561. if (!this.proxyCache) {
  34562. this.proxyCache = new Proxy(this, this.getProxyProcessor());
  34563. }
  34564. return this.proxyCache
  34565. }
  34566. addToError(error) {
  34567. error.postcssNode = this;
  34568. if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
  34569. let s = this.source;
  34570. error.stack = error.stack.replace(
  34571. /\n\s{4}at /,
  34572. `$&${s.input.from}:${s.start.line}:${s.start.column}$&`
  34573. );
  34574. }
  34575. return error
  34576. }
  34577. markDirty() {
  34578. if (this[isClean$1]) {
  34579. this[isClean$1] = false;
  34580. let next = this;
  34581. while ((next = next.parent)) {
  34582. next[isClean$1] = false;
  34583. }
  34584. }
  34585. }
  34586. get proxyOf() {
  34587. return this
  34588. }
  34589. }
  34590. var node_1 = Node$1;
  34591. Node$1.default = Node$1;
  34592. class Declaration extends node_1 {
  34593. constructor(defaults) {
  34594. if (
  34595. defaults &&
  34596. typeof defaults.value !== 'undefined' &&
  34597. typeof defaults.value !== 'string'
  34598. ) {
  34599. defaults = { ...defaults, value: String(defaults.value) };
  34600. }
  34601. super(defaults);
  34602. this.type = 'decl';
  34603. }
  34604. get variable() {
  34605. return this.prop.startsWith('--') || this.prop[0] === '$'
  34606. }
  34607. }
  34608. var declaration = Declaration;
  34609. Declaration.default = Declaration;
  34610. /* -*- Mode: js; js-indent-level: 2; -*- */
  34611. /*
  34612. * Copyright 2011 Mozilla Foundation and contributors
  34613. * Licensed under the New BSD license. See LICENSE or:
  34614. * http://opensource.org/licenses/BSD-3-Clause
  34615. */
  34616. var intToCharMap$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  34617. /**
  34618. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  34619. */
  34620. var encode$4 = function (number) {
  34621. if (0 <= number && number < intToCharMap$1.length) {
  34622. return intToCharMap$1[number];
  34623. }
  34624. throw new TypeError("Must be between 0 and 63: " + number);
  34625. };
  34626. /**
  34627. * Decode a single base 64 character code digit to an integer. Returns -1 on
  34628. * failure.
  34629. */
  34630. var decode$2 = function (charCode) {
  34631. var bigA = 65; // 'A'
  34632. var bigZ = 90; // 'Z'
  34633. var littleA = 97; // 'a'
  34634. var littleZ = 122; // 'z'
  34635. var zero = 48; // '0'
  34636. var nine = 57; // '9'
  34637. var plus = 43; // '+'
  34638. var slash = 47; // '/'
  34639. var littleOffset = 26;
  34640. var numberOffset = 52;
  34641. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  34642. if (bigA <= charCode && charCode <= bigZ) {
  34643. return (charCode - bigA);
  34644. }
  34645. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  34646. if (littleA <= charCode && charCode <= littleZ) {
  34647. return (charCode - littleA + littleOffset);
  34648. }
  34649. // 52 - 61: 0123456789
  34650. if (zero <= charCode && charCode <= nine) {
  34651. return (charCode - zero + numberOffset);
  34652. }
  34653. // 62: +
  34654. if (charCode == plus) {
  34655. return 62;
  34656. }
  34657. // 63: /
  34658. if (charCode == slash) {
  34659. return 63;
  34660. }
  34661. // Invalid base64 digit.
  34662. return -1;
  34663. };
  34664. var base64$1 = {
  34665. encode: encode$4,
  34666. decode: decode$2
  34667. };
  34668. /* -*- Mode: js; js-indent-level: 2; -*- */
  34669. /*
  34670. * Copyright 2011 Mozilla Foundation and contributors
  34671. * Licensed under the New BSD license. See LICENSE or:
  34672. * http://opensource.org/licenses/BSD-3-Clause
  34673. *
  34674. * Based on the Base 64 VLQ implementation in Closure Compiler:
  34675. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  34676. *
  34677. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  34678. * Redistribution and use in source and binary forms, with or without
  34679. * modification, are permitted provided that the following conditions are
  34680. * met:
  34681. *
  34682. * * Redistributions of source code must retain the above copyright
  34683. * notice, this list of conditions and the following disclaimer.
  34684. * * Redistributions in binary form must reproduce the above
  34685. * copyright notice, this list of conditions and the following
  34686. * disclaimer in the documentation and/or other materials provided
  34687. * with the distribution.
  34688. * * Neither the name of Google Inc. nor the names of its
  34689. * contributors may be used to endorse or promote products derived
  34690. * from this software without specific prior written permission.
  34691. *
  34692. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  34693. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  34694. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  34695. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  34696. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  34697. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  34698. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  34699. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  34700. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  34701. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  34702. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  34703. */
  34704. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  34705. // length quantities we use in the source map spec, the first bit is the sign,
  34706. // the next four bits are the actual value, and the 6th bit is the
  34707. // continuation bit. The continuation bit tells us whether there are more
  34708. // digits in this value following this digit.
  34709. //
  34710. // Continuation
  34711. // | Sign
  34712. // | |
  34713. // V V
  34714. // 101011
  34715. var VLQ_BASE_SHIFT$1 = 5;
  34716. // binary: 100000
  34717. var VLQ_BASE$1 = 1 << VLQ_BASE_SHIFT$1;
  34718. // binary: 011111
  34719. var VLQ_BASE_MASK$1 = VLQ_BASE$1 - 1;
  34720. // binary: 100000
  34721. var VLQ_CONTINUATION_BIT$1 = VLQ_BASE$1;
  34722. /**
  34723. * Converts from a two-complement value to a value where the sign bit is
  34724. * placed in the least significant bit. For example, as decimals:
  34725. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  34726. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  34727. */
  34728. function toVLQSigned$1(aValue) {
  34729. return aValue < 0
  34730. ? ((-aValue) << 1) + 1
  34731. : (aValue << 1) + 0;
  34732. }
  34733. /**
  34734. * Converts to a two-complement value from a value where the sign bit is
  34735. * placed in the least significant bit. For example, as decimals:
  34736. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  34737. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  34738. */
  34739. function fromVLQSigned$1(aValue) {
  34740. var isNegative = (aValue & 1) === 1;
  34741. var shifted = aValue >> 1;
  34742. return isNegative
  34743. ? -shifted
  34744. : shifted;
  34745. }
  34746. /**
  34747. * Returns the base 64 VLQ encoded value.
  34748. */
  34749. var encode$5 = function base64VLQ_encode(aValue) {
  34750. var encoded = "";
  34751. var digit;
  34752. var vlq = toVLQSigned$1(aValue);
  34753. do {
  34754. digit = vlq & VLQ_BASE_MASK$1;
  34755. vlq >>>= VLQ_BASE_SHIFT$1;
  34756. if (vlq > 0) {
  34757. // There are still more digits in this value, so we must make sure the
  34758. // continuation bit is marked.
  34759. digit |= VLQ_CONTINUATION_BIT$1;
  34760. }
  34761. encoded += base64$1.encode(digit);
  34762. } while (vlq > 0);
  34763. return encoded;
  34764. };
  34765. /**
  34766. * Decodes the next base 64 VLQ value from the given string and returns the
  34767. * value and the rest of the string via the out parameter.
  34768. */
  34769. var decode$3 = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  34770. var strLen = aStr.length;
  34771. var result = 0;
  34772. var shift = 0;
  34773. var continuation, digit;
  34774. do {
  34775. if (aIndex >= strLen) {
  34776. throw new Error("Expected more digits in base 64 VLQ value.");
  34777. }
  34778. digit = base64$1.decode(aStr.charCodeAt(aIndex++));
  34779. if (digit === -1) {
  34780. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  34781. }
  34782. continuation = !!(digit & VLQ_CONTINUATION_BIT$1);
  34783. digit &= VLQ_BASE_MASK$1;
  34784. result = result + (digit << shift);
  34785. shift += VLQ_BASE_SHIFT$1;
  34786. } while (continuation);
  34787. aOutParam.value = fromVLQSigned$1(result);
  34788. aOutParam.rest = aIndex;
  34789. };
  34790. var base64Vlq$1 = {
  34791. encode: encode$5,
  34792. decode: decode$3
  34793. };
  34794. /* -*- Mode: js; js-indent-level: 2; -*- */
  34795. var util$1 = createCommonjsModule(function (module, exports) {
  34796. /*
  34797. * Copyright 2011 Mozilla Foundation and contributors
  34798. * Licensed under the New BSD license. See LICENSE or:
  34799. * http://opensource.org/licenses/BSD-3-Clause
  34800. */
  34801. /**
  34802. * This is a helper function for getting values from parameter/options
  34803. * objects.
  34804. *
  34805. * @param args The object we are extracting values from
  34806. * @param name The name of the property we are getting.
  34807. * @param defaultValue An optional value to return if the property is missing
  34808. * from the object. If this is not specified and the property is missing, an
  34809. * error will be thrown.
  34810. */
  34811. function getArg(aArgs, aName, aDefaultValue) {
  34812. if (aName in aArgs) {
  34813. return aArgs[aName];
  34814. } else if (arguments.length === 3) {
  34815. return aDefaultValue;
  34816. } else {
  34817. throw new Error('"' + aName + '" is a required argument.');
  34818. }
  34819. }
  34820. exports.getArg = getArg;
  34821. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  34822. var dataUrlRegexp = /^data:.+\,.+$/;
  34823. function urlParse(aUrl) {
  34824. var match = aUrl.match(urlRegexp);
  34825. if (!match) {
  34826. return null;
  34827. }
  34828. return {
  34829. scheme: match[1],
  34830. auth: match[2],
  34831. host: match[3],
  34832. port: match[4],
  34833. path: match[5]
  34834. };
  34835. }
  34836. exports.urlParse = urlParse;
  34837. function urlGenerate(aParsedUrl) {
  34838. var url = '';
  34839. if (aParsedUrl.scheme) {
  34840. url += aParsedUrl.scheme + ':';
  34841. }
  34842. url += '//';
  34843. if (aParsedUrl.auth) {
  34844. url += aParsedUrl.auth + '@';
  34845. }
  34846. if (aParsedUrl.host) {
  34847. url += aParsedUrl.host;
  34848. }
  34849. if (aParsedUrl.port) {
  34850. url += ":" + aParsedUrl.port;
  34851. }
  34852. if (aParsedUrl.path) {
  34853. url += aParsedUrl.path;
  34854. }
  34855. return url;
  34856. }
  34857. exports.urlGenerate = urlGenerate;
  34858. var MAX_CACHED_INPUTS = 32;
  34859. /**
  34860. * Takes some function `f(input) -> result` and returns a memoized version of
  34861. * `f`.
  34862. *
  34863. * We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The
  34864. * memoization is a dumb-simple, linear least-recently-used cache.
  34865. */
  34866. function lruMemoize(f) {
  34867. var cache = [];
  34868. return function(input) {
  34869. for (var i = 0; i < cache.length; i++) {
  34870. if (cache[i].input === input) {
  34871. var temp = cache[0];
  34872. cache[0] = cache[i];
  34873. cache[i] = temp;
  34874. return cache[0].result;
  34875. }
  34876. }
  34877. var result = f(input);
  34878. cache.unshift({
  34879. input,
  34880. result,
  34881. });
  34882. if (cache.length > MAX_CACHED_INPUTS) {
  34883. cache.pop();
  34884. }
  34885. return result;
  34886. };
  34887. }
  34888. /**
  34889. * Normalizes a path, or the path portion of a URL:
  34890. *
  34891. * - Replaces consecutive slashes with one slash.
  34892. * - Removes unnecessary '.' parts.
  34893. * - Removes unnecessary '<dir>/..' parts.
  34894. *
  34895. * Based on code in the Node.js 'path' core module.
  34896. *
  34897. * @param aPath The path or url to normalize.
  34898. */
  34899. var normalize = lruMemoize(function normalize(aPath) {
  34900. var path = aPath;
  34901. var url = urlParse(aPath);
  34902. if (url) {
  34903. if (!url.path) {
  34904. return aPath;
  34905. }
  34906. path = url.path;
  34907. }
  34908. var isAbsolute = exports.isAbsolute(path);
  34909. // Split the path into parts between `/` characters. This is much faster than
  34910. // using `.split(/\/+/g)`.
  34911. var parts = [];
  34912. var start = 0;
  34913. var i = 0;
  34914. while (true) {
  34915. start = i;
  34916. i = path.indexOf("/", start);
  34917. if (i === -1) {
  34918. parts.push(path.slice(start));
  34919. break;
  34920. } else {
  34921. parts.push(path.slice(start, i));
  34922. while (i < path.length && path[i] === "/") {
  34923. i++;
  34924. }
  34925. }
  34926. }
  34927. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  34928. part = parts[i];
  34929. if (part === '.') {
  34930. parts.splice(i, 1);
  34931. } else if (part === '..') {
  34932. up++;
  34933. } else if (up > 0) {
  34934. if (part === '') {
  34935. // The first part is blank if the path is absolute. Trying to go
  34936. // above the root is a no-op. Therefore we can remove all '..' parts
  34937. // directly after the root.
  34938. parts.splice(i + 1, up);
  34939. up = 0;
  34940. } else {
  34941. parts.splice(i, 2);
  34942. up--;
  34943. }
  34944. }
  34945. }
  34946. path = parts.join('/');
  34947. if (path === '') {
  34948. path = isAbsolute ? '/' : '.';
  34949. }
  34950. if (url) {
  34951. url.path = path;
  34952. return urlGenerate(url);
  34953. }
  34954. return path;
  34955. });
  34956. exports.normalize = normalize;
  34957. /**
  34958. * Joins two paths/URLs.
  34959. *
  34960. * @param aRoot The root path or URL.
  34961. * @param aPath The path or URL to be joined with the root.
  34962. *
  34963. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  34964. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  34965. * first.
  34966. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  34967. * is updated with the result and aRoot is returned. Otherwise the result
  34968. * is returned.
  34969. * - If aPath is absolute, the result is aPath.
  34970. * - Otherwise the two paths are joined with a slash.
  34971. * - Joining for example 'http://' and 'www.example.com' is also supported.
  34972. */
  34973. function join(aRoot, aPath) {
  34974. if (aRoot === "") {
  34975. aRoot = ".";
  34976. }
  34977. if (aPath === "") {
  34978. aPath = ".";
  34979. }
  34980. var aPathUrl = urlParse(aPath);
  34981. var aRootUrl = urlParse(aRoot);
  34982. if (aRootUrl) {
  34983. aRoot = aRootUrl.path || '/';
  34984. }
  34985. // `join(foo, '//www.example.org')`
  34986. if (aPathUrl && !aPathUrl.scheme) {
  34987. if (aRootUrl) {
  34988. aPathUrl.scheme = aRootUrl.scheme;
  34989. }
  34990. return urlGenerate(aPathUrl);
  34991. }
  34992. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  34993. return aPath;
  34994. }
  34995. // `join('http://', 'www.example.com')`
  34996. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  34997. aRootUrl.host = aPath;
  34998. return urlGenerate(aRootUrl);
  34999. }
  35000. var joined = aPath.charAt(0) === '/'
  35001. ? aPath
  35002. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  35003. if (aRootUrl) {
  35004. aRootUrl.path = joined;
  35005. return urlGenerate(aRootUrl);
  35006. }
  35007. return joined;
  35008. }
  35009. exports.join = join;
  35010. exports.isAbsolute = function (aPath) {
  35011. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  35012. };
  35013. /**
  35014. * Make a path relative to a URL or another path.
  35015. *
  35016. * @param aRoot The root path or URL.
  35017. * @param aPath The path or URL to be made relative to aRoot.
  35018. */
  35019. function relative(aRoot, aPath) {
  35020. if (aRoot === "") {
  35021. aRoot = ".";
  35022. }
  35023. aRoot = aRoot.replace(/\/$/, '');
  35024. // It is possible for the path to be above the root. In this case, simply
  35025. // checking whether the root is a prefix of the path won't work. Instead, we
  35026. // need to remove components from the root one by one, until either we find
  35027. // a prefix that fits, or we run out of components to remove.
  35028. var level = 0;
  35029. while (aPath.indexOf(aRoot + '/') !== 0) {
  35030. var index = aRoot.lastIndexOf("/");
  35031. if (index < 0) {
  35032. return aPath;
  35033. }
  35034. // If the only part of the root that is left is the scheme (i.e. http://,
  35035. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  35036. // have exhausted all components, so the path is not relative to the root.
  35037. aRoot = aRoot.slice(0, index);
  35038. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  35039. return aPath;
  35040. }
  35041. ++level;
  35042. }
  35043. // Make sure we add a "../" for each component we removed from the root.
  35044. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  35045. }
  35046. exports.relative = relative;
  35047. var supportsNullProto = (function () {
  35048. var obj = Object.create(null);
  35049. return !('__proto__' in obj);
  35050. }());
  35051. function identity (s) {
  35052. return s;
  35053. }
  35054. /**
  35055. * Because behavior goes wacky when you set `__proto__` on objects, we
  35056. * have to prefix all the strings in our set with an arbitrary character.
  35057. *
  35058. * See https://github.com/mozilla/source-map/pull/31 and
  35059. * https://github.com/mozilla/source-map/issues/30
  35060. *
  35061. * @param String aStr
  35062. */
  35063. function toSetString(aStr) {
  35064. if (isProtoString(aStr)) {
  35065. return '$' + aStr;
  35066. }
  35067. return aStr;
  35068. }
  35069. exports.toSetString = supportsNullProto ? identity : toSetString;
  35070. function fromSetString(aStr) {
  35071. if (isProtoString(aStr)) {
  35072. return aStr.slice(1);
  35073. }
  35074. return aStr;
  35075. }
  35076. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  35077. function isProtoString(s) {
  35078. if (!s) {
  35079. return false;
  35080. }
  35081. var length = s.length;
  35082. if (length < 9 /* "__proto__".length */) {
  35083. return false;
  35084. }
  35085. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  35086. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  35087. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  35088. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  35089. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  35090. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  35091. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  35092. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  35093. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  35094. return false;
  35095. }
  35096. for (var i = length - 10; i >= 0; i--) {
  35097. if (s.charCodeAt(i) !== 36 /* '$' */) {
  35098. return false;
  35099. }
  35100. }
  35101. return true;
  35102. }
  35103. /**
  35104. * Comparator between two mappings where the original positions are compared.
  35105. *
  35106. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  35107. * mappings with the same original source/line/column, but different generated
  35108. * line and column the same. Useful when searching for a mapping with a
  35109. * stubbed out mapping.
  35110. */
  35111. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  35112. var cmp = strcmp(mappingA.source, mappingB.source);
  35113. if (cmp !== 0) {
  35114. return cmp;
  35115. }
  35116. cmp = mappingA.originalLine - mappingB.originalLine;
  35117. if (cmp !== 0) {
  35118. return cmp;
  35119. }
  35120. cmp = mappingA.originalColumn - mappingB.originalColumn;
  35121. if (cmp !== 0 || onlyCompareOriginal) {
  35122. return cmp;
  35123. }
  35124. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  35125. if (cmp !== 0) {
  35126. return cmp;
  35127. }
  35128. cmp = mappingA.generatedLine - mappingB.generatedLine;
  35129. if (cmp !== 0) {
  35130. return cmp;
  35131. }
  35132. return strcmp(mappingA.name, mappingB.name);
  35133. }
  35134. exports.compareByOriginalPositions = compareByOriginalPositions;
  35135. function compareByOriginalPositionsNoSource(mappingA, mappingB, onlyCompareOriginal) {
  35136. var cmp;
  35137. cmp = mappingA.originalLine - mappingB.originalLine;
  35138. if (cmp !== 0) {
  35139. return cmp;
  35140. }
  35141. cmp = mappingA.originalColumn - mappingB.originalColumn;
  35142. if (cmp !== 0 || onlyCompareOriginal) {
  35143. return cmp;
  35144. }
  35145. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  35146. if (cmp !== 0) {
  35147. return cmp;
  35148. }
  35149. cmp = mappingA.generatedLine - mappingB.generatedLine;
  35150. if (cmp !== 0) {
  35151. return cmp;
  35152. }
  35153. return strcmp(mappingA.name, mappingB.name);
  35154. }
  35155. exports.compareByOriginalPositionsNoSource = compareByOriginalPositionsNoSource;
  35156. /**
  35157. * Comparator between two mappings with deflated source and name indices where
  35158. * the generated positions are compared.
  35159. *
  35160. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  35161. * mappings with the same generated line and column, but different
  35162. * source/name/original line and column the same. Useful when searching for a
  35163. * mapping with a stubbed out mapping.
  35164. */
  35165. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  35166. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  35167. if (cmp !== 0) {
  35168. return cmp;
  35169. }
  35170. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  35171. if (cmp !== 0 || onlyCompareGenerated) {
  35172. return cmp;
  35173. }
  35174. cmp = strcmp(mappingA.source, mappingB.source);
  35175. if (cmp !== 0) {
  35176. return cmp;
  35177. }
  35178. cmp = mappingA.originalLine - mappingB.originalLine;
  35179. if (cmp !== 0) {
  35180. return cmp;
  35181. }
  35182. cmp = mappingA.originalColumn - mappingB.originalColumn;
  35183. if (cmp !== 0) {
  35184. return cmp;
  35185. }
  35186. return strcmp(mappingA.name, mappingB.name);
  35187. }
  35188. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  35189. function compareByGeneratedPositionsDeflatedNoLine(mappingA, mappingB, onlyCompareGenerated) {
  35190. var cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  35191. if (cmp !== 0 || onlyCompareGenerated) {
  35192. return cmp;
  35193. }
  35194. cmp = strcmp(mappingA.source, mappingB.source);
  35195. if (cmp !== 0) {
  35196. return cmp;
  35197. }
  35198. cmp = mappingA.originalLine - mappingB.originalLine;
  35199. if (cmp !== 0) {
  35200. return cmp;
  35201. }
  35202. cmp = mappingA.originalColumn - mappingB.originalColumn;
  35203. if (cmp !== 0) {
  35204. return cmp;
  35205. }
  35206. return strcmp(mappingA.name, mappingB.name);
  35207. }
  35208. exports.compareByGeneratedPositionsDeflatedNoLine = compareByGeneratedPositionsDeflatedNoLine;
  35209. function strcmp(aStr1, aStr2) {
  35210. if (aStr1 === aStr2) {
  35211. return 0;
  35212. }
  35213. if (aStr1 === null) {
  35214. return 1; // aStr2 !== null
  35215. }
  35216. if (aStr2 === null) {
  35217. return -1; // aStr1 !== null
  35218. }
  35219. if (aStr1 > aStr2) {
  35220. return 1;
  35221. }
  35222. return -1;
  35223. }
  35224. /**
  35225. * Comparator between two mappings with inflated source and name strings where
  35226. * the generated positions are compared.
  35227. */
  35228. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  35229. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  35230. if (cmp !== 0) {
  35231. return cmp;
  35232. }
  35233. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  35234. if (cmp !== 0) {
  35235. return cmp;
  35236. }
  35237. cmp = strcmp(mappingA.source, mappingB.source);
  35238. if (cmp !== 0) {
  35239. return cmp;
  35240. }
  35241. cmp = mappingA.originalLine - mappingB.originalLine;
  35242. if (cmp !== 0) {
  35243. return cmp;
  35244. }
  35245. cmp = mappingA.originalColumn - mappingB.originalColumn;
  35246. if (cmp !== 0) {
  35247. return cmp;
  35248. }
  35249. return strcmp(mappingA.name, mappingB.name);
  35250. }
  35251. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  35252. /**
  35253. * Strip any JSON XSSI avoidance prefix from the string (as documented
  35254. * in the source maps specification), and then parse the string as
  35255. * JSON.
  35256. */
  35257. function parseSourceMapInput(str) {
  35258. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  35259. }
  35260. exports.parseSourceMapInput = parseSourceMapInput;
  35261. /**
  35262. * Compute the URL of a source given the the source root, the source's
  35263. * URL, and the source map's URL.
  35264. */
  35265. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  35266. sourceURL = sourceURL || '';
  35267. if (sourceRoot) {
  35268. // This follows what Chrome does.
  35269. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  35270. sourceRoot += '/';
  35271. }
  35272. // The spec says:
  35273. // Line 4: An optional source root, useful for relocating source
  35274. // files on a server or removing repeated values in the
  35275. // “sources” entry. This value is prepended to the individual
  35276. // entries in the “source” field.
  35277. sourceURL = sourceRoot + sourceURL;
  35278. }
  35279. // Historically, SourceMapConsumer did not take the sourceMapURL as
  35280. // a parameter. This mode is still somewhat supported, which is why
  35281. // this code block is conditional. However, it's preferable to pass
  35282. // the source map URL to SourceMapConsumer, so that this function
  35283. // can implement the source URL resolution algorithm as outlined in
  35284. // the spec. This block is basically the equivalent of:
  35285. // new URL(sourceURL, sourceMapURL).toString()
  35286. // ... except it avoids using URL, which wasn't available in the
  35287. // older releases of node still supported by this library.
  35288. //
  35289. // The spec says:
  35290. // If the sources are not absolute URLs after prepending of the
  35291. // “sourceRoot”, the sources are resolved relative to the
  35292. // SourceMap (like resolving script src in a html document).
  35293. if (sourceMapURL) {
  35294. var parsed = urlParse(sourceMapURL);
  35295. if (!parsed) {
  35296. throw new Error("sourceMapURL could not be parsed");
  35297. }
  35298. if (parsed.path) {
  35299. // Strip the last path component, but keep the "/".
  35300. var index = parsed.path.lastIndexOf('/');
  35301. if (index >= 0) {
  35302. parsed.path = parsed.path.substring(0, index + 1);
  35303. }
  35304. }
  35305. sourceURL = join(urlGenerate(parsed), sourceURL);
  35306. }
  35307. return normalize(sourceURL);
  35308. }
  35309. exports.computeSourceURL = computeSourceURL;
  35310. });
  35311. /* -*- Mode: js; js-indent-level: 2; -*- */
  35312. /*
  35313. * Copyright 2011 Mozilla Foundation and contributors
  35314. * Licensed under the New BSD license. See LICENSE or:
  35315. * http://opensource.org/licenses/BSD-3-Clause
  35316. */
  35317. var has$1 = Object.prototype.hasOwnProperty;
  35318. var hasNativeMap$1 = typeof Map !== "undefined";
  35319. /**
  35320. * A data structure which is a combination of an array and a set. Adding a new
  35321. * member is O(1), testing for membership is O(1), and finding the index of an
  35322. * element is O(1). Removing elements from the set is not supported. Only
  35323. * strings are supported for membership.
  35324. */
  35325. function ArraySet$3() {
  35326. this._array = [];
  35327. this._set = hasNativeMap$1 ? new Map() : Object.create(null);
  35328. }
  35329. /**
  35330. * Static method for creating ArraySet instances from an existing array.
  35331. */
  35332. ArraySet$3.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  35333. var set = new ArraySet$3();
  35334. for (var i = 0, len = aArray.length; i < len; i++) {
  35335. set.add(aArray[i], aAllowDuplicates);
  35336. }
  35337. return set;
  35338. };
  35339. /**
  35340. * Return how many unique items are in this ArraySet. If duplicates have been
  35341. * added, than those do not count towards the size.
  35342. *
  35343. * @returns Number
  35344. */
  35345. ArraySet$3.prototype.size = function ArraySet_size() {
  35346. return hasNativeMap$1 ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  35347. };
  35348. /**
  35349. * Add the given string to this set.
  35350. *
  35351. * @param String aStr
  35352. */
  35353. ArraySet$3.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  35354. var sStr = hasNativeMap$1 ? aStr : util$1.toSetString(aStr);
  35355. var isDuplicate = hasNativeMap$1 ? this.has(aStr) : has$1.call(this._set, sStr);
  35356. var idx = this._array.length;
  35357. if (!isDuplicate || aAllowDuplicates) {
  35358. this._array.push(aStr);
  35359. }
  35360. if (!isDuplicate) {
  35361. if (hasNativeMap$1) {
  35362. this._set.set(aStr, idx);
  35363. } else {
  35364. this._set[sStr] = idx;
  35365. }
  35366. }
  35367. };
  35368. /**
  35369. * Is the given string a member of this set?
  35370. *
  35371. * @param String aStr
  35372. */
  35373. ArraySet$3.prototype.has = function ArraySet_has(aStr) {
  35374. if (hasNativeMap$1) {
  35375. return this._set.has(aStr);
  35376. } else {
  35377. var sStr = util$1.toSetString(aStr);
  35378. return has$1.call(this._set, sStr);
  35379. }
  35380. };
  35381. /**
  35382. * What is the index of the given string in the array?
  35383. *
  35384. * @param String aStr
  35385. */
  35386. ArraySet$3.prototype.indexOf = function ArraySet_indexOf(aStr) {
  35387. if (hasNativeMap$1) {
  35388. var idx = this._set.get(aStr);
  35389. if (idx >= 0) {
  35390. return idx;
  35391. }
  35392. } else {
  35393. var sStr = util$1.toSetString(aStr);
  35394. if (has$1.call(this._set, sStr)) {
  35395. return this._set[sStr];
  35396. }
  35397. }
  35398. throw new Error('"' + aStr + '" is not in the set.');
  35399. };
  35400. /**
  35401. * What is the element at the given index?
  35402. *
  35403. * @param Number aIdx
  35404. */
  35405. ArraySet$3.prototype.at = function ArraySet_at(aIdx) {
  35406. if (aIdx >= 0 && aIdx < this._array.length) {
  35407. return this._array[aIdx];
  35408. }
  35409. throw new Error('No element indexed by ' + aIdx);
  35410. };
  35411. /**
  35412. * Returns the array representation of this set (which has the proper indices
  35413. * indicated by indexOf). Note that this is a copy of the internal array used
  35414. * for storing the members so that no one can mess with internal state.
  35415. */
  35416. ArraySet$3.prototype.toArray = function ArraySet_toArray() {
  35417. return this._array.slice();
  35418. };
  35419. var ArraySet_1$1 = ArraySet$3;
  35420. var arraySet$1 = {
  35421. ArraySet: ArraySet_1$1
  35422. };
  35423. /* -*- Mode: js; js-indent-level: 2; -*- */
  35424. /*
  35425. * Copyright 2014 Mozilla Foundation and contributors
  35426. * Licensed under the New BSD license. See LICENSE or:
  35427. * http://opensource.org/licenses/BSD-3-Clause
  35428. */
  35429. /**
  35430. * Determine whether mappingB is after mappingA with respect to generated
  35431. * position.
  35432. */
  35433. function generatedPositionAfter$1(mappingA, mappingB) {
  35434. // Optimized for most common case
  35435. var lineA = mappingA.generatedLine;
  35436. var lineB = mappingB.generatedLine;
  35437. var columnA = mappingA.generatedColumn;
  35438. var columnB = mappingB.generatedColumn;
  35439. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  35440. util$1.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  35441. }
  35442. /**
  35443. * A data structure to provide a sorted view of accumulated mappings in a
  35444. * performance conscious manner. It trades a neglibable overhead in general
  35445. * case for a large speedup in case of mappings being added in order.
  35446. */
  35447. function MappingList$2() {
  35448. this._array = [];
  35449. this._sorted = true;
  35450. // Serves as infimum
  35451. this._last = {generatedLine: -1, generatedColumn: 0};
  35452. }
  35453. /**
  35454. * Iterate through internal items. This method takes the same arguments that
  35455. * `Array.prototype.forEach` takes.
  35456. *
  35457. * NOTE: The order of the mappings is NOT guaranteed.
  35458. */
  35459. MappingList$2.prototype.unsortedForEach =
  35460. function MappingList_forEach(aCallback, aThisArg) {
  35461. this._array.forEach(aCallback, aThisArg);
  35462. };
  35463. /**
  35464. * Add the given source mapping.
  35465. *
  35466. * @param Object aMapping
  35467. */
  35468. MappingList$2.prototype.add = function MappingList_add(aMapping) {
  35469. if (generatedPositionAfter$1(this._last, aMapping)) {
  35470. this._last = aMapping;
  35471. this._array.push(aMapping);
  35472. } else {
  35473. this._sorted = false;
  35474. this._array.push(aMapping);
  35475. }
  35476. };
  35477. /**
  35478. * Returns the flat, sorted array of mappings. The mappings are sorted by
  35479. * generated position.
  35480. *
  35481. * WARNING: This method returns internal data without copying, for
  35482. * performance. The return value must NOT be mutated, and should be treated as
  35483. * an immutable borrow. If you want to take ownership, you must make your own
  35484. * copy.
  35485. */
  35486. MappingList$2.prototype.toArray = function MappingList_toArray() {
  35487. if (!this._sorted) {
  35488. this._array.sort(util$1.compareByGeneratedPositionsInflated);
  35489. this._sorted = true;
  35490. }
  35491. return this._array;
  35492. };
  35493. var MappingList_1$1 = MappingList$2;
  35494. var mappingList$1 = {
  35495. MappingList: MappingList_1$1
  35496. };
  35497. /* -*- Mode: js; js-indent-level: 2; -*- */
  35498. /*
  35499. * Copyright 2011 Mozilla Foundation and contributors
  35500. * Licensed under the New BSD license. See LICENSE or:
  35501. * http://opensource.org/licenses/BSD-3-Clause
  35502. */
  35503. var ArraySet$4 = arraySet$1.ArraySet;
  35504. var MappingList$3 = mappingList$1.MappingList;
  35505. /**
  35506. * An instance of the SourceMapGenerator represents a source map which is
  35507. * being built incrementally. You may pass an object with the following
  35508. * properties:
  35509. *
  35510. * - file: The filename of the generated source.
  35511. * - sourceRoot: A root for all relative URLs in this source map.
  35512. */
  35513. function SourceMapGenerator$3(aArgs) {
  35514. if (!aArgs) {
  35515. aArgs = {};
  35516. }
  35517. this._file = util$1.getArg(aArgs, 'file', null);
  35518. this._sourceRoot = util$1.getArg(aArgs, 'sourceRoot', null);
  35519. this._skipValidation = util$1.getArg(aArgs, 'skipValidation', false);
  35520. this._sources = new ArraySet$4();
  35521. this._names = new ArraySet$4();
  35522. this._mappings = new MappingList$3();
  35523. this._sourcesContents = null;
  35524. }
  35525. SourceMapGenerator$3.prototype._version = 3;
  35526. /**
  35527. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  35528. *
  35529. * @param aSourceMapConsumer The SourceMap.
  35530. */
  35531. SourceMapGenerator$3.fromSourceMap =
  35532. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  35533. var sourceRoot = aSourceMapConsumer.sourceRoot;
  35534. var generator = new SourceMapGenerator$3({
  35535. file: aSourceMapConsumer.file,
  35536. sourceRoot: sourceRoot
  35537. });
  35538. aSourceMapConsumer.eachMapping(function (mapping) {
  35539. var newMapping = {
  35540. generated: {
  35541. line: mapping.generatedLine,
  35542. column: mapping.generatedColumn
  35543. }
  35544. };
  35545. if (mapping.source != null) {
  35546. newMapping.source = mapping.source;
  35547. if (sourceRoot != null) {
  35548. newMapping.source = util$1.relative(sourceRoot, newMapping.source);
  35549. }
  35550. newMapping.original = {
  35551. line: mapping.originalLine,
  35552. column: mapping.originalColumn
  35553. };
  35554. if (mapping.name != null) {
  35555. newMapping.name = mapping.name;
  35556. }
  35557. }
  35558. generator.addMapping(newMapping);
  35559. });
  35560. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  35561. var sourceRelative = sourceFile;
  35562. if (sourceRoot !== null) {
  35563. sourceRelative = util$1.relative(sourceRoot, sourceFile);
  35564. }
  35565. if (!generator._sources.has(sourceRelative)) {
  35566. generator._sources.add(sourceRelative);
  35567. }
  35568. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  35569. if (content != null) {
  35570. generator.setSourceContent(sourceFile, content);
  35571. }
  35572. });
  35573. return generator;
  35574. };
  35575. /**
  35576. * Add a single mapping from original source line and column to the generated
  35577. * source's line and column for this source map being created. The mapping
  35578. * object should have the following properties:
  35579. *
  35580. * - generated: An object with the generated line and column positions.
  35581. * - original: An object with the original line and column positions.
  35582. * - source: The original source file (relative to the sourceRoot).
  35583. * - name: An optional original token name for this mapping.
  35584. */
  35585. SourceMapGenerator$3.prototype.addMapping =
  35586. function SourceMapGenerator_addMapping(aArgs) {
  35587. var generated = util$1.getArg(aArgs, 'generated');
  35588. var original = util$1.getArg(aArgs, 'original', null);
  35589. var source = util$1.getArg(aArgs, 'source', null);
  35590. var name = util$1.getArg(aArgs, 'name', null);
  35591. if (!this._skipValidation) {
  35592. this._validateMapping(generated, original, source, name);
  35593. }
  35594. if (source != null) {
  35595. source = String(source);
  35596. if (!this._sources.has(source)) {
  35597. this._sources.add(source);
  35598. }
  35599. }
  35600. if (name != null) {
  35601. name = String(name);
  35602. if (!this._names.has(name)) {
  35603. this._names.add(name);
  35604. }
  35605. }
  35606. this._mappings.add({
  35607. generatedLine: generated.line,
  35608. generatedColumn: generated.column,
  35609. originalLine: original != null && original.line,
  35610. originalColumn: original != null && original.column,
  35611. source: source,
  35612. name: name
  35613. });
  35614. };
  35615. /**
  35616. * Set the source content for a source file.
  35617. */
  35618. SourceMapGenerator$3.prototype.setSourceContent =
  35619. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  35620. var source = aSourceFile;
  35621. if (this._sourceRoot != null) {
  35622. source = util$1.relative(this._sourceRoot, source);
  35623. }
  35624. if (aSourceContent != null) {
  35625. // Add the source content to the _sourcesContents map.
  35626. // Create a new _sourcesContents map if the property is null.
  35627. if (!this._sourcesContents) {
  35628. this._sourcesContents = Object.create(null);
  35629. }
  35630. this._sourcesContents[util$1.toSetString(source)] = aSourceContent;
  35631. } else if (this._sourcesContents) {
  35632. // Remove the source file from the _sourcesContents map.
  35633. // If the _sourcesContents map is empty, set the property to null.
  35634. delete this._sourcesContents[util$1.toSetString(source)];
  35635. if (Object.keys(this._sourcesContents).length === 0) {
  35636. this._sourcesContents = null;
  35637. }
  35638. }
  35639. };
  35640. /**
  35641. * Applies the mappings of a sub-source-map for a specific source file to the
  35642. * source map being generated. Each mapping to the supplied source file is
  35643. * rewritten using the supplied source map. Note: The resolution for the
  35644. * resulting mappings is the minimium of this map and the supplied map.
  35645. *
  35646. * @param aSourceMapConsumer The source map to be applied.
  35647. * @param aSourceFile Optional. The filename of the source file.
  35648. * If omitted, SourceMapConsumer's file property will be used.
  35649. * @param aSourceMapPath Optional. The dirname of the path to the source map
  35650. * to be applied. If relative, it is relative to the SourceMapConsumer.
  35651. * This parameter is needed when the two source maps aren't in the same
  35652. * directory, and the source map to be applied contains relative source
  35653. * paths. If so, those relative source paths need to be rewritten
  35654. * relative to the SourceMapGenerator.
  35655. */
  35656. SourceMapGenerator$3.prototype.applySourceMap =
  35657. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  35658. var sourceFile = aSourceFile;
  35659. // If aSourceFile is omitted, we will use the file property of the SourceMap
  35660. if (aSourceFile == null) {
  35661. if (aSourceMapConsumer.file == null) {
  35662. throw new Error(
  35663. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  35664. 'or the source map\'s "file" property. Both were omitted.'
  35665. );
  35666. }
  35667. sourceFile = aSourceMapConsumer.file;
  35668. }
  35669. var sourceRoot = this._sourceRoot;
  35670. // Make "sourceFile" relative if an absolute Url is passed.
  35671. if (sourceRoot != null) {
  35672. sourceFile = util$1.relative(sourceRoot, sourceFile);
  35673. }
  35674. // Applying the SourceMap can add and remove items from the sources and
  35675. // the names array.
  35676. var newSources = new ArraySet$4();
  35677. var newNames = new ArraySet$4();
  35678. // Find mappings for the "sourceFile"
  35679. this._mappings.unsortedForEach(function (mapping) {
  35680. if (mapping.source === sourceFile && mapping.originalLine != null) {
  35681. // Check if it can be mapped by the source map, then update the mapping.
  35682. var original = aSourceMapConsumer.originalPositionFor({
  35683. line: mapping.originalLine,
  35684. column: mapping.originalColumn
  35685. });
  35686. if (original.source != null) {
  35687. // Copy mapping
  35688. mapping.source = original.source;
  35689. if (aSourceMapPath != null) {
  35690. mapping.source = util$1.join(aSourceMapPath, mapping.source);
  35691. }
  35692. if (sourceRoot != null) {
  35693. mapping.source = util$1.relative(sourceRoot, mapping.source);
  35694. }
  35695. mapping.originalLine = original.line;
  35696. mapping.originalColumn = original.column;
  35697. if (original.name != null) {
  35698. mapping.name = original.name;
  35699. }
  35700. }
  35701. }
  35702. var source = mapping.source;
  35703. if (source != null && !newSources.has(source)) {
  35704. newSources.add(source);
  35705. }
  35706. var name = mapping.name;
  35707. if (name != null && !newNames.has(name)) {
  35708. newNames.add(name);
  35709. }
  35710. }, this);
  35711. this._sources = newSources;
  35712. this._names = newNames;
  35713. // Copy sourcesContents of applied map.
  35714. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  35715. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  35716. if (content != null) {
  35717. if (aSourceMapPath != null) {
  35718. sourceFile = util$1.join(aSourceMapPath, sourceFile);
  35719. }
  35720. if (sourceRoot != null) {
  35721. sourceFile = util$1.relative(sourceRoot, sourceFile);
  35722. }
  35723. this.setSourceContent(sourceFile, content);
  35724. }
  35725. }, this);
  35726. };
  35727. /**
  35728. * A mapping can have one of the three levels of data:
  35729. *
  35730. * 1. Just the generated position.
  35731. * 2. The Generated position, original position, and original source.
  35732. * 3. Generated and original position, original source, as well as a name
  35733. * token.
  35734. *
  35735. * To maintain consistency, we validate that any new mapping being added falls
  35736. * in to one of these categories.
  35737. */
  35738. SourceMapGenerator$3.prototype._validateMapping =
  35739. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  35740. aName) {
  35741. // When aOriginal is truthy but has empty values for .line and .column,
  35742. // it is most likely a programmer error. In this case we throw a very
  35743. // specific error message to try to guide them the right way.
  35744. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  35745. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  35746. throw new Error(
  35747. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  35748. 'the original mapping entirely and only map the generated position. If so, pass ' +
  35749. 'null for the original mapping instead of an object with empty or null values.'
  35750. );
  35751. }
  35752. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  35753. && aGenerated.line > 0 && aGenerated.column >= 0
  35754. && !aOriginal && !aSource && !aName) {
  35755. // Case 1.
  35756. return;
  35757. }
  35758. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  35759. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  35760. && aGenerated.line > 0 && aGenerated.column >= 0
  35761. && aOriginal.line > 0 && aOriginal.column >= 0
  35762. && aSource) {
  35763. // Cases 2 and 3.
  35764. return;
  35765. }
  35766. else {
  35767. throw new Error('Invalid mapping: ' + JSON.stringify({
  35768. generated: aGenerated,
  35769. source: aSource,
  35770. original: aOriginal,
  35771. name: aName
  35772. }));
  35773. }
  35774. };
  35775. /**
  35776. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  35777. * specified by the source map format.
  35778. */
  35779. SourceMapGenerator$3.prototype._serializeMappings =
  35780. function SourceMapGenerator_serializeMappings() {
  35781. var previousGeneratedColumn = 0;
  35782. var previousGeneratedLine = 1;
  35783. var previousOriginalColumn = 0;
  35784. var previousOriginalLine = 0;
  35785. var previousName = 0;
  35786. var previousSource = 0;
  35787. var result = '';
  35788. var next;
  35789. var mapping;
  35790. var nameIdx;
  35791. var sourceIdx;
  35792. var mappings = this._mappings.toArray();
  35793. for (var i = 0, len = mappings.length; i < len; i++) {
  35794. mapping = mappings[i];
  35795. next = '';
  35796. if (mapping.generatedLine !== previousGeneratedLine) {
  35797. previousGeneratedColumn = 0;
  35798. while (mapping.generatedLine !== previousGeneratedLine) {
  35799. next += ';';
  35800. previousGeneratedLine++;
  35801. }
  35802. }
  35803. else {
  35804. if (i > 0) {
  35805. if (!util$1.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  35806. continue;
  35807. }
  35808. next += ',';
  35809. }
  35810. }
  35811. next += base64Vlq$1.encode(mapping.generatedColumn
  35812. - previousGeneratedColumn);
  35813. previousGeneratedColumn = mapping.generatedColumn;
  35814. if (mapping.source != null) {
  35815. sourceIdx = this._sources.indexOf(mapping.source);
  35816. next += base64Vlq$1.encode(sourceIdx - previousSource);
  35817. previousSource = sourceIdx;
  35818. // lines are stored 0-based in SourceMap spec version 3
  35819. next += base64Vlq$1.encode(mapping.originalLine - 1
  35820. - previousOriginalLine);
  35821. previousOriginalLine = mapping.originalLine - 1;
  35822. next += base64Vlq$1.encode(mapping.originalColumn
  35823. - previousOriginalColumn);
  35824. previousOriginalColumn = mapping.originalColumn;
  35825. if (mapping.name != null) {
  35826. nameIdx = this._names.indexOf(mapping.name);
  35827. next += base64Vlq$1.encode(nameIdx - previousName);
  35828. previousName = nameIdx;
  35829. }
  35830. }
  35831. result += next;
  35832. }
  35833. return result;
  35834. };
  35835. SourceMapGenerator$3.prototype._generateSourcesContent =
  35836. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  35837. return aSources.map(function (source) {
  35838. if (!this._sourcesContents) {
  35839. return null;
  35840. }
  35841. if (aSourceRoot != null) {
  35842. source = util$1.relative(aSourceRoot, source);
  35843. }
  35844. var key = util$1.toSetString(source);
  35845. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  35846. ? this._sourcesContents[key]
  35847. : null;
  35848. }, this);
  35849. };
  35850. /**
  35851. * Externalize the source map.
  35852. */
  35853. SourceMapGenerator$3.prototype.toJSON =
  35854. function SourceMapGenerator_toJSON() {
  35855. var map = {
  35856. version: this._version,
  35857. sources: this._sources.toArray(),
  35858. names: this._names.toArray(),
  35859. mappings: this._serializeMappings()
  35860. };
  35861. if (this._file != null) {
  35862. map.file = this._file;
  35863. }
  35864. if (this._sourceRoot != null) {
  35865. map.sourceRoot = this._sourceRoot;
  35866. }
  35867. if (this._sourcesContents) {
  35868. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  35869. }
  35870. return map;
  35871. };
  35872. /**
  35873. * Render the source map being generated to a string.
  35874. */
  35875. SourceMapGenerator$3.prototype.toString =
  35876. function SourceMapGenerator_toString() {
  35877. return JSON.stringify(this.toJSON());
  35878. };
  35879. var SourceMapGenerator_1$1 = SourceMapGenerator$3;
  35880. var sourceMapGenerator$1 = {
  35881. SourceMapGenerator: SourceMapGenerator_1$1
  35882. };
  35883. /* -*- Mode: js; js-indent-level: 2; -*- */
  35884. var binarySearch$1 = createCommonjsModule(function (module, exports) {
  35885. /*
  35886. * Copyright 2011 Mozilla Foundation and contributors
  35887. * Licensed under the New BSD license. See LICENSE or:
  35888. * http://opensource.org/licenses/BSD-3-Clause
  35889. */
  35890. exports.GREATEST_LOWER_BOUND = 1;
  35891. exports.LEAST_UPPER_BOUND = 2;
  35892. /**
  35893. * Recursive implementation of binary search.
  35894. *
  35895. * @param aLow Indices here and lower do not contain the needle.
  35896. * @param aHigh Indices here and higher do not contain the needle.
  35897. * @param aNeedle The element being searched for.
  35898. * @param aHaystack The non-empty array being searched.
  35899. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  35900. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  35901. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  35902. * closest element that is smaller than or greater than the one we are
  35903. * searching for, respectively, if the exact element cannot be found.
  35904. */
  35905. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  35906. // This function terminates when one of the following is true:
  35907. //
  35908. // 1. We find the exact element we are looking for.
  35909. //
  35910. // 2. We did not find the exact element, but we can return the index of
  35911. // the next-closest element.
  35912. //
  35913. // 3. We did not find the exact element, and there is no next-closest
  35914. // element than the one we are searching for, so we return -1.
  35915. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  35916. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  35917. if (cmp === 0) {
  35918. // Found the element we are looking for.
  35919. return mid;
  35920. }
  35921. else if (cmp > 0) {
  35922. // Our needle is greater than aHaystack[mid].
  35923. if (aHigh - mid > 1) {
  35924. // The element is in the upper half.
  35925. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  35926. }
  35927. // The exact needle element was not found in this haystack. Determine if
  35928. // we are in termination case (3) or (2) and return the appropriate thing.
  35929. if (aBias == exports.LEAST_UPPER_BOUND) {
  35930. return aHigh < aHaystack.length ? aHigh : -1;
  35931. } else {
  35932. return mid;
  35933. }
  35934. }
  35935. else {
  35936. // Our needle is less than aHaystack[mid].
  35937. if (mid - aLow > 1) {
  35938. // The element is in the lower half.
  35939. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  35940. }
  35941. // we are in termination case (3) or (2) and return the appropriate thing.
  35942. if (aBias == exports.LEAST_UPPER_BOUND) {
  35943. return mid;
  35944. } else {
  35945. return aLow < 0 ? -1 : aLow;
  35946. }
  35947. }
  35948. }
  35949. /**
  35950. * This is an implementation of binary search which will always try and return
  35951. * the index of the closest element if there is no exact hit. This is because
  35952. * mappings between original and generated line/col pairs are single points,
  35953. * and there is an implicit region between each of them, so a miss just means
  35954. * that you aren't on the very start of a region.
  35955. *
  35956. * @param aNeedle The element you are looking for.
  35957. * @param aHaystack The array that is being searched.
  35958. * @param aCompare A function which takes the needle and an element in the
  35959. * array and returns -1, 0, or 1 depending on whether the needle is less
  35960. * than, equal to, or greater than the element, respectively.
  35961. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  35962. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  35963. * closest element that is smaller than or greater than the one we are
  35964. * searching for, respectively, if the exact element cannot be found.
  35965. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  35966. */
  35967. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  35968. if (aHaystack.length === 0) {
  35969. return -1;
  35970. }
  35971. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  35972. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  35973. if (index < 0) {
  35974. return -1;
  35975. }
  35976. // We have found either the exact element, or the next-closest element than
  35977. // the one we are searching for. However, there may be more than one such
  35978. // element. Make sure we always return the smallest of these.
  35979. while (index - 1 >= 0) {
  35980. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  35981. break;
  35982. }
  35983. --index;
  35984. }
  35985. return index;
  35986. };
  35987. });
  35988. /* -*- Mode: js; js-indent-level: 2; -*- */
  35989. /*
  35990. * Copyright 2011 Mozilla Foundation and contributors
  35991. * Licensed under the New BSD license. See LICENSE or:
  35992. * http://opensource.org/licenses/BSD-3-Clause
  35993. */
  35994. // It turns out that some (most?) JavaScript engines don't self-host
  35995. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  35996. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  35997. // custom comparator function, calling back and forth between the VM's C++ and
  35998. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  35999. // worse generated code for the comparator function than would be optimal. In
  36000. // fact, when sorting with a comparator, these costs outweigh the benefits of
  36001. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  36002. // a ~3500ms mean speed-up in `bench/bench.html`.
  36003. function SortTemplate(comparator) {
  36004. /**
  36005. * Swap the elements indexed by `x` and `y` in the array `ary`.
  36006. *
  36007. * @param {Array} ary
  36008. * The array.
  36009. * @param {Number} x
  36010. * The index of the first item.
  36011. * @param {Number} y
  36012. * The index of the second item.
  36013. */
  36014. function swap(ary, x, y) {
  36015. var temp = ary[x];
  36016. ary[x] = ary[y];
  36017. ary[y] = temp;
  36018. }
  36019. /**
  36020. * Returns a random integer within the range `low .. high` inclusive.
  36021. *
  36022. * @param {Number} low
  36023. * The lower bound on the range.
  36024. * @param {Number} high
  36025. * The upper bound on the range.
  36026. */
  36027. function randomIntInRange(low, high) {
  36028. return Math.round(low + (Math.random() * (high - low)));
  36029. }
  36030. /**
  36031. * The Quick Sort algorithm.
  36032. *
  36033. * @param {Array} ary
  36034. * An array to sort.
  36035. * @param {function} comparator
  36036. * Function to use to compare two items.
  36037. * @param {Number} p
  36038. * Start index of the array
  36039. * @param {Number} r
  36040. * End index of the array
  36041. */
  36042. function doQuickSort(ary, comparator, p, r) {
  36043. // If our lower bound is less than our upper bound, we (1) partition the
  36044. // array into two pieces and (2) recurse on each half. If it is not, this is
  36045. // the empty array and our base case.
  36046. if (p < r) {
  36047. // (1) Partitioning.
  36048. //
  36049. // The partitioning chooses a pivot between `p` and `r` and moves all
  36050. // elements that are less than or equal to the pivot to the before it, and
  36051. // all the elements that are greater than it after it. The effect is that
  36052. // once partition is done, the pivot is in the exact place it will be when
  36053. // the array is put in sorted order, and it will not need to be moved
  36054. // again. This runs in O(n) time.
  36055. // Always choose a random pivot so that an input array which is reverse
  36056. // sorted does not cause O(n^2) running time.
  36057. var pivotIndex = randomIntInRange(p, r);
  36058. var i = p - 1;
  36059. swap(ary, pivotIndex, r);
  36060. var pivot = ary[r];
  36061. // Immediately after `j` is incremented in this loop, the following hold
  36062. // true:
  36063. //
  36064. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  36065. //
  36066. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  36067. for (var j = p; j < r; j++) {
  36068. if (comparator(ary[j], pivot, false) <= 0) {
  36069. i += 1;
  36070. swap(ary, i, j);
  36071. }
  36072. }
  36073. swap(ary, i + 1, j);
  36074. var q = i + 1;
  36075. // (2) Recurse on each half.
  36076. doQuickSort(ary, comparator, p, q - 1);
  36077. doQuickSort(ary, comparator, q + 1, r);
  36078. }
  36079. }
  36080. return doQuickSort;
  36081. }
  36082. function cloneSort(comparator) {
  36083. let template = SortTemplate.toString();
  36084. let templateFn = new Function(`return ${template}`)();
  36085. return templateFn(comparator);
  36086. }
  36087. /**
  36088. * Sort the given array in-place with the given comparator function.
  36089. *
  36090. * @param {Array} ary
  36091. * An array to sort.
  36092. * @param {function} comparator
  36093. * Function to use to compare two items.
  36094. */
  36095. let sortCache = new WeakMap();
  36096. var quickSort_1$1 = function (ary, comparator, start = 0) {
  36097. let doQuickSort = sortCache.get(comparator);
  36098. if (doQuickSort === void 0) {
  36099. doQuickSort = cloneSort(comparator);
  36100. sortCache.set(comparator, doQuickSort);
  36101. }
  36102. doQuickSort(ary, comparator, start, ary.length - 1);
  36103. };
  36104. var quickSort$2 = {
  36105. quickSort: quickSort_1$1
  36106. };
  36107. /* -*- Mode: js; js-indent-level: 2; -*- */
  36108. /*
  36109. * Copyright 2011 Mozilla Foundation and contributors
  36110. * Licensed under the New BSD license. See LICENSE or:
  36111. * http://opensource.org/licenses/BSD-3-Clause
  36112. */
  36113. var ArraySet$5 = arraySet$1.ArraySet;
  36114. var quickSort$3 = quickSort$2.quickSort;
  36115. function SourceMapConsumer$2(aSourceMap, aSourceMapURL) {
  36116. var sourceMap = aSourceMap;
  36117. if (typeof aSourceMap === 'string') {
  36118. sourceMap = util$1.parseSourceMapInput(aSourceMap);
  36119. }
  36120. return sourceMap.sections != null
  36121. ? new IndexedSourceMapConsumer$1(sourceMap, aSourceMapURL)
  36122. : new BasicSourceMapConsumer$1(sourceMap, aSourceMapURL);
  36123. }
  36124. SourceMapConsumer$2.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  36125. return BasicSourceMapConsumer$1.fromSourceMap(aSourceMap, aSourceMapURL);
  36126. };
  36127. /**
  36128. * The version of the source mapping spec that we are consuming.
  36129. */
  36130. SourceMapConsumer$2.prototype._version = 3;
  36131. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  36132. // parsed mapping coordinates from the source map's "mappings" attribute. They
  36133. // are lazily instantiated, accessed via the `_generatedMappings` and
  36134. // `_originalMappings` getters respectively, and we only parse the mappings
  36135. // and create these arrays once queried for a source location. We jump through
  36136. // these hoops because there can be many thousands of mappings, and parsing
  36137. // them is expensive, so we only want to do it if we must.
  36138. //
  36139. // Each object in the arrays is of the form:
  36140. //
  36141. // {
  36142. // generatedLine: The line number in the generated code,
  36143. // generatedColumn: The column number in the generated code,
  36144. // source: The path to the original source file that generated this
  36145. // chunk of code,
  36146. // originalLine: The line number in the original source that
  36147. // corresponds to this chunk of generated code,
  36148. // originalColumn: The column number in the original source that
  36149. // corresponds to this chunk of generated code,
  36150. // name: The name of the original symbol which generated this chunk of
  36151. // code.
  36152. // }
  36153. //
  36154. // All properties except for `generatedLine` and `generatedColumn` can be
  36155. // `null`.
  36156. //
  36157. // `_generatedMappings` is ordered by the generated positions.
  36158. //
  36159. // `_originalMappings` is ordered by the original positions.
  36160. SourceMapConsumer$2.prototype.__generatedMappings = null;
  36161. Object.defineProperty(SourceMapConsumer$2.prototype, '_generatedMappings', {
  36162. configurable: true,
  36163. enumerable: true,
  36164. get: function () {
  36165. if (!this.__generatedMappings) {
  36166. this._parseMappings(this._mappings, this.sourceRoot);
  36167. }
  36168. return this.__generatedMappings;
  36169. }
  36170. });
  36171. SourceMapConsumer$2.prototype.__originalMappings = null;
  36172. Object.defineProperty(SourceMapConsumer$2.prototype, '_originalMappings', {
  36173. configurable: true,
  36174. enumerable: true,
  36175. get: function () {
  36176. if (!this.__originalMappings) {
  36177. this._parseMappings(this._mappings, this.sourceRoot);
  36178. }
  36179. return this.__originalMappings;
  36180. }
  36181. });
  36182. SourceMapConsumer$2.prototype._charIsMappingSeparator =
  36183. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  36184. var c = aStr.charAt(index);
  36185. return c === ";" || c === ",";
  36186. };
  36187. /**
  36188. * Parse the mappings in a string in to a data structure which we can easily
  36189. * query (the ordered arrays in the `this.__generatedMappings` and
  36190. * `this.__originalMappings` properties).
  36191. */
  36192. SourceMapConsumer$2.prototype._parseMappings =
  36193. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  36194. throw new Error("Subclasses must implement _parseMappings");
  36195. };
  36196. SourceMapConsumer$2.GENERATED_ORDER = 1;
  36197. SourceMapConsumer$2.ORIGINAL_ORDER = 2;
  36198. SourceMapConsumer$2.GREATEST_LOWER_BOUND = 1;
  36199. SourceMapConsumer$2.LEAST_UPPER_BOUND = 2;
  36200. /**
  36201. * Iterate over each mapping between an original source/line/column and a
  36202. * generated line/column in this source map.
  36203. *
  36204. * @param Function aCallback
  36205. * The function that is called with each mapping.
  36206. * @param Object aContext
  36207. * Optional. If specified, this object will be the value of `this` every
  36208. * time that `aCallback` is called.
  36209. * @param aOrder
  36210. * Either `SourceMapConsumer.GENERATED_ORDER` or
  36211. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  36212. * iterate over the mappings sorted by the generated file's line/column
  36213. * order or the original's source/line/column order, respectively. Defaults to
  36214. * `SourceMapConsumer.GENERATED_ORDER`.
  36215. */
  36216. SourceMapConsumer$2.prototype.eachMapping =
  36217. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  36218. var context = aContext || null;
  36219. var order = aOrder || SourceMapConsumer$2.GENERATED_ORDER;
  36220. var mappings;
  36221. switch (order) {
  36222. case SourceMapConsumer$2.GENERATED_ORDER:
  36223. mappings = this._generatedMappings;
  36224. break;
  36225. case SourceMapConsumer$2.ORIGINAL_ORDER:
  36226. mappings = this._originalMappings;
  36227. break;
  36228. default:
  36229. throw new Error("Unknown order of iteration.");
  36230. }
  36231. var sourceRoot = this.sourceRoot;
  36232. var boundCallback = aCallback.bind(context);
  36233. var names = this._names;
  36234. var sources = this._sources;
  36235. var sourceMapURL = this._sourceMapURL;
  36236. for (var i = 0, n = mappings.length; i < n; i++) {
  36237. var mapping = mappings[i];
  36238. var source = mapping.source === null ? null : sources.at(mapping.source);
  36239. source = util$1.computeSourceURL(sourceRoot, source, sourceMapURL);
  36240. boundCallback({
  36241. source: source,
  36242. generatedLine: mapping.generatedLine,
  36243. generatedColumn: mapping.generatedColumn,
  36244. originalLine: mapping.originalLine,
  36245. originalColumn: mapping.originalColumn,
  36246. name: mapping.name === null ? null : names.at(mapping.name)
  36247. });
  36248. }
  36249. };
  36250. /**
  36251. * Returns all generated line and column information for the original source,
  36252. * line, and column provided. If no column is provided, returns all mappings
  36253. * corresponding to a either the line we are searching for or the next
  36254. * closest line that has any mappings. Otherwise, returns all mappings
  36255. * corresponding to the given line and either the column we are searching for
  36256. * or the next closest column that has any offsets.
  36257. *
  36258. * The only argument is an object with the following properties:
  36259. *
  36260. * - source: The filename of the original source.
  36261. * - line: The line number in the original source. The line number is 1-based.
  36262. * - column: Optional. the column number in the original source.
  36263. * The column number is 0-based.
  36264. *
  36265. * and an array of objects is returned, each with the following properties:
  36266. *
  36267. * - line: The line number in the generated source, or null. The
  36268. * line number is 1-based.
  36269. * - column: The column number in the generated source, or null.
  36270. * The column number is 0-based.
  36271. */
  36272. SourceMapConsumer$2.prototype.allGeneratedPositionsFor =
  36273. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  36274. var line = util$1.getArg(aArgs, 'line');
  36275. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  36276. // returns the index of the closest mapping less than the needle. By
  36277. // setting needle.originalColumn to 0, we thus find the last mapping for
  36278. // the given line, provided such a mapping exists.
  36279. var needle = {
  36280. source: util$1.getArg(aArgs, 'source'),
  36281. originalLine: line,
  36282. originalColumn: util$1.getArg(aArgs, 'column', 0)
  36283. };
  36284. needle.source = this._findSourceIndex(needle.source);
  36285. if (needle.source < 0) {
  36286. return [];
  36287. }
  36288. var mappings = [];
  36289. var index = this._findMapping(needle,
  36290. this._originalMappings,
  36291. "originalLine",
  36292. "originalColumn",
  36293. util$1.compareByOriginalPositions,
  36294. binarySearch$1.LEAST_UPPER_BOUND);
  36295. if (index >= 0) {
  36296. var mapping = this._originalMappings[index];
  36297. if (aArgs.column === undefined) {
  36298. var originalLine = mapping.originalLine;
  36299. // Iterate until either we run out of mappings, or we run into
  36300. // a mapping for a different line than the one we found. Since
  36301. // mappings are sorted, this is guaranteed to find all mappings for
  36302. // the line we found.
  36303. while (mapping && mapping.originalLine === originalLine) {
  36304. mappings.push({
  36305. line: util$1.getArg(mapping, 'generatedLine', null),
  36306. column: util$1.getArg(mapping, 'generatedColumn', null),
  36307. lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
  36308. });
  36309. mapping = this._originalMappings[++index];
  36310. }
  36311. } else {
  36312. var originalColumn = mapping.originalColumn;
  36313. // Iterate until either we run out of mappings, or we run into
  36314. // a mapping for a different line than the one we were searching for.
  36315. // Since mappings are sorted, this is guaranteed to find all mappings for
  36316. // the line we are searching for.
  36317. while (mapping &&
  36318. mapping.originalLine === line &&
  36319. mapping.originalColumn == originalColumn) {
  36320. mappings.push({
  36321. line: util$1.getArg(mapping, 'generatedLine', null),
  36322. column: util$1.getArg(mapping, 'generatedColumn', null),
  36323. lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
  36324. });
  36325. mapping = this._originalMappings[++index];
  36326. }
  36327. }
  36328. }
  36329. return mappings;
  36330. };
  36331. var SourceMapConsumer_1$1 = SourceMapConsumer$2;
  36332. /**
  36333. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  36334. * query for information about the original file positions by giving it a file
  36335. * position in the generated source.
  36336. *
  36337. * The first parameter is the raw source map (either as a JSON string, or
  36338. * already parsed to an object). According to the spec, source maps have the
  36339. * following attributes:
  36340. *
  36341. * - version: Which version of the source map spec this map is following.
  36342. * - sources: An array of URLs to the original source files.
  36343. * - names: An array of identifiers which can be referrenced by individual mappings.
  36344. * - sourceRoot: Optional. The URL root from which all sources are relative.
  36345. * - sourcesContent: Optional. An array of contents of the original source files.
  36346. * - mappings: A string of base64 VLQs which contain the actual mappings.
  36347. * - file: Optional. The generated file this source map is associated with.
  36348. *
  36349. * Here is an example source map, taken from the source map spec[0]:
  36350. *
  36351. * {
  36352. * version : 3,
  36353. * file: "out.js",
  36354. * sourceRoot : "",
  36355. * sources: ["foo.js", "bar.js"],
  36356. * names: ["src", "maps", "are", "fun"],
  36357. * mappings: "AA,AB;;ABCDE;"
  36358. * }
  36359. *
  36360. * The second parameter, if given, is a string whose value is the URL
  36361. * at which the source map was found. This URL is used to compute the
  36362. * sources array.
  36363. *
  36364. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  36365. */
  36366. function BasicSourceMapConsumer$1(aSourceMap, aSourceMapURL) {
  36367. var sourceMap = aSourceMap;
  36368. if (typeof aSourceMap === 'string') {
  36369. sourceMap = util$1.parseSourceMapInput(aSourceMap);
  36370. }
  36371. var version = util$1.getArg(sourceMap, 'version');
  36372. var sources = util$1.getArg(sourceMap, 'sources');
  36373. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  36374. // requires the array) to play nice here.
  36375. var names = util$1.getArg(sourceMap, 'names', []);
  36376. var sourceRoot = util$1.getArg(sourceMap, 'sourceRoot', null);
  36377. var sourcesContent = util$1.getArg(sourceMap, 'sourcesContent', null);
  36378. var mappings = util$1.getArg(sourceMap, 'mappings');
  36379. var file = util$1.getArg(sourceMap, 'file', null);
  36380. // Once again, Sass deviates from the spec and supplies the version as a
  36381. // string rather than a number, so we use loose equality checking here.
  36382. if (version != this._version) {
  36383. throw new Error('Unsupported version: ' + version);
  36384. }
  36385. if (sourceRoot) {
  36386. sourceRoot = util$1.normalize(sourceRoot);
  36387. }
  36388. sources = sources
  36389. .map(String)
  36390. // Some source maps produce relative source paths like "./foo.js" instead of
  36391. // "foo.js". Normalize these first so that future comparisons will succeed.
  36392. // See bugzil.la/1090768.
  36393. .map(util$1.normalize)
  36394. // Always ensure that absolute sources are internally stored relative to
  36395. // the source root, if the source root is absolute. Not doing this would
  36396. // be particularly problematic when the source root is a prefix of the
  36397. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  36398. .map(function (source) {
  36399. return sourceRoot && util$1.isAbsolute(sourceRoot) && util$1.isAbsolute(source)
  36400. ? util$1.relative(sourceRoot, source)
  36401. : source;
  36402. });
  36403. // Pass `true` below to allow duplicate names and sources. While source maps
  36404. // are intended to be compressed and deduplicated, the TypeScript compiler
  36405. // sometimes generates source maps with duplicates in them. See Github issue
  36406. // #72 and bugzil.la/889492.
  36407. this._names = ArraySet$5.fromArray(names.map(String), true);
  36408. this._sources = ArraySet$5.fromArray(sources, true);
  36409. this._absoluteSources = this._sources.toArray().map(function (s) {
  36410. return util$1.computeSourceURL(sourceRoot, s, aSourceMapURL);
  36411. });
  36412. this.sourceRoot = sourceRoot;
  36413. this.sourcesContent = sourcesContent;
  36414. this._mappings = mappings;
  36415. this._sourceMapURL = aSourceMapURL;
  36416. this.file = file;
  36417. }
  36418. BasicSourceMapConsumer$1.prototype = Object.create(SourceMapConsumer$2.prototype);
  36419. BasicSourceMapConsumer$1.prototype.consumer = SourceMapConsumer$2;
  36420. /**
  36421. * Utility function to find the index of a source. Returns -1 if not
  36422. * found.
  36423. */
  36424. BasicSourceMapConsumer$1.prototype._findSourceIndex = function(aSource) {
  36425. var relativeSource = aSource;
  36426. if (this.sourceRoot != null) {
  36427. relativeSource = util$1.relative(this.sourceRoot, relativeSource);
  36428. }
  36429. if (this._sources.has(relativeSource)) {
  36430. return this._sources.indexOf(relativeSource);
  36431. }
  36432. // Maybe aSource is an absolute URL as returned by |sources|. In
  36433. // this case we can't simply undo the transform.
  36434. var i;
  36435. for (i = 0; i < this._absoluteSources.length; ++i) {
  36436. if (this._absoluteSources[i] == aSource) {
  36437. return i;
  36438. }
  36439. }
  36440. return -1;
  36441. };
  36442. /**
  36443. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  36444. *
  36445. * @param SourceMapGenerator aSourceMap
  36446. * The source map that will be consumed.
  36447. * @param String aSourceMapURL
  36448. * The URL at which the source map can be found (optional)
  36449. * @returns BasicSourceMapConsumer
  36450. */
  36451. BasicSourceMapConsumer$1.fromSourceMap =
  36452. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  36453. var smc = Object.create(BasicSourceMapConsumer$1.prototype);
  36454. var names = smc._names = ArraySet$5.fromArray(aSourceMap._names.toArray(), true);
  36455. var sources = smc._sources = ArraySet$5.fromArray(aSourceMap._sources.toArray(), true);
  36456. smc.sourceRoot = aSourceMap._sourceRoot;
  36457. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  36458. smc.sourceRoot);
  36459. smc.file = aSourceMap._file;
  36460. smc._sourceMapURL = aSourceMapURL;
  36461. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  36462. return util$1.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  36463. });
  36464. // Because we are modifying the entries (by converting string sources and
  36465. // names to indices into the sources and names ArraySets), we have to make
  36466. // a copy of the entry or else bad things happen. Shared mutable state
  36467. // strikes again! See github issue #191.
  36468. var generatedMappings = aSourceMap._mappings.toArray().slice();
  36469. var destGeneratedMappings = smc.__generatedMappings = [];
  36470. var destOriginalMappings = smc.__originalMappings = [];
  36471. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  36472. var srcMapping = generatedMappings[i];
  36473. var destMapping = new Mapping$1;
  36474. destMapping.generatedLine = srcMapping.generatedLine;
  36475. destMapping.generatedColumn = srcMapping.generatedColumn;
  36476. if (srcMapping.source) {
  36477. destMapping.source = sources.indexOf(srcMapping.source);
  36478. destMapping.originalLine = srcMapping.originalLine;
  36479. destMapping.originalColumn = srcMapping.originalColumn;
  36480. if (srcMapping.name) {
  36481. destMapping.name = names.indexOf(srcMapping.name);
  36482. }
  36483. destOriginalMappings.push(destMapping);
  36484. }
  36485. destGeneratedMappings.push(destMapping);
  36486. }
  36487. quickSort$3(smc.__originalMappings, util$1.compareByOriginalPositions);
  36488. return smc;
  36489. };
  36490. /**
  36491. * The version of the source mapping spec that we are consuming.
  36492. */
  36493. BasicSourceMapConsumer$1.prototype._version = 3;
  36494. /**
  36495. * The list of original sources.
  36496. */
  36497. Object.defineProperty(BasicSourceMapConsumer$1.prototype, 'sources', {
  36498. get: function () {
  36499. return this._absoluteSources.slice();
  36500. }
  36501. });
  36502. /**
  36503. * Provide the JIT with a nice shape / hidden class.
  36504. */
  36505. function Mapping$1() {
  36506. this.generatedLine = 0;
  36507. this.generatedColumn = 0;
  36508. this.source = null;
  36509. this.originalLine = null;
  36510. this.originalColumn = null;
  36511. this.name = null;
  36512. }
  36513. /**
  36514. * Parse the mappings in a string in to a data structure which we can easily
  36515. * query (the ordered arrays in the `this.__generatedMappings` and
  36516. * `this.__originalMappings` properties).
  36517. */
  36518. const compareGenerated = util$1.compareByGeneratedPositionsDeflatedNoLine;
  36519. function sortGenerated(array, start) {
  36520. let l = array.length;
  36521. let n = array.length - start;
  36522. if (n <= 1) {
  36523. return;
  36524. } else if (n == 2) {
  36525. let a = array[start];
  36526. let b = array[start + 1];
  36527. if (compareGenerated(a, b) > 0) {
  36528. array[start] = b;
  36529. array[start + 1] = a;
  36530. }
  36531. } else if (n < 20) {
  36532. for (let i = start; i < l; i++) {
  36533. for (let j = i; j > start; j--) {
  36534. let a = array[j - 1];
  36535. let b = array[j];
  36536. if (compareGenerated(a, b) <= 0) {
  36537. break;
  36538. }
  36539. array[j - 1] = b;
  36540. array[j] = a;
  36541. }
  36542. }
  36543. } else {
  36544. quickSort$3(array, compareGenerated, start);
  36545. }
  36546. }
  36547. BasicSourceMapConsumer$1.prototype._parseMappings =
  36548. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  36549. var generatedLine = 1;
  36550. var previousGeneratedColumn = 0;
  36551. var previousOriginalLine = 0;
  36552. var previousOriginalColumn = 0;
  36553. var previousSource = 0;
  36554. var previousName = 0;
  36555. var length = aStr.length;
  36556. var index = 0;
  36557. var temp = {};
  36558. var originalMappings = [];
  36559. var generatedMappings = [];
  36560. var mapping, segment, end, value;
  36561. let subarrayStart = 0;
  36562. while (index < length) {
  36563. if (aStr.charAt(index) === ';') {
  36564. generatedLine++;
  36565. index++;
  36566. previousGeneratedColumn = 0;
  36567. sortGenerated(generatedMappings, subarrayStart);
  36568. subarrayStart = generatedMappings.length;
  36569. }
  36570. else if (aStr.charAt(index) === ',') {
  36571. index++;
  36572. }
  36573. else {
  36574. mapping = new Mapping$1();
  36575. mapping.generatedLine = generatedLine;
  36576. for (end = index; end < length; end++) {
  36577. if (this._charIsMappingSeparator(aStr, end)) {
  36578. break;
  36579. }
  36580. }
  36581. aStr.slice(index, end);
  36582. segment = [];
  36583. while (index < end) {
  36584. base64Vlq$1.decode(aStr, index, temp);
  36585. value = temp.value;
  36586. index = temp.rest;
  36587. segment.push(value);
  36588. }
  36589. if (segment.length === 2) {
  36590. throw new Error('Found a source, but no line and column');
  36591. }
  36592. if (segment.length === 3) {
  36593. throw new Error('Found a source and line, but no column');
  36594. }
  36595. // Generated column.
  36596. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  36597. previousGeneratedColumn = mapping.generatedColumn;
  36598. if (segment.length > 1) {
  36599. // Original source.
  36600. mapping.source = previousSource + segment[1];
  36601. previousSource += segment[1];
  36602. // Original line.
  36603. mapping.originalLine = previousOriginalLine + segment[2];
  36604. previousOriginalLine = mapping.originalLine;
  36605. // Lines are stored 0-based
  36606. mapping.originalLine += 1;
  36607. // Original column.
  36608. mapping.originalColumn = previousOriginalColumn + segment[3];
  36609. previousOriginalColumn = mapping.originalColumn;
  36610. if (segment.length > 4) {
  36611. // Original name.
  36612. mapping.name = previousName + segment[4];
  36613. previousName += segment[4];
  36614. }
  36615. }
  36616. generatedMappings.push(mapping);
  36617. if (typeof mapping.originalLine === 'number') {
  36618. let currentSource = mapping.source;
  36619. while (originalMappings.length <= currentSource) {
  36620. originalMappings.push(null);
  36621. }
  36622. if (originalMappings[currentSource] === null) {
  36623. originalMappings[currentSource] = [];
  36624. }
  36625. originalMappings[currentSource].push(mapping);
  36626. }
  36627. }
  36628. }
  36629. sortGenerated(generatedMappings, subarrayStart);
  36630. this.__generatedMappings = generatedMappings;
  36631. for (var i = 0; i < originalMappings.length; i++) {
  36632. if (originalMappings[i] != null) {
  36633. quickSort$3(originalMappings[i], util$1.compareByOriginalPositionsNoSource);
  36634. }
  36635. }
  36636. this.__originalMappings = [].concat(...originalMappings);
  36637. };
  36638. /**
  36639. * Find the mapping that best matches the hypothetical "needle" mapping that
  36640. * we are searching for in the given "haystack" of mappings.
  36641. */
  36642. BasicSourceMapConsumer$1.prototype._findMapping =
  36643. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  36644. aColumnName, aComparator, aBias) {
  36645. // To return the position we are searching for, we must first find the
  36646. // mapping for the given position and then return the opposite position it
  36647. // points to. Because the mappings are sorted, we can use binary search to
  36648. // find the best mapping.
  36649. if (aNeedle[aLineName] <= 0) {
  36650. throw new TypeError('Line must be greater than or equal to 1, got '
  36651. + aNeedle[aLineName]);
  36652. }
  36653. if (aNeedle[aColumnName] < 0) {
  36654. throw new TypeError('Column must be greater than or equal to 0, got '
  36655. + aNeedle[aColumnName]);
  36656. }
  36657. return binarySearch$1.search(aNeedle, aMappings, aComparator, aBias);
  36658. };
  36659. /**
  36660. * Compute the last column for each generated mapping. The last column is
  36661. * inclusive.
  36662. */
  36663. BasicSourceMapConsumer$1.prototype.computeColumnSpans =
  36664. function SourceMapConsumer_computeColumnSpans() {
  36665. for (var index = 0; index < this._generatedMappings.length; ++index) {
  36666. var mapping = this._generatedMappings[index];
  36667. // Mappings do not contain a field for the last generated columnt. We
  36668. // can come up with an optimistic estimate, however, by assuming that
  36669. // mappings are contiguous (i.e. given two consecutive mappings, the
  36670. // first mapping ends where the second one starts).
  36671. if (index + 1 < this._generatedMappings.length) {
  36672. var nextMapping = this._generatedMappings[index + 1];
  36673. if (mapping.generatedLine === nextMapping.generatedLine) {
  36674. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  36675. continue;
  36676. }
  36677. }
  36678. // The last mapping for each line spans the entire line.
  36679. mapping.lastGeneratedColumn = Infinity;
  36680. }
  36681. };
  36682. /**
  36683. * Returns the original source, line, and column information for the generated
  36684. * source's line and column positions provided. The only argument is an object
  36685. * with the following properties:
  36686. *
  36687. * - line: The line number in the generated source. The line number
  36688. * is 1-based.
  36689. * - column: The column number in the generated source. The column
  36690. * number is 0-based.
  36691. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  36692. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  36693. * closest element that is smaller than or greater than the one we are
  36694. * searching for, respectively, if the exact element cannot be found.
  36695. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  36696. *
  36697. * and an object is returned with the following properties:
  36698. *
  36699. * - source: The original source file, or null.
  36700. * - line: The line number in the original source, or null. The
  36701. * line number is 1-based.
  36702. * - column: The column number in the original source, or null. The
  36703. * column number is 0-based.
  36704. * - name: The original identifier, or null.
  36705. */
  36706. BasicSourceMapConsumer$1.prototype.originalPositionFor =
  36707. function SourceMapConsumer_originalPositionFor(aArgs) {
  36708. var needle = {
  36709. generatedLine: util$1.getArg(aArgs, 'line'),
  36710. generatedColumn: util$1.getArg(aArgs, 'column')
  36711. };
  36712. var index = this._findMapping(
  36713. needle,
  36714. this._generatedMappings,
  36715. "generatedLine",
  36716. "generatedColumn",
  36717. util$1.compareByGeneratedPositionsDeflated,
  36718. util$1.getArg(aArgs, 'bias', SourceMapConsumer$2.GREATEST_LOWER_BOUND)
  36719. );
  36720. if (index >= 0) {
  36721. var mapping = this._generatedMappings[index];
  36722. if (mapping.generatedLine === needle.generatedLine) {
  36723. var source = util$1.getArg(mapping, 'source', null);
  36724. if (source !== null) {
  36725. source = this._sources.at(source);
  36726. source = util$1.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  36727. }
  36728. var name = util$1.getArg(mapping, 'name', null);
  36729. if (name !== null) {
  36730. name = this._names.at(name);
  36731. }
  36732. return {
  36733. source: source,
  36734. line: util$1.getArg(mapping, 'originalLine', null),
  36735. column: util$1.getArg(mapping, 'originalColumn', null),
  36736. name: name
  36737. };
  36738. }
  36739. }
  36740. return {
  36741. source: null,
  36742. line: null,
  36743. column: null,
  36744. name: null
  36745. };
  36746. };
  36747. /**
  36748. * Return true if we have the source content for every source in the source
  36749. * map, false otherwise.
  36750. */
  36751. BasicSourceMapConsumer$1.prototype.hasContentsOfAllSources =
  36752. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  36753. if (!this.sourcesContent) {
  36754. return false;
  36755. }
  36756. return this.sourcesContent.length >= this._sources.size() &&
  36757. !this.sourcesContent.some(function (sc) { return sc == null; });
  36758. };
  36759. /**
  36760. * Returns the original source content. The only argument is the url of the
  36761. * original source file. Returns null if no original source content is
  36762. * available.
  36763. */
  36764. BasicSourceMapConsumer$1.prototype.sourceContentFor =
  36765. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  36766. if (!this.sourcesContent) {
  36767. return null;
  36768. }
  36769. var index = this._findSourceIndex(aSource);
  36770. if (index >= 0) {
  36771. return this.sourcesContent[index];
  36772. }
  36773. var relativeSource = aSource;
  36774. if (this.sourceRoot != null) {
  36775. relativeSource = util$1.relative(this.sourceRoot, relativeSource);
  36776. }
  36777. var url;
  36778. if (this.sourceRoot != null
  36779. && (url = util$1.urlParse(this.sourceRoot))) {
  36780. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  36781. // many users. We can help them out when they expect file:// URIs to
  36782. // behave like it would if they were running a local HTTP server. See
  36783. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  36784. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  36785. if (url.scheme == "file"
  36786. && this._sources.has(fileUriAbsPath)) {
  36787. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  36788. }
  36789. if ((!url.path || url.path == "/")
  36790. && this._sources.has("/" + relativeSource)) {
  36791. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  36792. }
  36793. }
  36794. // This function is used recursively from
  36795. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  36796. // don't want to throw if we can't find the source - we just want to
  36797. // return null, so we provide a flag to exit gracefully.
  36798. if (nullOnMissing) {
  36799. return null;
  36800. }
  36801. else {
  36802. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  36803. }
  36804. };
  36805. /**
  36806. * Returns the generated line and column information for the original source,
  36807. * line, and column positions provided. The only argument is an object with
  36808. * the following properties:
  36809. *
  36810. * - source: The filename of the original source.
  36811. * - line: The line number in the original source. The line number
  36812. * is 1-based.
  36813. * - column: The column number in the original source. The column
  36814. * number is 0-based.
  36815. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  36816. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  36817. * closest element that is smaller than or greater than the one we are
  36818. * searching for, respectively, if the exact element cannot be found.
  36819. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  36820. *
  36821. * and an object is returned with the following properties:
  36822. *
  36823. * - line: The line number in the generated source, or null. The
  36824. * line number is 1-based.
  36825. * - column: The column number in the generated source, or null.
  36826. * The column number is 0-based.
  36827. */
  36828. BasicSourceMapConsumer$1.prototype.generatedPositionFor =
  36829. function SourceMapConsumer_generatedPositionFor(aArgs) {
  36830. var source = util$1.getArg(aArgs, 'source');
  36831. source = this._findSourceIndex(source);
  36832. if (source < 0) {
  36833. return {
  36834. line: null,
  36835. column: null,
  36836. lastColumn: null
  36837. };
  36838. }
  36839. var needle = {
  36840. source: source,
  36841. originalLine: util$1.getArg(aArgs, 'line'),
  36842. originalColumn: util$1.getArg(aArgs, 'column')
  36843. };
  36844. var index = this._findMapping(
  36845. needle,
  36846. this._originalMappings,
  36847. "originalLine",
  36848. "originalColumn",
  36849. util$1.compareByOriginalPositions,
  36850. util$1.getArg(aArgs, 'bias', SourceMapConsumer$2.GREATEST_LOWER_BOUND)
  36851. );
  36852. if (index >= 0) {
  36853. var mapping = this._originalMappings[index];
  36854. if (mapping.source === needle.source) {
  36855. return {
  36856. line: util$1.getArg(mapping, 'generatedLine', null),
  36857. column: util$1.getArg(mapping, 'generatedColumn', null),
  36858. lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
  36859. };
  36860. }
  36861. }
  36862. return {
  36863. line: null,
  36864. column: null,
  36865. lastColumn: null
  36866. };
  36867. };
  36868. var BasicSourceMapConsumer_1$1 = BasicSourceMapConsumer$1;
  36869. /**
  36870. * An IndexedSourceMapConsumer instance represents a parsed source map which
  36871. * we can query for information. It differs from BasicSourceMapConsumer in
  36872. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  36873. * input.
  36874. *
  36875. * The first parameter is a raw source map (either as a JSON string, or already
  36876. * parsed to an object). According to the spec for indexed source maps, they
  36877. * have the following attributes:
  36878. *
  36879. * - version: Which version of the source map spec this map is following.
  36880. * - file: Optional. The generated file this source map is associated with.
  36881. * - sections: A list of section definitions.
  36882. *
  36883. * Each value under the "sections" field has two fields:
  36884. * - offset: The offset into the original specified at which this section
  36885. * begins to apply, defined as an object with a "line" and "column"
  36886. * field.
  36887. * - map: A source map definition. This source map could also be indexed,
  36888. * but doesn't have to be.
  36889. *
  36890. * Instead of the "map" field, it's also possible to have a "url" field
  36891. * specifying a URL to retrieve a source map from, but that's currently
  36892. * unsupported.
  36893. *
  36894. * Here's an example source map, taken from the source map spec[0], but
  36895. * modified to omit a section which uses the "url" field.
  36896. *
  36897. * {
  36898. * version : 3,
  36899. * file: "app.js",
  36900. * sections: [{
  36901. * offset: {line:100, column:10},
  36902. * map: {
  36903. * version : 3,
  36904. * file: "section.js",
  36905. * sources: ["foo.js", "bar.js"],
  36906. * names: ["src", "maps", "are", "fun"],
  36907. * mappings: "AAAA,E;;ABCDE;"
  36908. * }
  36909. * }],
  36910. * }
  36911. *
  36912. * The second parameter, if given, is a string whose value is the URL
  36913. * at which the source map was found. This URL is used to compute the
  36914. * sources array.
  36915. *
  36916. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  36917. */
  36918. function IndexedSourceMapConsumer$1(aSourceMap, aSourceMapURL) {
  36919. var sourceMap = aSourceMap;
  36920. if (typeof aSourceMap === 'string') {
  36921. sourceMap = util$1.parseSourceMapInput(aSourceMap);
  36922. }
  36923. var version = util$1.getArg(sourceMap, 'version');
  36924. var sections = util$1.getArg(sourceMap, 'sections');
  36925. if (version != this._version) {
  36926. throw new Error('Unsupported version: ' + version);
  36927. }
  36928. this._sources = new ArraySet$5();
  36929. this._names = new ArraySet$5();
  36930. var lastOffset = {
  36931. line: -1,
  36932. column: 0
  36933. };
  36934. this._sections = sections.map(function (s) {
  36935. if (s.url) {
  36936. // The url field will require support for asynchronicity.
  36937. // See https://github.com/mozilla/source-map/issues/16
  36938. throw new Error('Support for url field in sections not implemented.');
  36939. }
  36940. var offset = util$1.getArg(s, 'offset');
  36941. var offsetLine = util$1.getArg(offset, 'line');
  36942. var offsetColumn = util$1.getArg(offset, 'column');
  36943. if (offsetLine < lastOffset.line ||
  36944. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  36945. throw new Error('Section offsets must be ordered and non-overlapping.');
  36946. }
  36947. lastOffset = offset;
  36948. return {
  36949. generatedOffset: {
  36950. // The offset fields are 0-based, but we use 1-based indices when
  36951. // encoding/decoding from VLQ.
  36952. generatedLine: offsetLine + 1,
  36953. generatedColumn: offsetColumn + 1
  36954. },
  36955. consumer: new SourceMapConsumer$2(util$1.getArg(s, 'map'), aSourceMapURL)
  36956. }
  36957. });
  36958. }
  36959. IndexedSourceMapConsumer$1.prototype = Object.create(SourceMapConsumer$2.prototype);
  36960. IndexedSourceMapConsumer$1.prototype.constructor = SourceMapConsumer$2;
  36961. /**
  36962. * The version of the source mapping spec that we are consuming.
  36963. */
  36964. IndexedSourceMapConsumer$1.prototype._version = 3;
  36965. /**
  36966. * The list of original sources.
  36967. */
  36968. Object.defineProperty(IndexedSourceMapConsumer$1.prototype, 'sources', {
  36969. get: function () {
  36970. var sources = [];
  36971. for (var i = 0; i < this._sections.length; i++) {
  36972. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  36973. sources.push(this._sections[i].consumer.sources[j]);
  36974. }
  36975. }
  36976. return sources;
  36977. }
  36978. });
  36979. /**
  36980. * Returns the original source, line, and column information for the generated
  36981. * source's line and column positions provided. The only argument is an object
  36982. * with the following properties:
  36983. *
  36984. * - line: The line number in the generated source. The line number
  36985. * is 1-based.
  36986. * - column: The column number in the generated source. The column
  36987. * number is 0-based.
  36988. *
  36989. * and an object is returned with the following properties:
  36990. *
  36991. * - source: The original source file, or null.
  36992. * - line: The line number in the original source, or null. The
  36993. * line number is 1-based.
  36994. * - column: The column number in the original source, or null. The
  36995. * column number is 0-based.
  36996. * - name: The original identifier, or null.
  36997. */
  36998. IndexedSourceMapConsumer$1.prototype.originalPositionFor =
  36999. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  37000. var needle = {
  37001. generatedLine: util$1.getArg(aArgs, 'line'),
  37002. generatedColumn: util$1.getArg(aArgs, 'column')
  37003. };
  37004. // Find the section containing the generated position we're trying to map
  37005. // to an original position.
  37006. var sectionIndex = binarySearch$1.search(needle, this._sections,
  37007. function(needle, section) {
  37008. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  37009. if (cmp) {
  37010. return cmp;
  37011. }
  37012. return (needle.generatedColumn -
  37013. section.generatedOffset.generatedColumn);
  37014. });
  37015. var section = this._sections[sectionIndex];
  37016. if (!section) {
  37017. return {
  37018. source: null,
  37019. line: null,
  37020. column: null,
  37021. name: null
  37022. };
  37023. }
  37024. return section.consumer.originalPositionFor({
  37025. line: needle.generatedLine -
  37026. (section.generatedOffset.generatedLine - 1),
  37027. column: needle.generatedColumn -
  37028. (section.generatedOffset.generatedLine === needle.generatedLine
  37029. ? section.generatedOffset.generatedColumn - 1
  37030. : 0),
  37031. bias: aArgs.bias
  37032. });
  37033. };
  37034. /**
  37035. * Return true if we have the source content for every source in the source
  37036. * map, false otherwise.
  37037. */
  37038. IndexedSourceMapConsumer$1.prototype.hasContentsOfAllSources =
  37039. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  37040. return this._sections.every(function (s) {
  37041. return s.consumer.hasContentsOfAllSources();
  37042. });
  37043. };
  37044. /**
  37045. * Returns the original source content. The only argument is the url of the
  37046. * original source file. Returns null if no original source content is
  37047. * available.
  37048. */
  37049. IndexedSourceMapConsumer$1.prototype.sourceContentFor =
  37050. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  37051. for (var i = 0; i < this._sections.length; i++) {
  37052. var section = this._sections[i];
  37053. var content = section.consumer.sourceContentFor(aSource, true);
  37054. if (content) {
  37055. return content;
  37056. }
  37057. }
  37058. if (nullOnMissing) {
  37059. return null;
  37060. }
  37061. else {
  37062. throw new Error('"' + aSource + '" is not in the SourceMap.');
  37063. }
  37064. };
  37065. /**
  37066. * Returns the generated line and column information for the original source,
  37067. * line, and column positions provided. The only argument is an object with
  37068. * the following properties:
  37069. *
  37070. * - source: The filename of the original source.
  37071. * - line: The line number in the original source. The line number
  37072. * is 1-based.
  37073. * - column: The column number in the original source. The column
  37074. * number is 0-based.
  37075. *
  37076. * and an object is returned with the following properties:
  37077. *
  37078. * - line: The line number in the generated source, or null. The
  37079. * line number is 1-based.
  37080. * - column: The column number in the generated source, or null.
  37081. * The column number is 0-based.
  37082. */
  37083. IndexedSourceMapConsumer$1.prototype.generatedPositionFor =
  37084. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  37085. for (var i = 0; i < this._sections.length; i++) {
  37086. var section = this._sections[i];
  37087. // Only consider this section if the requested source is in the list of
  37088. // sources of the consumer.
  37089. if (section.consumer._findSourceIndex(util$1.getArg(aArgs, 'source')) === -1) {
  37090. continue;
  37091. }
  37092. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  37093. if (generatedPosition) {
  37094. var ret = {
  37095. line: generatedPosition.line +
  37096. (section.generatedOffset.generatedLine - 1),
  37097. column: generatedPosition.column +
  37098. (section.generatedOffset.generatedLine === generatedPosition.line
  37099. ? section.generatedOffset.generatedColumn - 1
  37100. : 0)
  37101. };
  37102. return ret;
  37103. }
  37104. }
  37105. return {
  37106. line: null,
  37107. column: null
  37108. };
  37109. };
  37110. /**
  37111. * Parse the mappings in a string in to a data structure which we can easily
  37112. * query (the ordered arrays in the `this.__generatedMappings` and
  37113. * `this.__originalMappings` properties).
  37114. */
  37115. IndexedSourceMapConsumer$1.prototype._parseMappings =
  37116. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  37117. this.__generatedMappings = [];
  37118. this.__originalMappings = [];
  37119. for (var i = 0; i < this._sections.length; i++) {
  37120. var section = this._sections[i];
  37121. var sectionMappings = section.consumer._generatedMappings;
  37122. for (var j = 0; j < sectionMappings.length; j++) {
  37123. var mapping = sectionMappings[j];
  37124. var source = section.consumer._sources.at(mapping.source);
  37125. source = util$1.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  37126. this._sources.add(source);
  37127. source = this._sources.indexOf(source);
  37128. var name = null;
  37129. if (mapping.name) {
  37130. name = section.consumer._names.at(mapping.name);
  37131. this._names.add(name);
  37132. name = this._names.indexOf(name);
  37133. }
  37134. // The mappings coming from the consumer for the section have
  37135. // generated positions relative to the start of the section, so we
  37136. // need to offset them to be relative to the start of the concatenated
  37137. // generated file.
  37138. var adjustedMapping = {
  37139. source: source,
  37140. generatedLine: mapping.generatedLine +
  37141. (section.generatedOffset.generatedLine - 1),
  37142. generatedColumn: mapping.generatedColumn +
  37143. (section.generatedOffset.generatedLine === mapping.generatedLine
  37144. ? section.generatedOffset.generatedColumn - 1
  37145. : 0),
  37146. originalLine: mapping.originalLine,
  37147. originalColumn: mapping.originalColumn,
  37148. name: name
  37149. };
  37150. this.__generatedMappings.push(adjustedMapping);
  37151. if (typeof adjustedMapping.originalLine === 'number') {
  37152. this.__originalMappings.push(adjustedMapping);
  37153. }
  37154. }
  37155. }
  37156. quickSort$3(this.__generatedMappings, util$1.compareByGeneratedPositionsDeflated);
  37157. quickSort$3(this.__originalMappings, util$1.compareByOriginalPositions);
  37158. };
  37159. var IndexedSourceMapConsumer_1$1 = IndexedSourceMapConsumer$1;
  37160. var sourceMapConsumer$1 = {
  37161. SourceMapConsumer: SourceMapConsumer_1$1,
  37162. BasicSourceMapConsumer: BasicSourceMapConsumer_1$1,
  37163. IndexedSourceMapConsumer: IndexedSourceMapConsumer_1$1
  37164. };
  37165. /* -*- Mode: js; js-indent-level: 2; -*- */
  37166. /*
  37167. * Copyright 2011 Mozilla Foundation and contributors
  37168. * Licensed under the New BSD license. See LICENSE or:
  37169. * http://opensource.org/licenses/BSD-3-Clause
  37170. */
  37171. var SourceMapGenerator$4 = sourceMapGenerator$1.SourceMapGenerator;
  37172. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  37173. // operating systems these days (capturing the result).
  37174. var REGEX_NEWLINE$1 = /(\r?\n)/;
  37175. // Newline character code for charCodeAt() comparisons
  37176. var NEWLINE_CODE$1 = 10;
  37177. // Private symbol for identifying `SourceNode`s when multiple versions of
  37178. // the source-map library are loaded. This MUST NOT CHANGE across
  37179. // versions!
  37180. var isSourceNode$1 = "$$$isSourceNode$$$";
  37181. /**
  37182. * SourceNodes provide a way to abstract over interpolating/concatenating
  37183. * snippets of generated JavaScript source code while maintaining the line and
  37184. * column information associated with the original source code.
  37185. *
  37186. * @param aLine The original line number.
  37187. * @param aColumn The original column number.
  37188. * @param aSource The original source's filename.
  37189. * @param aChunks Optional. An array of strings which are snippets of
  37190. * generated JS, or other SourceNodes.
  37191. * @param aName The original identifier.
  37192. */
  37193. function SourceNode$2(aLine, aColumn, aSource, aChunks, aName) {
  37194. this.children = [];
  37195. this.sourceContents = {};
  37196. this.line = aLine == null ? null : aLine;
  37197. this.column = aColumn == null ? null : aColumn;
  37198. this.source = aSource == null ? null : aSource;
  37199. this.name = aName == null ? null : aName;
  37200. this[isSourceNode$1] = true;
  37201. if (aChunks != null) this.add(aChunks);
  37202. }
  37203. /**
  37204. * Creates a SourceNode from generated code and a SourceMapConsumer.
  37205. *
  37206. * @param aGeneratedCode The generated code
  37207. * @param aSourceMapConsumer The SourceMap for the generated code
  37208. * @param aRelativePath Optional. The path that relative sources in the
  37209. * SourceMapConsumer should be relative to.
  37210. */
  37211. SourceNode$2.fromStringWithSourceMap =
  37212. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  37213. // The SourceNode we want to fill with the generated code
  37214. // and the SourceMap
  37215. var node = new SourceNode$2();
  37216. // All even indices of this array are one line of the generated code,
  37217. // while all odd indices are the newlines between two adjacent lines
  37218. // (since `REGEX_NEWLINE` captures its match).
  37219. // Processed fragments are accessed by calling `shiftNextLine`.
  37220. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE$1);
  37221. var remainingLinesIndex = 0;
  37222. var shiftNextLine = function() {
  37223. var lineContents = getNextLine();
  37224. // The last line of a file might not have a newline.
  37225. var newLine = getNextLine() || "";
  37226. return lineContents + newLine;
  37227. function getNextLine() {
  37228. return remainingLinesIndex < remainingLines.length ?
  37229. remainingLines[remainingLinesIndex++] : undefined;
  37230. }
  37231. };
  37232. // We need to remember the position of "remainingLines"
  37233. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  37234. // The generate SourceNodes we need a code range.
  37235. // To extract it current and last mapping is used.
  37236. // Here we store the last mapping.
  37237. var lastMapping = null;
  37238. aSourceMapConsumer.eachMapping(function (mapping) {
  37239. if (lastMapping !== null) {
  37240. // We add the code from "lastMapping" to "mapping":
  37241. // First check if there is a new line in between.
  37242. if (lastGeneratedLine < mapping.generatedLine) {
  37243. // Associate first line with "lastMapping"
  37244. addMappingWithCode(lastMapping, shiftNextLine());
  37245. lastGeneratedLine++;
  37246. lastGeneratedColumn = 0;
  37247. // The remaining code is added without mapping
  37248. } else {
  37249. // There is no new line in between.
  37250. // Associate the code between "lastGeneratedColumn" and
  37251. // "mapping.generatedColumn" with "lastMapping"
  37252. var nextLine = remainingLines[remainingLinesIndex] || '';
  37253. var code = nextLine.substr(0, mapping.generatedColumn -
  37254. lastGeneratedColumn);
  37255. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  37256. lastGeneratedColumn);
  37257. lastGeneratedColumn = mapping.generatedColumn;
  37258. addMappingWithCode(lastMapping, code);
  37259. // No more remaining code, continue
  37260. lastMapping = mapping;
  37261. return;
  37262. }
  37263. }
  37264. // We add the generated code until the first mapping
  37265. // to the SourceNode without any mapping.
  37266. // Each line is added as separate string.
  37267. while (lastGeneratedLine < mapping.generatedLine) {
  37268. node.add(shiftNextLine());
  37269. lastGeneratedLine++;
  37270. }
  37271. if (lastGeneratedColumn < mapping.generatedColumn) {
  37272. var nextLine = remainingLines[remainingLinesIndex] || '';
  37273. node.add(nextLine.substr(0, mapping.generatedColumn));
  37274. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  37275. lastGeneratedColumn = mapping.generatedColumn;
  37276. }
  37277. lastMapping = mapping;
  37278. }, this);
  37279. // We have processed all mappings.
  37280. if (remainingLinesIndex < remainingLines.length) {
  37281. if (lastMapping) {
  37282. // Associate the remaining code in the current line with "lastMapping"
  37283. addMappingWithCode(lastMapping, shiftNextLine());
  37284. }
  37285. // and add the remaining lines without any mapping
  37286. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  37287. }
  37288. // Copy sourcesContent into SourceNode
  37289. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  37290. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  37291. if (content != null) {
  37292. if (aRelativePath != null) {
  37293. sourceFile = util$1.join(aRelativePath, sourceFile);
  37294. }
  37295. node.setSourceContent(sourceFile, content);
  37296. }
  37297. });
  37298. return node;
  37299. function addMappingWithCode(mapping, code) {
  37300. if (mapping === null || mapping.source === undefined) {
  37301. node.add(code);
  37302. } else {
  37303. var source = aRelativePath
  37304. ? util$1.join(aRelativePath, mapping.source)
  37305. : mapping.source;
  37306. node.add(new SourceNode$2(mapping.originalLine,
  37307. mapping.originalColumn,
  37308. source,
  37309. code,
  37310. mapping.name));
  37311. }
  37312. }
  37313. };
  37314. /**
  37315. * Add a chunk of generated JS to this source node.
  37316. *
  37317. * @param aChunk A string snippet of generated JS code, another instance of
  37318. * SourceNode, or an array where each member is one of those things.
  37319. */
  37320. SourceNode$2.prototype.add = function SourceNode_add(aChunk) {
  37321. if (Array.isArray(aChunk)) {
  37322. aChunk.forEach(function (chunk) {
  37323. this.add(chunk);
  37324. }, this);
  37325. }
  37326. else if (aChunk[isSourceNode$1] || typeof aChunk === "string") {
  37327. if (aChunk) {
  37328. this.children.push(aChunk);
  37329. }
  37330. }
  37331. else {
  37332. throw new TypeError(
  37333. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  37334. );
  37335. }
  37336. return this;
  37337. };
  37338. /**
  37339. * Add a chunk of generated JS to the beginning of this source node.
  37340. *
  37341. * @param aChunk A string snippet of generated JS code, another instance of
  37342. * SourceNode, or an array where each member is one of those things.
  37343. */
  37344. SourceNode$2.prototype.prepend = function SourceNode_prepend(aChunk) {
  37345. if (Array.isArray(aChunk)) {
  37346. for (var i = aChunk.length-1; i >= 0; i--) {
  37347. this.prepend(aChunk[i]);
  37348. }
  37349. }
  37350. else if (aChunk[isSourceNode$1] || typeof aChunk === "string") {
  37351. this.children.unshift(aChunk);
  37352. }
  37353. else {
  37354. throw new TypeError(
  37355. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  37356. );
  37357. }
  37358. return this;
  37359. };
  37360. /**
  37361. * Walk over the tree of JS snippets in this node and its children. The
  37362. * walking function is called once for each snippet of JS and is passed that
  37363. * snippet and the its original associated source's line/column location.
  37364. *
  37365. * @param aFn The traversal function.
  37366. */
  37367. SourceNode$2.prototype.walk = function SourceNode_walk(aFn) {
  37368. var chunk;
  37369. for (var i = 0, len = this.children.length; i < len; i++) {
  37370. chunk = this.children[i];
  37371. if (chunk[isSourceNode$1]) {
  37372. chunk.walk(aFn);
  37373. }
  37374. else {
  37375. if (chunk !== '') {
  37376. aFn(chunk, { source: this.source,
  37377. line: this.line,
  37378. column: this.column,
  37379. name: this.name });
  37380. }
  37381. }
  37382. }
  37383. };
  37384. /**
  37385. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  37386. * each of `this.children`.
  37387. *
  37388. * @param aSep The separator.
  37389. */
  37390. SourceNode$2.prototype.join = function SourceNode_join(aSep) {
  37391. var newChildren;
  37392. var i;
  37393. var len = this.children.length;
  37394. if (len > 0) {
  37395. newChildren = [];
  37396. for (i = 0; i < len-1; i++) {
  37397. newChildren.push(this.children[i]);
  37398. newChildren.push(aSep);
  37399. }
  37400. newChildren.push(this.children[i]);
  37401. this.children = newChildren;
  37402. }
  37403. return this;
  37404. };
  37405. /**
  37406. * Call String.prototype.replace on the very right-most source snippet. Useful
  37407. * for trimming whitespace from the end of a source node, etc.
  37408. *
  37409. * @param aPattern The pattern to replace.
  37410. * @param aReplacement The thing to replace the pattern with.
  37411. */
  37412. SourceNode$2.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  37413. var lastChild = this.children[this.children.length - 1];
  37414. if (lastChild[isSourceNode$1]) {
  37415. lastChild.replaceRight(aPattern, aReplacement);
  37416. }
  37417. else if (typeof lastChild === 'string') {
  37418. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  37419. }
  37420. else {
  37421. this.children.push(''.replace(aPattern, aReplacement));
  37422. }
  37423. return this;
  37424. };
  37425. /**
  37426. * Set the source content for a source file. This will be added to the SourceMapGenerator
  37427. * in the sourcesContent field.
  37428. *
  37429. * @param aSourceFile The filename of the source file
  37430. * @param aSourceContent The content of the source file
  37431. */
  37432. SourceNode$2.prototype.setSourceContent =
  37433. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  37434. this.sourceContents[util$1.toSetString(aSourceFile)] = aSourceContent;
  37435. };
  37436. /**
  37437. * Walk over the tree of SourceNodes. The walking function is called for each
  37438. * source file content and is passed the filename and source content.
  37439. *
  37440. * @param aFn The traversal function.
  37441. */
  37442. SourceNode$2.prototype.walkSourceContents =
  37443. function SourceNode_walkSourceContents(aFn) {
  37444. for (var i = 0, len = this.children.length; i < len; i++) {
  37445. if (this.children[i][isSourceNode$1]) {
  37446. this.children[i].walkSourceContents(aFn);
  37447. }
  37448. }
  37449. var sources = Object.keys(this.sourceContents);
  37450. for (var i = 0, len = sources.length; i < len; i++) {
  37451. aFn(util$1.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  37452. }
  37453. };
  37454. /**
  37455. * Return the string representation of this source node. Walks over the tree
  37456. * and concatenates all the various snippets together to one string.
  37457. */
  37458. SourceNode$2.prototype.toString = function SourceNode_toString() {
  37459. var str = "";
  37460. this.walk(function (chunk) {
  37461. str += chunk;
  37462. });
  37463. return str;
  37464. };
  37465. /**
  37466. * Returns the string representation of this source node along with a source
  37467. * map.
  37468. */
  37469. SourceNode$2.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  37470. var generated = {
  37471. code: "",
  37472. line: 1,
  37473. column: 0
  37474. };
  37475. var map = new SourceMapGenerator$4(aArgs);
  37476. var sourceMappingActive = false;
  37477. var lastOriginalSource = null;
  37478. var lastOriginalLine = null;
  37479. var lastOriginalColumn = null;
  37480. var lastOriginalName = null;
  37481. this.walk(function (chunk, original) {
  37482. generated.code += chunk;
  37483. if (original.source !== null
  37484. && original.line !== null
  37485. && original.column !== null) {
  37486. if(lastOriginalSource !== original.source
  37487. || lastOriginalLine !== original.line
  37488. || lastOriginalColumn !== original.column
  37489. || lastOriginalName !== original.name) {
  37490. map.addMapping({
  37491. source: original.source,
  37492. original: {
  37493. line: original.line,
  37494. column: original.column
  37495. },
  37496. generated: {
  37497. line: generated.line,
  37498. column: generated.column
  37499. },
  37500. name: original.name
  37501. });
  37502. }
  37503. lastOriginalSource = original.source;
  37504. lastOriginalLine = original.line;
  37505. lastOriginalColumn = original.column;
  37506. lastOriginalName = original.name;
  37507. sourceMappingActive = true;
  37508. } else if (sourceMappingActive) {
  37509. map.addMapping({
  37510. generated: {
  37511. line: generated.line,
  37512. column: generated.column
  37513. }
  37514. });
  37515. lastOriginalSource = null;
  37516. sourceMappingActive = false;
  37517. }
  37518. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  37519. if (chunk.charCodeAt(idx) === NEWLINE_CODE$1) {
  37520. generated.line++;
  37521. generated.column = 0;
  37522. // Mappings end at eol
  37523. if (idx + 1 === length) {
  37524. lastOriginalSource = null;
  37525. sourceMappingActive = false;
  37526. } else if (sourceMappingActive) {
  37527. map.addMapping({
  37528. source: original.source,
  37529. original: {
  37530. line: original.line,
  37531. column: original.column
  37532. },
  37533. generated: {
  37534. line: generated.line,
  37535. column: generated.column
  37536. },
  37537. name: original.name
  37538. });
  37539. }
  37540. } else {
  37541. generated.column++;
  37542. }
  37543. }
  37544. });
  37545. this.walkSourceContents(function (sourceFile, sourceContent) {
  37546. map.setSourceContent(sourceFile, sourceContent);
  37547. });
  37548. return { code: generated.code, map: map };
  37549. };
  37550. var SourceNode_1$1 = SourceNode$2;
  37551. var sourceNode$1 = {
  37552. SourceNode: SourceNode_1$1
  37553. };
  37554. /*
  37555. * Copyright 2009-2011 Mozilla Foundation and contributors
  37556. * Licensed under the New BSD license. See LICENSE.txt or:
  37557. * http://opensource.org/licenses/BSD-3-Clause
  37558. */
  37559. var SourceMapGenerator$5 = sourceMapGenerator$1.SourceMapGenerator;
  37560. var SourceMapConsumer$3 = sourceMapConsumer$1.SourceMapConsumer;
  37561. var SourceNode$3 = sourceNode$1.SourceNode;
  37562. var sourceMap$1 = {
  37563. SourceMapGenerator: SourceMapGenerator$5,
  37564. SourceMapConsumer: SourceMapConsumer$3,
  37565. SourceNode: SourceNode$3
  37566. };
  37567. let urlAlphabet =
  37568. 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
  37569. let customAlphabet = (alphabet, size) => {
  37570. return () => {
  37571. let id = '';
  37572. let i = size;
  37573. while (i--) {
  37574. id += alphabet[(Math.random() * alphabet.length) | 0];
  37575. }
  37576. return id
  37577. }
  37578. };
  37579. let nanoid = (size = 21) => {
  37580. let id = '';
  37581. let i = size;
  37582. while (i--) {
  37583. id += urlAlphabet[(Math.random() * 64) | 0];
  37584. }
  37585. return id
  37586. };
  37587. var nonSecure = { nanoid, customAlphabet };
  37588. let { SourceMapConsumer: SourceMapConsumer$4, SourceMapGenerator: SourceMapGenerator$6 } = sourceMap$1;
  37589. let { existsSync, readFileSync } = _fs;
  37590. let { dirname: dirname$1, join: join$1 } = _path;
  37591. function fromBase64(str) {
  37592. if (Buffer) {
  37593. return Buffer.from(str, 'base64').toString()
  37594. } else {
  37595. /* c8 ignore next 2 */
  37596. return window.atob(str)
  37597. }
  37598. }
  37599. class PreviousMap {
  37600. constructor(css, opts) {
  37601. if (opts.map === false) return
  37602. this.loadAnnotation(css);
  37603. this.inline = this.startWith(this.annotation, 'data:');
  37604. let prev = opts.map ? opts.map.prev : undefined;
  37605. let text = this.loadMap(opts.from, prev);
  37606. if (!this.mapFile && opts.from) {
  37607. this.mapFile = opts.from;
  37608. }
  37609. if (this.mapFile) this.root = dirname$1(this.mapFile);
  37610. if (text) this.text = text;
  37611. }
  37612. consumer() {
  37613. if (!this.consumerCache) {
  37614. this.consumerCache = new SourceMapConsumer$4(this.text);
  37615. }
  37616. return this.consumerCache
  37617. }
  37618. withContent() {
  37619. return !!(
  37620. this.consumer().sourcesContent &&
  37621. this.consumer().sourcesContent.length > 0
  37622. )
  37623. }
  37624. startWith(string, start) {
  37625. if (!string) return false
  37626. return string.substr(0, start.length) === start
  37627. }
  37628. getAnnotationURL(sourceMapString) {
  37629. return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, '').trim()
  37630. }
  37631. loadAnnotation(css) {
  37632. let comments = css.match(/\/\*\s*# sourceMappingURL=/gm);
  37633. if (!comments) return
  37634. // sourceMappingURLs from comments, strings, etc.
  37635. let start = css.lastIndexOf(comments.pop());
  37636. let end = css.indexOf('*/', start);
  37637. if (start > -1 && end > -1) {
  37638. // Locate the last sourceMappingURL to avoid pickin
  37639. this.annotation = this.getAnnotationURL(css.substring(start, end));
  37640. }
  37641. }
  37642. decodeInline(text) {
  37643. let baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/;
  37644. let baseUri = /^data:application\/json;base64,/;
  37645. let charsetUri = /^data:application\/json;charset=utf-?8,/;
  37646. let uri = /^data:application\/json,/;
  37647. if (charsetUri.test(text) || uri.test(text)) {
  37648. return decodeURIComponent(text.substr(RegExp.lastMatch.length))
  37649. }
  37650. if (baseCharsetUri.test(text) || baseUri.test(text)) {
  37651. return fromBase64(text.substr(RegExp.lastMatch.length))
  37652. }
  37653. let encoding = text.match(/data:application\/json;([^,]+),/)[1];
  37654. throw new Error('Unsupported source map encoding ' + encoding)
  37655. }
  37656. loadFile(path) {
  37657. this.root = dirname$1(path);
  37658. if (existsSync(path)) {
  37659. this.mapFile = path;
  37660. return readFileSync(path, 'utf-8').toString().trim()
  37661. }
  37662. }
  37663. loadMap(file, prev) {
  37664. if (prev === false) return false
  37665. if (prev) {
  37666. if (typeof prev === 'string') {
  37667. return prev
  37668. } else if (typeof prev === 'function') {
  37669. let prevPath = prev(file);
  37670. if (prevPath) {
  37671. let map = this.loadFile(prevPath);
  37672. if (!map) {
  37673. throw new Error(
  37674. 'Unable to load previous source map: ' + prevPath.toString()
  37675. )
  37676. }
  37677. return map
  37678. }
  37679. } else if (prev instanceof SourceMapConsumer$4) {
  37680. return SourceMapGenerator$6.fromSourceMap(prev).toString()
  37681. } else if (prev instanceof SourceMapGenerator$6) {
  37682. return prev.toString()
  37683. } else if (this.isMap(prev)) {
  37684. return JSON.stringify(prev)
  37685. } else {
  37686. throw new Error(
  37687. 'Unsupported previous source map format: ' + prev.toString()
  37688. )
  37689. }
  37690. } else if (this.inline) {
  37691. return this.decodeInline(this.annotation)
  37692. } else if (this.annotation) {
  37693. let map = this.annotation;
  37694. if (file) map = join$1(dirname$1(file), map);
  37695. return this.loadFile(map)
  37696. }
  37697. }
  37698. isMap(map) {
  37699. if (typeof map !== 'object') return false
  37700. return (
  37701. typeof map.mappings === 'string' ||
  37702. typeof map._mappings === 'string' ||
  37703. Array.isArray(map.sections)
  37704. )
  37705. }
  37706. }
  37707. var previousMap = PreviousMap;
  37708. PreviousMap.default = PreviousMap;
  37709. var require$$2 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_url$1);
  37710. let { SourceMapConsumer: SourceMapConsumer$5, SourceMapGenerator: SourceMapGenerator$7 } = sourceMap$1;
  37711. let { fileURLToPath, pathToFileURL } = require$$2;
  37712. let { resolve: resolve$1, isAbsolute: isAbsolute$1 } = _path;
  37713. let { nanoid: nanoid$1 } = nonSecure;
  37714. let fromOffsetCache = Symbol('fromOffsetCache');
  37715. let sourceMapAvailable = Boolean(SourceMapConsumer$5 && SourceMapGenerator$7);
  37716. let pathAvailable = Boolean(resolve$1 && isAbsolute$1);
  37717. class Input$1 {
  37718. constructor(css, opts = {}) {
  37719. if (
  37720. css === null ||
  37721. typeof css === 'undefined' ||
  37722. (typeof css === 'object' && !css.toString)
  37723. ) {
  37724. throw new Error(`PostCSS received ${css} instead of CSS string`)
  37725. }
  37726. this.css = css.toString();
  37727. if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') {
  37728. this.hasBOM = true;
  37729. this.css = this.css.slice(1);
  37730. } else {
  37731. this.hasBOM = false;
  37732. }
  37733. if (opts.from) {
  37734. if (
  37735. !pathAvailable ||
  37736. /^\w+:\/\//.test(opts.from) ||
  37737. isAbsolute$1(opts.from)
  37738. ) {
  37739. this.file = opts.from;
  37740. } else {
  37741. this.file = resolve$1(opts.from);
  37742. }
  37743. }
  37744. if (pathAvailable && sourceMapAvailable) {
  37745. let map = new previousMap(this.css, opts);
  37746. if (map.text) {
  37747. this.map = map;
  37748. let file = map.consumer().file;
  37749. if (!this.file && file) this.file = this.mapResolve(file);
  37750. }
  37751. }
  37752. if (!this.file) {
  37753. this.id = '<input css ' + nanoid$1(6) + '>';
  37754. }
  37755. if (this.map) this.map.file = this.from;
  37756. }
  37757. fromOffset(offset) {
  37758. let lastLine, lineToIndex;
  37759. if (!this[fromOffsetCache]) {
  37760. let lines = this.css.split('\n');
  37761. lineToIndex = new Array(lines.length);
  37762. let prevIndex = 0;
  37763. for (let i = 0, l = lines.length; i < l; i++) {
  37764. lineToIndex[i] = prevIndex;
  37765. prevIndex += lines[i].length + 1;
  37766. }
  37767. this[fromOffsetCache] = lineToIndex;
  37768. } else {
  37769. lineToIndex = this[fromOffsetCache];
  37770. }
  37771. lastLine = lineToIndex[lineToIndex.length - 1];
  37772. let min = 0;
  37773. if (offset >= lastLine) {
  37774. min = lineToIndex.length - 1;
  37775. } else {
  37776. let max = lineToIndex.length - 2;
  37777. let mid;
  37778. while (min < max) {
  37779. mid = min + ((max - min) >> 1);
  37780. if (offset < lineToIndex[mid]) {
  37781. max = mid - 1;
  37782. } else if (offset >= lineToIndex[mid + 1]) {
  37783. min = mid + 1;
  37784. } else {
  37785. min = mid;
  37786. break
  37787. }
  37788. }
  37789. }
  37790. return {
  37791. line: min + 1,
  37792. col: offset - lineToIndex[min] + 1
  37793. }
  37794. }
  37795. error(message, line, column, opts = {}) {
  37796. let result, endLine, endColumn;
  37797. if (line && typeof line === 'object') {
  37798. let start = line;
  37799. let end = column;
  37800. if (typeof line.offset === 'number') {
  37801. let pos = this.fromOffset(start.offset);
  37802. line = pos.line;
  37803. column = pos.col;
  37804. } else {
  37805. line = start.line;
  37806. column = start.column;
  37807. }
  37808. if (typeof end.offset === 'number') {
  37809. let pos = this.fromOffset(end.offset);
  37810. endLine = pos.line;
  37811. endColumn = pos.col;
  37812. } else {
  37813. endLine = end.line;
  37814. endColumn = end.column;
  37815. }
  37816. } else if (!column) {
  37817. let pos = this.fromOffset(line);
  37818. line = pos.line;
  37819. column = pos.col;
  37820. }
  37821. let origin = this.origin(line, column, endLine, endColumn);
  37822. if (origin) {
  37823. result = new cssSyntaxError(
  37824. message,
  37825. origin.endLine === undefined
  37826. ? origin.line
  37827. : { line: origin.line, column: origin.column },
  37828. origin.endLine === undefined
  37829. ? origin.column
  37830. : { line: origin.endLine, column: origin.endColumn },
  37831. origin.source,
  37832. origin.file,
  37833. opts.plugin
  37834. );
  37835. } else {
  37836. result = new cssSyntaxError(
  37837. message,
  37838. endLine === undefined ? line : { line, column },
  37839. endLine === undefined ? column : { line: endLine, column: endColumn },
  37840. this.css,
  37841. this.file,
  37842. opts.plugin
  37843. );
  37844. }
  37845. result.input = { line, column, endLine, endColumn, source: this.css };
  37846. if (this.file) {
  37847. if (pathToFileURL) {
  37848. result.input.url = pathToFileURL(this.file).toString();
  37849. }
  37850. result.input.file = this.file;
  37851. }
  37852. return result
  37853. }
  37854. origin(line, column, endLine, endColumn) {
  37855. if (!this.map) return false
  37856. let consumer = this.map.consumer();
  37857. let from = consumer.originalPositionFor({ line, column });
  37858. if (!from.source) return false
  37859. let to;
  37860. if (typeof endLine === 'number') {
  37861. to = consumer.originalPositionFor({ line: endLine, column: endColumn });
  37862. }
  37863. let fromUrl;
  37864. if (isAbsolute$1(from.source)) {
  37865. fromUrl = pathToFileURL(from.source);
  37866. } else {
  37867. fromUrl = new URL(
  37868. from.source,
  37869. this.map.consumer().sourceRoot || pathToFileURL(this.map.mapFile)
  37870. );
  37871. }
  37872. let result = {
  37873. url: fromUrl.toString(),
  37874. line: from.line,
  37875. column: from.column,
  37876. endLine: to && to.line,
  37877. endColumn: to && to.column
  37878. };
  37879. if (fromUrl.protocol === 'file:') {
  37880. if (fileURLToPath) {
  37881. result.file = fileURLToPath(fromUrl);
  37882. } else {
  37883. /* c8 ignore next 2 */
  37884. throw new Error(`file: protocol is not available in this PostCSS build`)
  37885. }
  37886. }
  37887. let source = consumer.sourceContentFor(from.source);
  37888. if (source) result.source = source;
  37889. return result
  37890. }
  37891. mapResolve(file) {
  37892. if (/^\w+:\/\//.test(file)) {
  37893. return file
  37894. }
  37895. return resolve$1(this.map.consumer().sourceRoot || this.map.root || '.', file)
  37896. }
  37897. get from() {
  37898. return this.file || this.id
  37899. }
  37900. toJSON() {
  37901. let json = {};
  37902. for (let name of ['hasBOM', 'css', 'file', 'id']) {
  37903. if (this[name] != null) {
  37904. json[name] = this[name];
  37905. }
  37906. }
  37907. if (this.map) {
  37908. json.map = { ...this.map };
  37909. if (json.map.consumerCache) {
  37910. json.map.consumerCache = undefined;
  37911. }
  37912. }
  37913. return json
  37914. }
  37915. }
  37916. var input = Input$1;
  37917. Input$1.default = Input$1;
  37918. if (terminalHighlight_1 && terminalHighlight_1.registerInput) {
  37919. terminalHighlight_1.registerInput(Input$1);
  37920. }
  37921. let { SourceMapConsumer: SourceMapConsumer$6, SourceMapGenerator: SourceMapGenerator$8 } = sourceMap$1;
  37922. let { dirname: dirname$2, resolve: resolve$2, relative: relative$1, sep: sep$1 } = _path;
  37923. let { pathToFileURL: pathToFileURL$1 } = require$$2;
  37924. let sourceMapAvailable$1 = Boolean(SourceMapConsumer$6 && SourceMapGenerator$8);
  37925. let pathAvailable$1 = Boolean(dirname$2 && resolve$2 && relative$1 && sep$1);
  37926. class MapGenerator {
  37927. constructor(stringify, root, opts, cssString) {
  37928. this.stringify = stringify;
  37929. this.mapOpts = opts.map || {};
  37930. this.root = root;
  37931. this.opts = opts;
  37932. this.css = cssString;
  37933. }
  37934. isMap() {
  37935. if (typeof this.opts.map !== 'undefined') {
  37936. return !!this.opts.map
  37937. }
  37938. return this.previous().length > 0
  37939. }
  37940. previous() {
  37941. if (!this.previousMaps) {
  37942. this.previousMaps = [];
  37943. if (this.root) {
  37944. this.root.walk(node => {
  37945. if (node.source && node.source.input.map) {
  37946. let map = node.source.input.map;
  37947. if (!this.previousMaps.includes(map)) {
  37948. this.previousMaps.push(map);
  37949. }
  37950. }
  37951. });
  37952. } else {
  37953. let input$1 = new input(this.css, this.opts);
  37954. if (input$1.map) this.previousMaps.push(input$1.map);
  37955. }
  37956. }
  37957. return this.previousMaps
  37958. }
  37959. isInline() {
  37960. if (typeof this.mapOpts.inline !== 'undefined') {
  37961. return this.mapOpts.inline
  37962. }
  37963. let annotation = this.mapOpts.annotation;
  37964. if (typeof annotation !== 'undefined' && annotation !== true) {
  37965. return false
  37966. }
  37967. if (this.previous().length) {
  37968. return this.previous().some(i => i.inline)
  37969. }
  37970. return true
  37971. }
  37972. isSourcesContent() {
  37973. if (typeof this.mapOpts.sourcesContent !== 'undefined') {
  37974. return this.mapOpts.sourcesContent
  37975. }
  37976. if (this.previous().length) {
  37977. return this.previous().some(i => i.withContent())
  37978. }
  37979. return true
  37980. }
  37981. clearAnnotation() {
  37982. if (this.mapOpts.annotation === false) return
  37983. if (this.root) {
  37984. let node;
  37985. for (let i = this.root.nodes.length - 1; i >= 0; i--) {
  37986. node = this.root.nodes[i];
  37987. if (node.type !== 'comment') continue
  37988. if (node.text.indexOf('# sourceMappingURL=') === 0) {
  37989. this.root.removeChild(i);
  37990. }
  37991. }
  37992. } else if (this.css) {
  37993. this.css = this.css.replace(/(\n)?\/\*#[\S\s]*?\*\/$/gm, '');
  37994. }
  37995. }
  37996. setSourcesContent() {
  37997. let already = {};
  37998. if (this.root) {
  37999. this.root.walk(node => {
  38000. if (node.source) {
  38001. let from = node.source.input.from;
  38002. if (from && !already[from]) {
  38003. already[from] = true;
  38004. this.map.setSourceContent(
  38005. this.toUrl(this.path(from)),
  38006. node.source.input.css
  38007. );
  38008. }
  38009. }
  38010. });
  38011. } else if (this.css) {
  38012. let from = this.opts.from
  38013. ? this.toUrl(this.path(this.opts.from))
  38014. : '<no source>';
  38015. this.map.setSourceContent(from, this.css);
  38016. }
  38017. }
  38018. applyPrevMaps() {
  38019. for (let prev of this.previous()) {
  38020. let from = this.toUrl(this.path(prev.file));
  38021. let root = prev.root || dirname$2(prev.file);
  38022. let map;
  38023. if (this.mapOpts.sourcesContent === false) {
  38024. map = new SourceMapConsumer$6(prev.text);
  38025. if (map.sourcesContent) {
  38026. map.sourcesContent = map.sourcesContent.map(() => null);
  38027. }
  38028. } else {
  38029. map = prev.consumer();
  38030. }
  38031. this.map.applySourceMap(map, from, this.toUrl(this.path(root)));
  38032. }
  38033. }
  38034. isAnnotation() {
  38035. if (this.isInline()) {
  38036. return true
  38037. }
  38038. if (typeof this.mapOpts.annotation !== 'undefined') {
  38039. return this.mapOpts.annotation
  38040. }
  38041. if (this.previous().length) {
  38042. return this.previous().some(i => i.annotation)
  38043. }
  38044. return true
  38045. }
  38046. toBase64(str) {
  38047. if (Buffer) {
  38048. return Buffer.from(str).toString('base64')
  38049. } else {
  38050. return window.btoa(unescape(encodeURIComponent(str)))
  38051. }
  38052. }
  38053. addAnnotation() {
  38054. let content;
  38055. if (this.isInline()) {
  38056. content =
  38057. 'data:application/json;base64,' + this.toBase64(this.map.toString());
  38058. } else if (typeof this.mapOpts.annotation === 'string') {
  38059. content = this.mapOpts.annotation;
  38060. } else if (typeof this.mapOpts.annotation === 'function') {
  38061. content = this.mapOpts.annotation(this.opts.to, this.root);
  38062. } else {
  38063. content = this.outputFile() + '.map';
  38064. }
  38065. let eol = '\n';
  38066. if (this.css.includes('\r\n')) eol = '\r\n';
  38067. this.css += eol + '/*# sourceMappingURL=' + content + ' */';
  38068. }
  38069. outputFile() {
  38070. if (this.opts.to) {
  38071. return this.path(this.opts.to)
  38072. } else if (this.opts.from) {
  38073. return this.path(this.opts.from)
  38074. } else {
  38075. return 'to.css'
  38076. }
  38077. }
  38078. generateMap() {
  38079. if (this.root) {
  38080. this.generateString();
  38081. } else if (this.previous().length === 1) {
  38082. let prev = this.previous()[0].consumer();
  38083. prev.file = this.outputFile();
  38084. this.map = SourceMapGenerator$8.fromSourceMap(prev);
  38085. } else {
  38086. this.map = new SourceMapGenerator$8({ file: this.outputFile() });
  38087. this.map.addMapping({
  38088. source: this.opts.from
  38089. ? this.toUrl(this.path(this.opts.from))
  38090. : '<no source>',
  38091. generated: { line: 1, column: 0 },
  38092. original: { line: 1, column: 0 }
  38093. });
  38094. }
  38095. if (this.isSourcesContent()) this.setSourcesContent();
  38096. if (this.root && this.previous().length > 0) this.applyPrevMaps();
  38097. if (this.isAnnotation()) this.addAnnotation();
  38098. if (this.isInline()) {
  38099. return [this.css]
  38100. } else {
  38101. return [this.css, this.map]
  38102. }
  38103. }
  38104. path(file) {
  38105. if (file.indexOf('<') === 0) return file
  38106. if (/^\w+:\/\//.test(file)) return file
  38107. if (this.mapOpts.absolute) return file
  38108. let from = this.opts.to ? dirname$2(this.opts.to) : '.';
  38109. if (typeof this.mapOpts.annotation === 'string') {
  38110. from = dirname$2(resolve$2(from, this.mapOpts.annotation));
  38111. }
  38112. file = relative$1(from, file);
  38113. return file
  38114. }
  38115. toUrl(path) {
  38116. if (sep$1 === '\\') {
  38117. path = path.replace(/\\/g, '/');
  38118. }
  38119. return encodeURI(path).replace(/[#?]/g, encodeURIComponent)
  38120. }
  38121. sourcePath(node) {
  38122. if (this.mapOpts.from) {
  38123. return this.toUrl(this.mapOpts.from)
  38124. } else if (this.mapOpts.absolute) {
  38125. if (pathToFileURL$1) {
  38126. return pathToFileURL$1(node.source.input.from).toString()
  38127. } else {
  38128. throw new Error(
  38129. '`map.absolute` option is not available in this PostCSS build'
  38130. )
  38131. }
  38132. } else {
  38133. return this.toUrl(this.path(node.source.input.from))
  38134. }
  38135. }
  38136. generateString() {
  38137. this.css = '';
  38138. this.map = new SourceMapGenerator$8({ file: this.outputFile() });
  38139. let line = 1;
  38140. let column = 1;
  38141. let noSource = '<no source>';
  38142. let mapping = {
  38143. source: '',
  38144. generated: { line: 0, column: 0 },
  38145. original: { line: 0, column: 0 }
  38146. };
  38147. let lines, last;
  38148. this.stringify(this.root, (str, node, type) => {
  38149. this.css += str;
  38150. if (node && type !== 'end') {
  38151. mapping.generated.line = line;
  38152. mapping.generated.column = column - 1;
  38153. if (node.source && node.source.start) {
  38154. mapping.source = this.sourcePath(node);
  38155. mapping.original.line = node.source.start.line;
  38156. mapping.original.column = node.source.start.column - 1;
  38157. this.map.addMapping(mapping);
  38158. } else {
  38159. mapping.source = noSource;
  38160. mapping.original.line = 1;
  38161. mapping.original.column = 0;
  38162. this.map.addMapping(mapping);
  38163. }
  38164. }
  38165. lines = str.match(/\n/g);
  38166. if (lines) {
  38167. line += lines.length;
  38168. last = str.lastIndexOf('\n');
  38169. column = str.length - last;
  38170. } else {
  38171. column += str.length;
  38172. }
  38173. if (node && type !== 'start') {
  38174. let p = node.parent || { raws: {} };
  38175. if (node.type !== 'decl' || node !== p.last || p.raws.semicolon) {
  38176. if (node.source && node.source.end) {
  38177. mapping.source = this.sourcePath(node);
  38178. mapping.original.line = node.source.end.line;
  38179. mapping.original.column = node.source.end.column - 1;
  38180. mapping.generated.line = line;
  38181. mapping.generated.column = column - 2;
  38182. this.map.addMapping(mapping);
  38183. } else {
  38184. mapping.source = noSource;
  38185. mapping.original.line = 1;
  38186. mapping.original.column = 0;
  38187. mapping.generated.line = line;
  38188. mapping.generated.column = column - 1;
  38189. this.map.addMapping(mapping);
  38190. }
  38191. }
  38192. }
  38193. });
  38194. }
  38195. generate() {
  38196. this.clearAnnotation();
  38197. if (pathAvailable$1 && sourceMapAvailable$1 && this.isMap()) {
  38198. return this.generateMap()
  38199. } else {
  38200. let result = '';
  38201. this.stringify(this.root, i => {
  38202. result += i;
  38203. });
  38204. return [result]
  38205. }
  38206. }
  38207. }
  38208. var mapGenerator = MapGenerator;
  38209. class Comment extends node_1 {
  38210. constructor(defaults) {
  38211. super(defaults);
  38212. this.type = 'comment';
  38213. }
  38214. }
  38215. var comment = Comment;
  38216. Comment.default = Comment;
  38217. let { isClean: isClean$2, my: my$2 } = symbols;
  38218. let parse$5, Rule, AtRule;
  38219. function cleanSource(nodes) {
  38220. return nodes.map(i => {
  38221. if (i.nodes) i.nodes = cleanSource(i.nodes);
  38222. delete i.source;
  38223. return i
  38224. })
  38225. }
  38226. function markDirtyUp(node) {
  38227. node[isClean$2] = false;
  38228. if (node.proxyOf.nodes) {
  38229. for (let i of node.proxyOf.nodes) {
  38230. markDirtyUp(i);
  38231. }
  38232. }
  38233. }
  38234. class Container extends node_1 {
  38235. push(child) {
  38236. child.parent = this;
  38237. this.proxyOf.nodes.push(child);
  38238. return this
  38239. }
  38240. each(callback) {
  38241. if (!this.proxyOf.nodes) return undefined
  38242. let iterator = this.getIterator();
  38243. let index, result;
  38244. while (this.indexes[iterator] < this.proxyOf.nodes.length) {
  38245. index = this.indexes[iterator];
  38246. result = callback(this.proxyOf.nodes[index], index);
  38247. if (result === false) break
  38248. this.indexes[iterator] += 1;
  38249. }
  38250. delete this.indexes[iterator];
  38251. return result
  38252. }
  38253. walk(callback) {
  38254. return this.each((child, i) => {
  38255. let result;
  38256. try {
  38257. result = callback(child, i);
  38258. } catch (e) {
  38259. throw child.addToError(e)
  38260. }
  38261. if (result !== false && child.walk) {
  38262. result = child.walk(callback);
  38263. }
  38264. return result
  38265. })
  38266. }
  38267. walkDecls(prop, callback) {
  38268. if (!callback) {
  38269. callback = prop;
  38270. return this.walk((child, i) => {
  38271. if (child.type === 'decl') {
  38272. return callback(child, i)
  38273. }
  38274. })
  38275. }
  38276. if (prop instanceof RegExp) {
  38277. return this.walk((child, i) => {
  38278. if (child.type === 'decl' && prop.test(child.prop)) {
  38279. return callback(child, i)
  38280. }
  38281. })
  38282. }
  38283. return this.walk((child, i) => {
  38284. if (child.type === 'decl' && child.prop === prop) {
  38285. return callback(child, i)
  38286. }
  38287. })
  38288. }
  38289. walkRules(selector, callback) {
  38290. if (!callback) {
  38291. callback = selector;
  38292. return this.walk((child, i) => {
  38293. if (child.type === 'rule') {
  38294. return callback(child, i)
  38295. }
  38296. })
  38297. }
  38298. if (selector instanceof RegExp) {
  38299. return this.walk((child, i) => {
  38300. if (child.type === 'rule' && selector.test(child.selector)) {
  38301. return callback(child, i)
  38302. }
  38303. })
  38304. }
  38305. return this.walk((child, i) => {
  38306. if (child.type === 'rule' && child.selector === selector) {
  38307. return callback(child, i)
  38308. }
  38309. })
  38310. }
  38311. walkAtRules(name, callback) {
  38312. if (!callback) {
  38313. callback = name;
  38314. return this.walk((child, i) => {
  38315. if (child.type === 'atrule') {
  38316. return callback(child, i)
  38317. }
  38318. })
  38319. }
  38320. if (name instanceof RegExp) {
  38321. return this.walk((child, i) => {
  38322. if (child.type === 'atrule' && name.test(child.name)) {
  38323. return callback(child, i)
  38324. }
  38325. })
  38326. }
  38327. return this.walk((child, i) => {
  38328. if (child.type === 'atrule' && child.name === name) {
  38329. return callback(child, i)
  38330. }
  38331. })
  38332. }
  38333. walkComments(callback) {
  38334. return this.walk((child, i) => {
  38335. if (child.type === 'comment') {
  38336. return callback(child, i)
  38337. }
  38338. })
  38339. }
  38340. append(...children) {
  38341. for (let child of children) {
  38342. let nodes = this.normalize(child, this.last);
  38343. for (let node of nodes) this.proxyOf.nodes.push(node);
  38344. }
  38345. this.markDirty();
  38346. return this
  38347. }
  38348. prepend(...children) {
  38349. children = children.reverse();
  38350. for (let child of children) {
  38351. let nodes = this.normalize(child, this.first, 'prepend').reverse();
  38352. for (let node of nodes) this.proxyOf.nodes.unshift(node);
  38353. for (let id in this.indexes) {
  38354. this.indexes[id] = this.indexes[id] + nodes.length;
  38355. }
  38356. }
  38357. this.markDirty();
  38358. return this
  38359. }
  38360. cleanRaws(keepBetween) {
  38361. super.cleanRaws(keepBetween);
  38362. if (this.nodes) {
  38363. for (let node of this.nodes) node.cleanRaws(keepBetween);
  38364. }
  38365. }
  38366. insertBefore(exist, add) {
  38367. exist = this.index(exist);
  38368. let type = exist === 0 ? 'prepend' : false;
  38369. let nodes = this.normalize(add, this.proxyOf.nodes[exist], type).reverse();
  38370. for (let node of nodes) this.proxyOf.nodes.splice(exist, 0, node);
  38371. let index;
  38372. for (let id in this.indexes) {
  38373. index = this.indexes[id];
  38374. if (exist <= index) {
  38375. this.indexes[id] = index + nodes.length;
  38376. }
  38377. }
  38378. this.markDirty();
  38379. return this
  38380. }
  38381. insertAfter(exist, add) {
  38382. exist = this.index(exist);
  38383. let nodes = this.normalize(add, this.proxyOf.nodes[exist]).reverse();
  38384. for (let node of nodes) this.proxyOf.nodes.splice(exist + 1, 0, node);
  38385. let index;
  38386. for (let id in this.indexes) {
  38387. index = this.indexes[id];
  38388. if (exist < index) {
  38389. this.indexes[id] = index + nodes.length;
  38390. }
  38391. }
  38392. this.markDirty();
  38393. return this
  38394. }
  38395. removeChild(child) {
  38396. child = this.index(child);
  38397. this.proxyOf.nodes[child].parent = undefined;
  38398. this.proxyOf.nodes.splice(child, 1);
  38399. let index;
  38400. for (let id in this.indexes) {
  38401. index = this.indexes[id];
  38402. if (index >= child) {
  38403. this.indexes[id] = index - 1;
  38404. }
  38405. }
  38406. this.markDirty();
  38407. return this
  38408. }
  38409. removeAll() {
  38410. for (let node of this.proxyOf.nodes) node.parent = undefined;
  38411. this.proxyOf.nodes = [];
  38412. this.markDirty();
  38413. return this
  38414. }
  38415. replaceValues(pattern, opts, callback) {
  38416. if (!callback) {
  38417. callback = opts;
  38418. opts = {};
  38419. }
  38420. this.walkDecls(decl => {
  38421. if (opts.props && !opts.props.includes(decl.prop)) return
  38422. if (opts.fast && !decl.value.includes(opts.fast)) return
  38423. decl.value = decl.value.replace(pattern, callback);
  38424. });
  38425. this.markDirty();
  38426. return this
  38427. }
  38428. every(condition) {
  38429. return this.nodes.every(condition)
  38430. }
  38431. some(condition) {
  38432. return this.nodes.some(condition)
  38433. }
  38434. index(child) {
  38435. if (typeof child === 'number') return child
  38436. if (child.proxyOf) child = child.proxyOf;
  38437. return this.proxyOf.nodes.indexOf(child)
  38438. }
  38439. get first() {
  38440. if (!this.proxyOf.nodes) return undefined
  38441. return this.proxyOf.nodes[0]
  38442. }
  38443. get last() {
  38444. if (!this.proxyOf.nodes) return undefined
  38445. return this.proxyOf.nodes[this.proxyOf.nodes.length - 1]
  38446. }
  38447. normalize(nodes, sample) {
  38448. if (typeof nodes === 'string') {
  38449. nodes = cleanSource(parse$5(nodes).nodes);
  38450. } else if (Array.isArray(nodes)) {
  38451. nodes = nodes.slice(0);
  38452. for (let i of nodes) {
  38453. if (i.parent) i.parent.removeChild(i, 'ignore');
  38454. }
  38455. } else if (nodes.type === 'root' && this.type !== 'document') {
  38456. nodes = nodes.nodes.slice(0);
  38457. for (let i of nodes) {
  38458. if (i.parent) i.parent.removeChild(i, 'ignore');
  38459. }
  38460. } else if (nodes.type) {
  38461. nodes = [nodes];
  38462. } else if (nodes.prop) {
  38463. if (typeof nodes.value === 'undefined') {
  38464. throw new Error('Value field is missed in node creation')
  38465. } else if (typeof nodes.value !== 'string') {
  38466. nodes.value = String(nodes.value);
  38467. }
  38468. nodes = [new declaration(nodes)];
  38469. } else if (nodes.selector) {
  38470. nodes = [new Rule(nodes)];
  38471. } else if (nodes.name) {
  38472. nodes = [new AtRule(nodes)];
  38473. } else if (nodes.text) {
  38474. nodes = [new comment(nodes)];
  38475. } else {
  38476. throw new Error('Unknown node type in node creation')
  38477. }
  38478. let processed = nodes.map(i => {
  38479. /* c8 ignore next */
  38480. if (!i[my$2]) Container.rebuild(i);
  38481. i = i.proxyOf;
  38482. if (i.parent) i.parent.removeChild(i);
  38483. if (i[isClean$2]) markDirtyUp(i);
  38484. if (typeof i.raws.before === 'undefined') {
  38485. if (sample && typeof sample.raws.before !== 'undefined') {
  38486. i.raws.before = sample.raws.before.replace(/\S/g, '');
  38487. }
  38488. }
  38489. i.parent = this;
  38490. return i
  38491. });
  38492. return processed
  38493. }
  38494. getProxyProcessor() {
  38495. return {
  38496. set(node, prop, value) {
  38497. if (node[prop] === value) return true
  38498. node[prop] = value;
  38499. if (prop === 'name' || prop === 'params' || prop === 'selector') {
  38500. node.markDirty();
  38501. }
  38502. return true
  38503. },
  38504. get(node, prop) {
  38505. if (prop === 'proxyOf') {
  38506. return node
  38507. } else if (!node[prop]) {
  38508. return node[prop]
  38509. } else if (
  38510. prop === 'each' ||
  38511. (typeof prop === 'string' && prop.startsWith('walk'))
  38512. ) {
  38513. return (...args) => {
  38514. return node[prop](
  38515. ...args.map(i => {
  38516. if (typeof i === 'function') {
  38517. return (child, index) => i(child.toProxy(), index)
  38518. } else {
  38519. return i
  38520. }
  38521. })
  38522. )
  38523. }
  38524. } else if (prop === 'every' || prop === 'some') {
  38525. return cb => {
  38526. return node[prop]((child, ...other) =>
  38527. cb(child.toProxy(), ...other)
  38528. )
  38529. }
  38530. } else if (prop === 'root') {
  38531. return () => node.root().toProxy()
  38532. } else if (prop === 'nodes') {
  38533. return node.nodes.map(i => i.toProxy())
  38534. } else if (prop === 'first' || prop === 'last') {
  38535. return node[prop].toProxy()
  38536. } else {
  38537. return node[prop]
  38538. }
  38539. }
  38540. }
  38541. }
  38542. getIterator() {
  38543. if (!this.lastEach) this.lastEach = 0;
  38544. if (!this.indexes) this.indexes = {};
  38545. this.lastEach += 1;
  38546. let iterator = this.lastEach;
  38547. this.indexes[iterator] = 0;
  38548. return iterator
  38549. }
  38550. }
  38551. Container.registerParse = dependant => {
  38552. parse$5 = dependant;
  38553. };
  38554. Container.registerRule = dependant => {
  38555. Rule = dependant;
  38556. };
  38557. Container.registerAtRule = dependant => {
  38558. AtRule = dependant;
  38559. };
  38560. var container = Container;
  38561. Container.default = Container;
  38562. /* c8 ignore start */
  38563. Container.rebuild = node => {
  38564. if (node.type === 'atrule') {
  38565. Object.setPrototypeOf(node, AtRule.prototype);
  38566. } else if (node.type === 'rule') {
  38567. Object.setPrototypeOf(node, Rule.prototype);
  38568. } else if (node.type === 'decl') {
  38569. Object.setPrototypeOf(node, declaration.prototype);
  38570. } else if (node.type === 'comment') {
  38571. Object.setPrototypeOf(node, comment.prototype);
  38572. }
  38573. node[my$2] = true;
  38574. if (node.nodes) {
  38575. node.nodes.forEach(child => {
  38576. Container.rebuild(child);
  38577. });
  38578. }
  38579. };
  38580. let LazyResult, Processor;
  38581. class Document extends container {
  38582. constructor(defaults) {
  38583. // type needs to be passed to super, otherwise child roots won't be normalized correctly
  38584. super({ type: 'document', ...defaults });
  38585. if (!this.nodes) {
  38586. this.nodes = [];
  38587. }
  38588. }
  38589. toResult(opts = {}) {
  38590. let lazy = new LazyResult(new Processor(), this, opts);
  38591. return lazy.stringify()
  38592. }
  38593. }
  38594. Document.registerLazyResult = dependant => {
  38595. LazyResult = dependant;
  38596. };
  38597. Document.registerProcessor = dependant => {
  38598. Processor = dependant;
  38599. };
  38600. var document = Document;
  38601. Document.default = Document;
  38602. /* eslint-disable no-console */
  38603. let printed = {};
  38604. var warnOnce$2 = function warnOnce(message) {
  38605. if (printed[message]) return
  38606. printed[message] = true;
  38607. if (typeof console !== 'undefined' && console.warn) {
  38608. console.warn(message);
  38609. }
  38610. };
  38611. class Warning {
  38612. constructor(text, opts = {}) {
  38613. this.type = 'warning';
  38614. this.text = text;
  38615. if (opts.node && opts.node.source) {
  38616. let range = opts.node.rangeBy(opts);
  38617. this.line = range.start.line;
  38618. this.column = range.start.column;
  38619. this.endLine = range.end.line;
  38620. this.endColumn = range.end.column;
  38621. }
  38622. for (let opt in opts) this[opt] = opts[opt];
  38623. }
  38624. toString() {
  38625. if (this.node) {
  38626. return this.node.error(this.text, {
  38627. plugin: this.plugin,
  38628. index: this.index,
  38629. word: this.word
  38630. }).message
  38631. }
  38632. if (this.plugin) {
  38633. return this.plugin + ': ' + this.text
  38634. }
  38635. return this.text
  38636. }
  38637. }
  38638. var warning = Warning;
  38639. Warning.default = Warning;
  38640. class Result {
  38641. constructor(processor, root, opts) {
  38642. this.processor = processor;
  38643. this.messages = [];
  38644. this.root = root;
  38645. this.opts = opts;
  38646. this.css = undefined;
  38647. this.map = undefined;
  38648. }
  38649. toString() {
  38650. return this.css
  38651. }
  38652. warn(text, opts = {}) {
  38653. if (!opts.plugin) {
  38654. if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
  38655. opts.plugin = this.lastPlugin.postcssPlugin;
  38656. }
  38657. }
  38658. let warning$1 = new warning(text, opts);
  38659. this.messages.push(warning$1);
  38660. return warning$1
  38661. }
  38662. warnings() {
  38663. return this.messages.filter(i => i.type === 'warning')
  38664. }
  38665. get content() {
  38666. return this.css
  38667. }
  38668. }
  38669. var result = Result;
  38670. Result.default = Result;
  38671. class AtRule$1 extends container {
  38672. constructor(defaults) {
  38673. super(defaults);
  38674. this.type = 'atrule';
  38675. }
  38676. append(...children) {
  38677. if (!this.proxyOf.nodes) this.nodes = [];
  38678. return super.append(...children)
  38679. }
  38680. prepend(...children) {
  38681. if (!this.proxyOf.nodes) this.nodes = [];
  38682. return super.prepend(...children)
  38683. }
  38684. }
  38685. var atRule = AtRule$1;
  38686. AtRule$1.default = AtRule$1;
  38687. container.registerAtRule(AtRule$1);
  38688. let LazyResult$1, Processor$1;
  38689. class Root extends container {
  38690. constructor(defaults) {
  38691. super(defaults);
  38692. this.type = 'root';
  38693. if (!this.nodes) this.nodes = [];
  38694. }
  38695. removeChild(child, ignore) {
  38696. let index = this.index(child);
  38697. if (!ignore && index === 0 && this.nodes.length > 1) {
  38698. this.nodes[1].raws.before = this.nodes[index].raws.before;
  38699. }
  38700. return super.removeChild(child)
  38701. }
  38702. normalize(child, sample, type) {
  38703. let nodes = super.normalize(child);
  38704. if (sample) {
  38705. if (type === 'prepend') {
  38706. if (this.nodes.length > 1) {
  38707. sample.raws.before = this.nodes[1].raws.before;
  38708. } else {
  38709. delete sample.raws.before;
  38710. }
  38711. } else if (this.first !== sample) {
  38712. for (let node of nodes) {
  38713. node.raws.before = sample.raws.before;
  38714. }
  38715. }
  38716. }
  38717. return nodes
  38718. }
  38719. toResult(opts = {}) {
  38720. let lazy = new LazyResult$1(new Processor$1(), this, opts);
  38721. return lazy.stringify()
  38722. }
  38723. }
  38724. Root.registerLazyResult = dependant => {
  38725. LazyResult$1 = dependant;
  38726. };
  38727. Root.registerProcessor = dependant => {
  38728. Processor$1 = dependant;
  38729. };
  38730. var root = Root;
  38731. Root.default = Root;
  38732. let list = {
  38733. split(string, separators, last) {
  38734. let array = [];
  38735. let current = '';
  38736. let split = false;
  38737. let func = 0;
  38738. let quote = false;
  38739. let escape = false;
  38740. for (let letter of string) {
  38741. if (escape) {
  38742. escape = false;
  38743. } else if (letter === '\\') {
  38744. escape = true;
  38745. } else if (quote) {
  38746. if (letter === quote) {
  38747. quote = false;
  38748. }
  38749. } else if (letter === '"' || letter === "'") {
  38750. quote = letter;
  38751. } else if (letter === '(') {
  38752. func += 1;
  38753. } else if (letter === ')') {
  38754. if (func > 0) func -= 1;
  38755. } else if (func === 0) {
  38756. if (separators.includes(letter)) split = true;
  38757. }
  38758. if (split) {
  38759. if (current !== '') array.push(current.trim());
  38760. current = '';
  38761. split = false;
  38762. } else {
  38763. current += letter;
  38764. }
  38765. }
  38766. if (last || current !== '') array.push(current.trim());
  38767. return array
  38768. },
  38769. space(string) {
  38770. let spaces = [' ', '\n', '\t'];
  38771. return list.split(string, spaces)
  38772. },
  38773. comma(string) {
  38774. return list.split(string, [','], true)
  38775. }
  38776. };
  38777. var list_1 = list;
  38778. list.default = list;
  38779. class Rule$1 extends container {
  38780. constructor(defaults) {
  38781. super(defaults);
  38782. this.type = 'rule';
  38783. if (!this.nodes) this.nodes = [];
  38784. }
  38785. get selectors() {
  38786. return list_1.comma(this.selector)
  38787. }
  38788. set selectors(values) {
  38789. let match = this.selector ? this.selector.match(/,\s*/) : null;
  38790. let sep = match ? match[0] : ',' + this.raw('between', 'beforeOpen');
  38791. this.selector = values.join(sep);
  38792. }
  38793. }
  38794. var rule = Rule$1;
  38795. Rule$1.default = Rule$1;
  38796. container.registerRule(Rule$1);
  38797. class Parser$1 {
  38798. constructor(input) {
  38799. this.input = input;
  38800. this.root = new root();
  38801. this.current = this.root;
  38802. this.spaces = '';
  38803. this.semicolon = false;
  38804. this.customProperty = false;
  38805. this.createTokenizer();
  38806. this.root.source = { input, start: { offset: 0, line: 1, column: 1 } };
  38807. }
  38808. createTokenizer() {
  38809. this.tokenizer = tokenize(this.input);
  38810. }
  38811. parse() {
  38812. let token;
  38813. while (!this.tokenizer.endOfFile()) {
  38814. token = this.tokenizer.nextToken();
  38815. switch (token[0]) {
  38816. case 'space':
  38817. this.spaces += token[1];
  38818. break
  38819. case ';':
  38820. this.freeSemicolon(token);
  38821. break
  38822. case '}':
  38823. this.end(token);
  38824. break
  38825. case 'comment':
  38826. this.comment(token);
  38827. break
  38828. case 'at-word':
  38829. this.atrule(token);
  38830. break
  38831. case '{':
  38832. this.emptyRule(token);
  38833. break
  38834. default:
  38835. this.other(token);
  38836. break
  38837. }
  38838. }
  38839. this.endFile();
  38840. }
  38841. comment(token) {
  38842. let node = new comment();
  38843. this.init(node, token[2]);
  38844. node.source.end = this.getPosition(token[3] || token[2]);
  38845. let text = token[1].slice(2, -2);
  38846. if (/^\s*$/.test(text)) {
  38847. node.text = '';
  38848. node.raws.left = text;
  38849. node.raws.right = '';
  38850. } else {
  38851. let match = text.match(/^(\s*)([^]*\S)(\s*)$/);
  38852. node.text = match[2];
  38853. node.raws.left = match[1];
  38854. node.raws.right = match[3];
  38855. }
  38856. }
  38857. emptyRule(token) {
  38858. let node = new rule();
  38859. this.init(node, token[2]);
  38860. node.selector = '';
  38861. node.raws.between = '';
  38862. this.current = node;
  38863. }
  38864. other(start) {
  38865. let end = false;
  38866. let type = null;
  38867. let colon = false;
  38868. let bracket = null;
  38869. let brackets = [];
  38870. let customProperty = start[1].startsWith('--');
  38871. let tokens = [];
  38872. let token = start;
  38873. while (token) {
  38874. type = token[0];
  38875. tokens.push(token);
  38876. if (type === '(' || type === '[') {
  38877. if (!bracket) bracket = token;
  38878. brackets.push(type === '(' ? ')' : ']');
  38879. } else if (customProperty && colon && type === '{') {
  38880. if (!bracket) bracket = token;
  38881. brackets.push('}');
  38882. } else if (brackets.length === 0) {
  38883. if (type === ';') {
  38884. if (colon) {
  38885. this.decl(tokens, customProperty);
  38886. return
  38887. } else {
  38888. break
  38889. }
  38890. } else if (type === '{') {
  38891. this.rule(tokens);
  38892. return
  38893. } else if (type === '}') {
  38894. this.tokenizer.back(tokens.pop());
  38895. end = true;
  38896. break
  38897. } else if (type === ':') {
  38898. colon = true;
  38899. }
  38900. } else if (type === brackets[brackets.length - 1]) {
  38901. brackets.pop();
  38902. if (brackets.length === 0) bracket = null;
  38903. }
  38904. token = this.tokenizer.nextToken();
  38905. }
  38906. if (this.tokenizer.endOfFile()) end = true;
  38907. if (brackets.length > 0) this.unclosedBracket(bracket);
  38908. if (end && colon) {
  38909. while (tokens.length) {
  38910. token = tokens[tokens.length - 1][0];
  38911. if (token !== 'space' && token !== 'comment') break
  38912. this.tokenizer.back(tokens.pop());
  38913. }
  38914. this.decl(tokens, customProperty);
  38915. } else {
  38916. this.unknownWord(tokens);
  38917. }
  38918. }
  38919. rule(tokens) {
  38920. tokens.pop();
  38921. let node = new rule();
  38922. this.init(node, tokens[0][2]);
  38923. node.raws.between = this.spacesAndCommentsFromEnd(tokens);
  38924. this.raw(node, 'selector', tokens);
  38925. this.current = node;
  38926. }
  38927. decl(tokens, customProperty) {
  38928. let node = new declaration();
  38929. this.init(node, tokens[0][2]);
  38930. let last = tokens[tokens.length - 1];
  38931. if (last[0] === ';') {
  38932. this.semicolon = true;
  38933. tokens.pop();
  38934. }
  38935. node.source.end = this.getPosition(last[3] || last[2]);
  38936. while (tokens[0][0] !== 'word') {
  38937. if (tokens.length === 1) this.unknownWord(tokens);
  38938. node.raws.before += tokens.shift()[1];
  38939. }
  38940. node.source.start = this.getPosition(tokens[0][2]);
  38941. node.prop = '';
  38942. while (tokens.length) {
  38943. let type = tokens[0][0];
  38944. if (type === ':' || type === 'space' || type === 'comment') {
  38945. break
  38946. }
  38947. node.prop += tokens.shift()[1];
  38948. }
  38949. node.raws.between = '';
  38950. let token;
  38951. while (tokens.length) {
  38952. token = tokens.shift();
  38953. if (token[0] === ':') {
  38954. node.raws.between += token[1];
  38955. break
  38956. } else {
  38957. if (token[0] === 'word' && /\w/.test(token[1])) {
  38958. this.unknownWord([token]);
  38959. }
  38960. node.raws.between += token[1];
  38961. }
  38962. }
  38963. if (node.prop[0] === '_' || node.prop[0] === '*') {
  38964. node.raws.before += node.prop[0];
  38965. node.prop = node.prop.slice(1);
  38966. }
  38967. let firstSpaces = this.spacesAndCommentsFromStart(tokens);
  38968. this.precheckMissedSemicolon(tokens);
  38969. for (let i = tokens.length - 1; i >= 0; i--) {
  38970. token = tokens[i];
  38971. if (token[1].toLowerCase() === '!important') {
  38972. node.important = true;
  38973. let string = this.stringFrom(tokens, i);
  38974. string = this.spacesFromEnd(tokens) + string;
  38975. if (string !== ' !important') node.raws.important = string;
  38976. break
  38977. } else if (token[1].toLowerCase() === 'important') {
  38978. let cache = tokens.slice(0);
  38979. let str = '';
  38980. for (let j = i; j > 0; j--) {
  38981. let type = cache[j][0];
  38982. if (str.trim().indexOf('!') === 0 && type !== 'space') {
  38983. break
  38984. }
  38985. str = cache.pop()[1] + str;
  38986. }
  38987. if (str.trim().indexOf('!') === 0) {
  38988. node.important = true;
  38989. node.raws.important = str;
  38990. tokens = cache;
  38991. }
  38992. }
  38993. if (token[0] !== 'space' && token[0] !== 'comment') {
  38994. break
  38995. }
  38996. }
  38997. let hasWord = tokens.some(i => i[0] !== 'space' && i[0] !== 'comment');
  38998. this.raw(node, 'value', tokens);
  38999. if (hasWord) {
  39000. node.raws.between += firstSpaces;
  39001. } else {
  39002. node.value = firstSpaces + node.value;
  39003. }
  39004. if (node.value.includes(':') && !customProperty) {
  39005. this.checkMissedSemicolon(tokens);
  39006. }
  39007. }
  39008. atrule(token) {
  39009. let node = new atRule();
  39010. node.name = token[1].slice(1);
  39011. if (node.name === '') {
  39012. this.unnamedAtrule(node, token);
  39013. }
  39014. this.init(node, token[2]);
  39015. let type;
  39016. let prev;
  39017. let shift;
  39018. let last = false;
  39019. let open = false;
  39020. let params = [];
  39021. let brackets = [];
  39022. while (!this.tokenizer.endOfFile()) {
  39023. token = this.tokenizer.nextToken();
  39024. type = token[0];
  39025. if (type === '(' || type === '[') {
  39026. brackets.push(type === '(' ? ')' : ']');
  39027. } else if (type === '{' && brackets.length > 0) {
  39028. brackets.push('}');
  39029. } else if (type === brackets[brackets.length - 1]) {
  39030. brackets.pop();
  39031. }
  39032. if (brackets.length === 0) {
  39033. if (type === ';') {
  39034. node.source.end = this.getPosition(token[2]);
  39035. this.semicolon = true;
  39036. break
  39037. } else if (type === '{') {
  39038. open = true;
  39039. break
  39040. } else if (type === '}') {
  39041. if (params.length > 0) {
  39042. shift = params.length - 1;
  39043. prev = params[shift];
  39044. while (prev && prev[0] === 'space') {
  39045. prev = params[--shift];
  39046. }
  39047. if (prev) {
  39048. node.source.end = this.getPosition(prev[3] || prev[2]);
  39049. }
  39050. }
  39051. this.end(token);
  39052. break
  39053. } else {
  39054. params.push(token);
  39055. }
  39056. } else {
  39057. params.push(token);
  39058. }
  39059. if (this.tokenizer.endOfFile()) {
  39060. last = true;
  39061. break
  39062. }
  39063. }
  39064. node.raws.between = this.spacesAndCommentsFromEnd(params);
  39065. if (params.length) {
  39066. node.raws.afterName = this.spacesAndCommentsFromStart(params);
  39067. this.raw(node, 'params', params);
  39068. if (last) {
  39069. token = params[params.length - 1];
  39070. node.source.end = this.getPosition(token[3] || token[2]);
  39071. this.spaces = node.raws.between;
  39072. node.raws.between = '';
  39073. }
  39074. } else {
  39075. node.raws.afterName = '';
  39076. node.params = '';
  39077. }
  39078. if (open) {
  39079. node.nodes = [];
  39080. this.current = node;
  39081. }
  39082. }
  39083. end(token) {
  39084. if (this.current.nodes && this.current.nodes.length) {
  39085. this.current.raws.semicolon = this.semicolon;
  39086. }
  39087. this.semicolon = false;
  39088. this.current.raws.after = (this.current.raws.after || '') + this.spaces;
  39089. this.spaces = '';
  39090. if (this.current.parent) {
  39091. this.current.source.end = this.getPosition(token[2]);
  39092. this.current = this.current.parent;
  39093. } else {
  39094. this.unexpectedClose(token);
  39095. }
  39096. }
  39097. endFile() {
  39098. if (this.current.parent) this.unclosedBlock();
  39099. if (this.current.nodes && this.current.nodes.length) {
  39100. this.current.raws.semicolon = this.semicolon;
  39101. }
  39102. this.current.raws.after = (this.current.raws.after || '') + this.spaces;
  39103. }
  39104. freeSemicolon(token) {
  39105. this.spaces += token[1];
  39106. if (this.current.nodes) {
  39107. let prev = this.current.nodes[this.current.nodes.length - 1];
  39108. if (prev && prev.type === 'rule' && !prev.raws.ownSemicolon) {
  39109. prev.raws.ownSemicolon = this.spaces;
  39110. this.spaces = '';
  39111. }
  39112. }
  39113. }
  39114. // Helpers
  39115. getPosition(offset) {
  39116. let pos = this.input.fromOffset(offset);
  39117. return {
  39118. offset,
  39119. line: pos.line,
  39120. column: pos.col
  39121. }
  39122. }
  39123. init(node, offset) {
  39124. this.current.push(node);
  39125. node.source = {
  39126. start: this.getPosition(offset),
  39127. input: this.input
  39128. };
  39129. node.raws.before = this.spaces;
  39130. this.spaces = '';
  39131. if (node.type !== 'comment') this.semicolon = false;
  39132. }
  39133. raw(node, prop, tokens) {
  39134. let token, type;
  39135. let length = tokens.length;
  39136. let value = '';
  39137. let clean = true;
  39138. let next, prev;
  39139. let pattern = /^([#.|])?(\w)+/i;
  39140. for (let i = 0; i < length; i += 1) {
  39141. token = tokens[i];
  39142. type = token[0];
  39143. if (type === 'comment' && node.type === 'rule') {
  39144. prev = tokens[i - 1];
  39145. next = tokens[i + 1];
  39146. if (
  39147. prev[0] !== 'space' &&
  39148. next[0] !== 'space' &&
  39149. pattern.test(prev[1]) &&
  39150. pattern.test(next[1])
  39151. ) {
  39152. value += token[1];
  39153. } else {
  39154. clean = false;
  39155. }
  39156. continue
  39157. }
  39158. if (type === 'comment' || (type === 'space' && i === length - 1)) {
  39159. clean = false;
  39160. } else {
  39161. value += token[1];
  39162. }
  39163. }
  39164. if (!clean) {
  39165. let raw = tokens.reduce((all, i) => all + i[1], '');
  39166. node.raws[prop] = { value, raw };
  39167. }
  39168. node[prop] = value;
  39169. }
  39170. spacesAndCommentsFromEnd(tokens) {
  39171. let lastTokenType;
  39172. let spaces = '';
  39173. while (tokens.length) {
  39174. lastTokenType = tokens[tokens.length - 1][0];
  39175. if (lastTokenType !== 'space' && lastTokenType !== 'comment') break
  39176. spaces = tokens.pop()[1] + spaces;
  39177. }
  39178. return spaces
  39179. }
  39180. spacesAndCommentsFromStart(tokens) {
  39181. let next;
  39182. let spaces = '';
  39183. while (tokens.length) {
  39184. next = tokens[0][0];
  39185. if (next !== 'space' && next !== 'comment') break
  39186. spaces += tokens.shift()[1];
  39187. }
  39188. return spaces
  39189. }
  39190. spacesFromEnd(tokens) {
  39191. let lastTokenType;
  39192. let spaces = '';
  39193. while (tokens.length) {
  39194. lastTokenType = tokens[tokens.length - 1][0];
  39195. if (lastTokenType !== 'space') break
  39196. spaces = tokens.pop()[1] + spaces;
  39197. }
  39198. return spaces
  39199. }
  39200. stringFrom(tokens, from) {
  39201. let result = '';
  39202. for (let i = from; i < tokens.length; i++) {
  39203. result += tokens[i][1];
  39204. }
  39205. tokens.splice(from, tokens.length - from);
  39206. return result
  39207. }
  39208. colon(tokens) {
  39209. let brackets = 0;
  39210. let token, type, prev;
  39211. for (let [i, element] of tokens.entries()) {
  39212. token = element;
  39213. type = token[0];
  39214. if (type === '(') {
  39215. brackets += 1;
  39216. }
  39217. if (type === ')') {
  39218. brackets -= 1;
  39219. }
  39220. if (brackets === 0 && type === ':') {
  39221. if (!prev) {
  39222. this.doubleColon(token);
  39223. } else if (prev[0] === 'word' && prev[1] === 'progid') {
  39224. continue
  39225. } else {
  39226. return i
  39227. }
  39228. }
  39229. prev = token;
  39230. }
  39231. return false
  39232. }
  39233. // Errors
  39234. unclosedBracket(bracket) {
  39235. throw this.input.error(
  39236. 'Unclosed bracket',
  39237. { offset: bracket[2] },
  39238. { offset: bracket[2] + 1 }
  39239. )
  39240. }
  39241. unknownWord(tokens) {
  39242. throw this.input.error(
  39243. 'Unknown word',
  39244. { offset: tokens[0][2] },
  39245. { offset: tokens[0][2] + tokens[0][1].length }
  39246. )
  39247. }
  39248. unexpectedClose(token) {
  39249. throw this.input.error(
  39250. 'Unexpected }',
  39251. { offset: token[2] },
  39252. { offset: token[2] + 1 }
  39253. )
  39254. }
  39255. unclosedBlock() {
  39256. let pos = this.current.source.start;
  39257. throw this.input.error('Unclosed block', pos.line, pos.column)
  39258. }
  39259. doubleColon(token) {
  39260. throw this.input.error(
  39261. 'Double colon',
  39262. { offset: token[2] },
  39263. { offset: token[2] + token[1].length }
  39264. )
  39265. }
  39266. unnamedAtrule(node, token) {
  39267. throw this.input.error(
  39268. 'At-rule without name',
  39269. { offset: token[2] },
  39270. { offset: token[2] + token[1].length }
  39271. )
  39272. }
  39273. precheckMissedSemicolon(/* tokens */) {
  39274. // Hook for Safe Parser
  39275. }
  39276. checkMissedSemicolon(tokens) {
  39277. let colon = this.colon(tokens);
  39278. if (colon === false) return
  39279. let founded = 0;
  39280. let token;
  39281. for (let j = colon - 1; j >= 0; j--) {
  39282. token = tokens[j];
  39283. if (token[0] !== 'space') {
  39284. founded += 1;
  39285. if (founded === 2) break
  39286. }
  39287. }
  39288. // If the token is a word, e.g. `!important`, `red` or any other valid property's value.
  39289. // Then we need to return the colon after that word token. [3] is the "end" colon of that word.
  39290. // And because we need it after that one we do +1 to get the next one.
  39291. throw this.input.error(
  39292. 'Missed semicolon',
  39293. token[0] === 'word' ? token[3] + 1 : token[2]
  39294. )
  39295. }
  39296. }
  39297. var parser = Parser$1;
  39298. function parse$6(css, opts) {
  39299. let input$1 = new input(css, opts);
  39300. let parser$1 = new parser(input$1);
  39301. try {
  39302. parser$1.parse();
  39303. } catch (e) {
  39304. {
  39305. if (e.name === 'CssSyntaxError' && opts && opts.from) {
  39306. if (/\.scss$/i.test(opts.from)) {
  39307. e.message +=
  39308. '\nYou tried to parse SCSS with ' +
  39309. 'the standard CSS parser; ' +
  39310. 'try again with the postcss-scss parser';
  39311. } else if (/\.sass/i.test(opts.from)) {
  39312. e.message +=
  39313. '\nYou tried to parse Sass with ' +
  39314. 'the standard CSS parser; ' +
  39315. 'try again with the postcss-sass parser';
  39316. } else if (/\.less$/i.test(opts.from)) {
  39317. e.message +=
  39318. '\nYou tried to parse Less with ' +
  39319. 'the standard CSS parser; ' +
  39320. 'try again with the postcss-less parser';
  39321. }
  39322. }
  39323. }
  39324. throw e
  39325. }
  39326. return parser$1.root
  39327. }
  39328. var parse_1$1 = parse$6;
  39329. parse$6.default = parse$6;
  39330. container.registerParse(parse$6);
  39331. let { isClean: isClean$3, my: my$3 } = symbols;
  39332. const TYPE_TO_CLASS_NAME = {
  39333. document: 'Document',
  39334. root: 'Root',
  39335. atrule: 'AtRule',
  39336. rule: 'Rule',
  39337. decl: 'Declaration',
  39338. comment: 'Comment'
  39339. };
  39340. const PLUGIN_PROPS = {
  39341. postcssPlugin: true,
  39342. prepare: true,
  39343. Once: true,
  39344. Document: true,
  39345. Root: true,
  39346. Declaration: true,
  39347. Rule: true,
  39348. AtRule: true,
  39349. Comment: true,
  39350. DeclarationExit: true,
  39351. RuleExit: true,
  39352. AtRuleExit: true,
  39353. CommentExit: true,
  39354. RootExit: true,
  39355. DocumentExit: true,
  39356. OnceExit: true
  39357. };
  39358. const NOT_VISITORS = {
  39359. postcssPlugin: true,
  39360. prepare: true,
  39361. Once: true
  39362. };
  39363. const CHILDREN = 0;
  39364. function isPromise(obj) {
  39365. return typeof obj === 'object' && typeof obj.then === 'function'
  39366. }
  39367. function getEvents(node) {
  39368. let key = false;
  39369. let type = TYPE_TO_CLASS_NAME[node.type];
  39370. if (node.type === 'decl') {
  39371. key = node.prop.toLowerCase();
  39372. } else if (node.type === 'atrule') {
  39373. key = node.name.toLowerCase();
  39374. }
  39375. if (key && node.append) {
  39376. return [
  39377. type,
  39378. type + '-' + key,
  39379. CHILDREN,
  39380. type + 'Exit',
  39381. type + 'Exit-' + key
  39382. ]
  39383. } else if (key) {
  39384. return [type, type + '-' + key, type + 'Exit', type + 'Exit-' + key]
  39385. } else if (node.append) {
  39386. return [type, CHILDREN, type + 'Exit']
  39387. } else {
  39388. return [type, type + 'Exit']
  39389. }
  39390. }
  39391. function toStack(node) {
  39392. let events;
  39393. if (node.type === 'document') {
  39394. events = ['Document', CHILDREN, 'DocumentExit'];
  39395. } else if (node.type === 'root') {
  39396. events = ['Root', CHILDREN, 'RootExit'];
  39397. } else {
  39398. events = getEvents(node);
  39399. }
  39400. return {
  39401. node,
  39402. events,
  39403. eventIndex: 0,
  39404. visitors: [],
  39405. visitorIndex: 0,
  39406. iterator: 0
  39407. }
  39408. }
  39409. function cleanMarks(node) {
  39410. node[isClean$3] = false;
  39411. if (node.nodes) node.nodes.forEach(i => cleanMarks(i));
  39412. return node
  39413. }
  39414. let postcss = {};
  39415. class LazyResult$2 {
  39416. constructor(processor, css, opts) {
  39417. this.stringified = false;
  39418. this.processed = false;
  39419. let root;
  39420. if (
  39421. typeof css === 'object' &&
  39422. css !== null &&
  39423. (css.type === 'root' || css.type === 'document')
  39424. ) {
  39425. root = cleanMarks(css);
  39426. } else if (css instanceof LazyResult$2 || css instanceof result) {
  39427. root = cleanMarks(css.root);
  39428. if (css.map) {
  39429. if (typeof opts.map === 'undefined') opts.map = {};
  39430. if (!opts.map.inline) opts.map.inline = false;
  39431. opts.map.prev = css.map;
  39432. }
  39433. } else {
  39434. let parser = parse_1$1;
  39435. if (opts.syntax) parser = opts.syntax.parse;
  39436. if (opts.parser) parser = opts.parser;
  39437. if (parser.parse) parser = parser.parse;
  39438. try {
  39439. root = parser(css, opts);
  39440. } catch (error) {
  39441. this.processed = true;
  39442. this.error = error;
  39443. }
  39444. if (root && !root[my$3]) {
  39445. /* c8 ignore next 2 */
  39446. container.rebuild(root);
  39447. }
  39448. }
  39449. this.result = new result(processor, root, opts);
  39450. this.helpers = { ...postcss, result: this.result, postcss };
  39451. this.plugins = this.processor.plugins.map(plugin => {
  39452. if (typeof plugin === 'object' && plugin.prepare) {
  39453. return { ...plugin, ...plugin.prepare(this.result) }
  39454. } else {
  39455. return plugin
  39456. }
  39457. });
  39458. }
  39459. get [Symbol.toStringTag]() {
  39460. return 'LazyResult'
  39461. }
  39462. get processor() {
  39463. return this.result.processor
  39464. }
  39465. get opts() {
  39466. return this.result.opts
  39467. }
  39468. get css() {
  39469. return this.stringify().css
  39470. }
  39471. get content() {
  39472. return this.stringify().content
  39473. }
  39474. get map() {
  39475. return this.stringify().map
  39476. }
  39477. get root() {
  39478. return this.sync().root
  39479. }
  39480. get messages() {
  39481. return this.sync().messages
  39482. }
  39483. warnings() {
  39484. return this.sync().warnings()
  39485. }
  39486. toString() {
  39487. return this.css
  39488. }
  39489. then(onFulfilled, onRejected) {
  39490. {
  39491. if (!('from' in this.opts)) {
  39492. warnOnce$2(
  39493. 'Without `from` option PostCSS could generate wrong source map ' +
  39494. 'and will not find Browserslist config. Set it to CSS file path ' +
  39495. 'or to `undefined` to prevent this warning.'
  39496. );
  39497. }
  39498. }
  39499. return this.async().then(onFulfilled, onRejected)
  39500. }
  39501. catch(onRejected) {
  39502. return this.async().catch(onRejected)
  39503. }
  39504. finally(onFinally) {
  39505. return this.async().then(onFinally, onFinally)
  39506. }
  39507. async() {
  39508. if (this.error) return Promise.reject(this.error)
  39509. if (this.processed) return Promise.resolve(this.result)
  39510. if (!this.processing) {
  39511. this.processing = this.runAsync();
  39512. }
  39513. return this.processing
  39514. }
  39515. sync() {
  39516. if (this.error) throw this.error
  39517. if (this.processed) return this.result
  39518. this.processed = true;
  39519. if (this.processing) {
  39520. throw this.getAsyncError()
  39521. }
  39522. for (let plugin of this.plugins) {
  39523. let promise = this.runOnRoot(plugin);
  39524. if (isPromise(promise)) {
  39525. throw this.getAsyncError()
  39526. }
  39527. }
  39528. this.prepareVisitors();
  39529. if (this.hasListener) {
  39530. let root = this.result.root;
  39531. while (!root[isClean$3]) {
  39532. root[isClean$3] = true;
  39533. this.walkSync(root);
  39534. }
  39535. if (this.listeners.OnceExit) {
  39536. if (root.type === 'document') {
  39537. for (let subRoot of root.nodes) {
  39538. this.visitSync(this.listeners.OnceExit, subRoot);
  39539. }
  39540. } else {
  39541. this.visitSync(this.listeners.OnceExit, root);
  39542. }
  39543. }
  39544. }
  39545. return this.result
  39546. }
  39547. stringify() {
  39548. if (this.error) throw this.error
  39549. if (this.stringified) return this.result
  39550. this.stringified = true;
  39551. this.sync();
  39552. let opts = this.result.opts;
  39553. let str = stringify_1;
  39554. if (opts.syntax) str = opts.syntax.stringify;
  39555. if (opts.stringifier) str = opts.stringifier;
  39556. if (str.stringify) str = str.stringify;
  39557. let map = new mapGenerator(str, this.result.root, this.result.opts);
  39558. let data = map.generate();
  39559. this.result.css = data[0];
  39560. this.result.map = data[1];
  39561. return this.result
  39562. }
  39563. walkSync(node) {
  39564. node[isClean$3] = true;
  39565. let events = getEvents(node);
  39566. for (let event of events) {
  39567. if (event === CHILDREN) {
  39568. if (node.nodes) {
  39569. node.each(child => {
  39570. if (!child[isClean$3]) this.walkSync(child);
  39571. });
  39572. }
  39573. } else {
  39574. let visitors = this.listeners[event];
  39575. if (visitors) {
  39576. if (this.visitSync(visitors, node.toProxy())) return
  39577. }
  39578. }
  39579. }
  39580. }
  39581. visitSync(visitors, node) {
  39582. for (let [plugin, visitor] of visitors) {
  39583. this.result.lastPlugin = plugin;
  39584. let promise;
  39585. try {
  39586. promise = visitor(node, this.helpers);
  39587. } catch (e) {
  39588. throw this.handleError(e, node.proxyOf)
  39589. }
  39590. if (node.type !== 'root' && node.type !== 'document' && !node.parent) {
  39591. return true
  39592. }
  39593. if (isPromise(promise)) {
  39594. throw this.getAsyncError()
  39595. }
  39596. }
  39597. }
  39598. runOnRoot(plugin) {
  39599. this.result.lastPlugin = plugin;
  39600. try {
  39601. if (typeof plugin === 'object' && plugin.Once) {
  39602. if (this.result.root.type === 'document') {
  39603. let roots = this.result.root.nodes.map(root =>
  39604. plugin.Once(root, this.helpers)
  39605. );
  39606. if (isPromise(roots[0])) {
  39607. return Promise.all(roots)
  39608. }
  39609. return roots
  39610. }
  39611. return plugin.Once(this.result.root, this.helpers)
  39612. } else if (typeof plugin === 'function') {
  39613. return plugin(this.result.root, this.result)
  39614. }
  39615. } catch (error) {
  39616. throw this.handleError(error)
  39617. }
  39618. }
  39619. getAsyncError() {
  39620. throw new Error('Use process(css).then(cb) to work with async plugins')
  39621. }
  39622. handleError(error, node) {
  39623. let plugin = this.result.lastPlugin;
  39624. try {
  39625. if (node) node.addToError(error);
  39626. this.error = error;
  39627. if (error.name === 'CssSyntaxError' && !error.plugin) {
  39628. error.plugin = plugin.postcssPlugin;
  39629. error.setMessage();
  39630. } else if (plugin.postcssVersion) {
  39631. if (({}).NODE_ENV !== 'production') {
  39632. let pluginName = plugin.postcssPlugin;
  39633. let pluginVer = plugin.postcssVersion;
  39634. let runtimeVer = this.result.processor.version;
  39635. let a = pluginVer.split('.');
  39636. let b = runtimeVer.split('.');
  39637. if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) {
  39638. // eslint-disable-next-line no-console
  39639. console.error(
  39640. 'Unknown error from PostCSS plugin. Your current PostCSS ' +
  39641. 'version is ' +
  39642. runtimeVer +
  39643. ', but ' +
  39644. pluginName +
  39645. ' uses ' +
  39646. pluginVer +
  39647. '. Perhaps this is the source of the error below.'
  39648. );
  39649. }
  39650. }
  39651. }
  39652. } catch (err) {
  39653. /* c8 ignore next 3 */
  39654. // eslint-disable-next-line no-console
  39655. if (console && console.error) console.error(err);
  39656. }
  39657. return error
  39658. }
  39659. async runAsync() {
  39660. this.plugin = 0;
  39661. for (let i = 0; i < this.plugins.length; i++) {
  39662. let plugin = this.plugins[i];
  39663. let promise = this.runOnRoot(plugin);
  39664. if (isPromise(promise)) {
  39665. try {
  39666. await promise;
  39667. } catch (error) {
  39668. throw this.handleError(error)
  39669. }
  39670. }
  39671. }
  39672. this.prepareVisitors();
  39673. if (this.hasListener) {
  39674. let root = this.result.root;
  39675. while (!root[isClean$3]) {
  39676. root[isClean$3] = true;
  39677. let stack = [toStack(root)];
  39678. while (stack.length > 0) {
  39679. let promise = this.visitTick(stack);
  39680. if (isPromise(promise)) {
  39681. try {
  39682. await promise;
  39683. } catch (e) {
  39684. let node = stack[stack.length - 1].node;
  39685. throw this.handleError(e, node)
  39686. }
  39687. }
  39688. }
  39689. }
  39690. if (this.listeners.OnceExit) {
  39691. for (let [plugin, visitor] of this.listeners.OnceExit) {
  39692. this.result.lastPlugin = plugin;
  39693. try {
  39694. if (root.type === 'document') {
  39695. let roots = root.nodes.map(subRoot =>
  39696. visitor(subRoot, this.helpers)
  39697. );
  39698. await Promise.all(roots);
  39699. } else {
  39700. await visitor(root, this.helpers);
  39701. }
  39702. } catch (e) {
  39703. throw this.handleError(e)
  39704. }
  39705. }
  39706. }
  39707. }
  39708. this.processed = true;
  39709. return this.stringify()
  39710. }
  39711. prepareVisitors() {
  39712. this.listeners = {};
  39713. let add = (plugin, type, cb) => {
  39714. if (!this.listeners[type]) this.listeners[type] = [];
  39715. this.listeners[type].push([plugin, cb]);
  39716. };
  39717. for (let plugin of this.plugins) {
  39718. if (typeof plugin === 'object') {
  39719. for (let event in plugin) {
  39720. if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) {
  39721. throw new Error(
  39722. `Unknown event ${event} in ${plugin.postcssPlugin}. ` +
  39723. `Try to update PostCSS (${this.processor.version} now).`
  39724. )
  39725. }
  39726. if (!NOT_VISITORS[event]) {
  39727. if (typeof plugin[event] === 'object') {
  39728. for (let filter in plugin[event]) {
  39729. if (filter === '*') {
  39730. add(plugin, event, plugin[event][filter]);
  39731. } else {
  39732. add(
  39733. plugin,
  39734. event + '-' + filter.toLowerCase(),
  39735. plugin[event][filter]
  39736. );
  39737. }
  39738. }
  39739. } else if (typeof plugin[event] === 'function') {
  39740. add(plugin, event, plugin[event]);
  39741. }
  39742. }
  39743. }
  39744. }
  39745. }
  39746. this.hasListener = Object.keys(this.listeners).length > 0;
  39747. }
  39748. visitTick(stack) {
  39749. let visit = stack[stack.length - 1];
  39750. let { node, visitors } = visit;
  39751. if (node.type !== 'root' && node.type !== 'document' && !node.parent) {
  39752. stack.pop();
  39753. return
  39754. }
  39755. if (visitors.length > 0 && visit.visitorIndex < visitors.length) {
  39756. let [plugin, visitor] = visitors[visit.visitorIndex];
  39757. visit.visitorIndex += 1;
  39758. if (visit.visitorIndex === visitors.length) {
  39759. visit.visitors = [];
  39760. visit.visitorIndex = 0;
  39761. }
  39762. this.result.lastPlugin = plugin;
  39763. try {
  39764. return visitor(node.toProxy(), this.helpers)
  39765. } catch (e) {
  39766. throw this.handleError(e, node)
  39767. }
  39768. }
  39769. if (visit.iterator !== 0) {
  39770. let iterator = visit.iterator;
  39771. let child;
  39772. while ((child = node.nodes[node.indexes[iterator]])) {
  39773. node.indexes[iterator] += 1;
  39774. if (!child[isClean$3]) {
  39775. child[isClean$3] = true;
  39776. stack.push(toStack(child));
  39777. return
  39778. }
  39779. }
  39780. visit.iterator = 0;
  39781. delete node.indexes[iterator];
  39782. }
  39783. let events = visit.events;
  39784. while (visit.eventIndex < events.length) {
  39785. let event = events[visit.eventIndex];
  39786. visit.eventIndex += 1;
  39787. if (event === CHILDREN) {
  39788. if (node.nodes && node.nodes.length) {
  39789. node[isClean$3] = true;
  39790. visit.iterator = node.getIterator();
  39791. }
  39792. return
  39793. } else if (this.listeners[event]) {
  39794. visit.visitors = this.listeners[event];
  39795. return
  39796. }
  39797. }
  39798. stack.pop();
  39799. }
  39800. }
  39801. LazyResult$2.registerPostcss = dependant => {
  39802. postcss = dependant;
  39803. };
  39804. var lazyResult = LazyResult$2;
  39805. LazyResult$2.default = LazyResult$2;
  39806. root.registerLazyResult(LazyResult$2);
  39807. document.registerLazyResult(LazyResult$2);
  39808. class NoWorkResult {
  39809. constructor(processor, css, opts) {
  39810. css = css.toString();
  39811. this.stringified = false;
  39812. this._processor = processor;
  39813. this._css = css;
  39814. this._opts = opts;
  39815. this._map = undefined;
  39816. let root;
  39817. let str = stringify_1;
  39818. this.result = new result(this._processor, root, this._opts);
  39819. this.result.css = css;
  39820. let self = this;
  39821. Object.defineProperty(this.result, 'root', {
  39822. get() {
  39823. return self.root
  39824. }
  39825. });
  39826. let map = new mapGenerator(str, root, this._opts, css);
  39827. if (map.isMap()) {
  39828. let [generatedCSS, generatedMap] = map.generate();
  39829. if (generatedCSS) {
  39830. this.result.css = generatedCSS;
  39831. }
  39832. if (generatedMap) {
  39833. this.result.map = generatedMap;
  39834. }
  39835. }
  39836. }
  39837. get [Symbol.toStringTag]() {
  39838. return 'NoWorkResult'
  39839. }
  39840. get processor() {
  39841. return this.result.processor
  39842. }
  39843. get opts() {
  39844. return this.result.opts
  39845. }
  39846. get css() {
  39847. return this.result.css
  39848. }
  39849. get content() {
  39850. return this.result.css
  39851. }
  39852. get map() {
  39853. return this.result.map
  39854. }
  39855. get root() {
  39856. if (this._root) {
  39857. return this._root
  39858. }
  39859. let root;
  39860. let parser = parse_1$1;
  39861. try {
  39862. root = parser(this._css, this._opts);
  39863. } catch (error) {
  39864. this.error = error;
  39865. }
  39866. this._root = root;
  39867. return root
  39868. }
  39869. get messages() {
  39870. return []
  39871. }
  39872. warnings() {
  39873. return []
  39874. }
  39875. toString() {
  39876. return this._css
  39877. }
  39878. then(onFulfilled, onRejected) {
  39879. {
  39880. if (!('from' in this._opts)) {
  39881. warnOnce$2(
  39882. 'Without `from` option PostCSS could generate wrong source map ' +
  39883. 'and will not find Browserslist config. Set it to CSS file path ' +
  39884. 'or to `undefined` to prevent this warning.'
  39885. );
  39886. }
  39887. }
  39888. return this.async().then(onFulfilled, onRejected)
  39889. }
  39890. catch(onRejected) {
  39891. return this.async().catch(onRejected)
  39892. }
  39893. finally(onFinally) {
  39894. return this.async().then(onFinally, onFinally)
  39895. }
  39896. async() {
  39897. if (this.error) return Promise.reject(this.error)
  39898. return Promise.resolve(this.result)
  39899. }
  39900. sync() {
  39901. if (this.error) throw this.error
  39902. return this.result
  39903. }
  39904. }
  39905. var noWorkResult = NoWorkResult;
  39906. NoWorkResult.default = NoWorkResult;
  39907. class Processor$2 {
  39908. constructor(plugins = []) {
  39909. this.version = '8.4.4';
  39910. this.plugins = this.normalize(plugins);
  39911. }
  39912. use(plugin) {
  39913. this.plugins = this.plugins.concat(this.normalize([plugin]));
  39914. return this
  39915. }
  39916. process(css, opts = {}) {
  39917. if (
  39918. this.plugins.length === 0 &&
  39919. typeof opts.parser === 'undefined' &&
  39920. typeof opts.stringifier === 'undefined' &&
  39921. typeof opts.syntax === 'undefined'
  39922. ) {
  39923. return new noWorkResult(this, css, opts)
  39924. } else {
  39925. return new lazyResult(this, css, opts)
  39926. }
  39927. }
  39928. normalize(plugins) {
  39929. let normalized = [];
  39930. for (let i of plugins) {
  39931. if (i.postcss === true) {
  39932. i = i();
  39933. } else if (i.postcss) {
  39934. i = i.postcss;
  39935. }
  39936. if (typeof i === 'object' && Array.isArray(i.plugins)) {
  39937. normalized = normalized.concat(i.plugins);
  39938. } else if (typeof i === 'object' && i.postcssPlugin) {
  39939. normalized.push(i);
  39940. } else if (typeof i === 'function') {
  39941. normalized.push(i);
  39942. } else if (typeof i === 'object' && (i.parse || i.stringify)) {
  39943. {
  39944. throw new Error(
  39945. 'PostCSS syntaxes cannot be used as plugins. Instead, please use ' +
  39946. 'one of the syntax/parser/stringifier options as outlined ' +
  39947. 'in your PostCSS runner documentation.'
  39948. )
  39949. }
  39950. } else {
  39951. throw new Error(i + ' is not a PostCSS plugin')
  39952. }
  39953. }
  39954. return normalized
  39955. }
  39956. }
  39957. var processor = Processor$2;
  39958. Processor$2.default = Processor$2;
  39959. root.registerProcessor(Processor$2);
  39960. document.registerProcessor(Processor$2);
  39961. function fromJSON(json, inputs) {
  39962. if (Array.isArray(json)) return json.map(n => fromJSON(n))
  39963. let { inputs: ownInputs, ...defaults } = json;
  39964. if (ownInputs) {
  39965. inputs = [];
  39966. for (let input$1 of ownInputs) {
  39967. let inputHydrated = { ...input$1, __proto__: input.prototype };
  39968. if (inputHydrated.map) {
  39969. inputHydrated.map = {
  39970. ...inputHydrated.map,
  39971. __proto__: previousMap.prototype
  39972. };
  39973. }
  39974. inputs.push(inputHydrated);
  39975. }
  39976. }
  39977. if (defaults.nodes) {
  39978. defaults.nodes = json.nodes.map(n => fromJSON(n, inputs));
  39979. }
  39980. if (defaults.source) {
  39981. let { inputId, ...source } = defaults.source;
  39982. defaults.source = source;
  39983. if (inputId != null) {
  39984. defaults.source.input = inputs[inputId];
  39985. }
  39986. }
  39987. if (defaults.type === 'root') {
  39988. return new root(defaults)
  39989. } else if (defaults.type === 'decl') {
  39990. return new declaration(defaults)
  39991. } else if (defaults.type === 'rule') {
  39992. return new rule(defaults)
  39993. } else if (defaults.type === 'comment') {
  39994. return new comment(defaults)
  39995. } else if (defaults.type === 'atrule') {
  39996. return new atRule(defaults)
  39997. } else {
  39998. throw new Error('Unknown node type: ' + json.type)
  39999. }
  40000. }
  40001. var fromJSON_1 = fromJSON;
  40002. fromJSON.default = fromJSON;
  40003. function postcss$1(...plugins) {
  40004. if (plugins.length === 1 && Array.isArray(plugins[0])) {
  40005. plugins = plugins[0];
  40006. }
  40007. return new processor(plugins)
  40008. }
  40009. postcss$1.plugin = function plugin(name, initializer) {
  40010. // eslint-disable-next-line no-console
  40011. if (console && console.warn) {
  40012. // eslint-disable-next-line no-console
  40013. console.warn(
  40014. name +
  40015. ': postcss.plugin was deprecated. Migration guide:\n' +
  40016. 'https://evilmartians.com/chronicles/postcss-8-plugin-migration'
  40017. );
  40018. }
  40019. function creator(...args) {
  40020. let transformer = initializer(...args);
  40021. transformer.postcssPlugin = name;
  40022. transformer.postcssVersion = new processor().version;
  40023. return transformer
  40024. }
  40025. let cache;
  40026. Object.defineProperty(creator, 'postcss', {
  40027. get() {
  40028. if (!cache) cache = creator();
  40029. return cache
  40030. }
  40031. });
  40032. creator.process = function (css, processOpts, pluginOpts) {
  40033. return postcss$1([creator(pluginOpts)]).process(css, processOpts)
  40034. };
  40035. return creator
  40036. };
  40037. postcss$1.stringify = stringify_1;
  40038. postcss$1.parse = parse_1$1;
  40039. postcss$1.fromJSON = fromJSON_1;
  40040. postcss$1.list = list_1;
  40041. postcss$1.comment = defaults => new comment(defaults);
  40042. postcss$1.atRule = defaults => new atRule(defaults);
  40043. postcss$1.decl = defaults => new declaration(defaults);
  40044. postcss$1.rule = defaults => new rule(defaults);
  40045. postcss$1.root = defaults => new root(defaults);
  40046. postcss$1.document = defaults => new document(defaults);
  40047. postcss$1.CssSyntaxError = cssSyntaxError;
  40048. postcss$1.Declaration = declaration;
  40049. postcss$1.Container = container;
  40050. postcss$1.Processor = processor;
  40051. postcss$1.Document = document;
  40052. postcss$1.Comment = comment;
  40053. postcss$1.Warning = warning;
  40054. postcss$1.AtRule = atRule;
  40055. postcss$1.Result = result;
  40056. postcss$1.Input = input;
  40057. postcss$1.Rule = rule;
  40058. postcss$1.Root = root;
  40059. postcss$1.Node = node_1;
  40060. lazyResult.registerPostcss(postcss$1);
  40061. var postcss_1 = postcss$1;
  40062. postcss$1.default = postcss$1;
  40063. const trimPlugin = () => {
  40064. return {
  40065. postcssPlugin: 'vue-sfc-trim',
  40066. Once(root) {
  40067. root.walk(({ type, raws }) => {
  40068. if (type === 'rule' || type === 'atrule') {
  40069. if (raws.before)
  40070. raws.before = '\n';
  40071. if ('after' in raws && raws.after)
  40072. raws.after = '\n';
  40073. }
  40074. });
  40075. }
  40076. };
  40077. };
  40078. trimPlugin.postcss = true;
  40079. var unesc_1 = createCommonjsModule(function (module, exports) {
  40080. exports.__esModule = true;
  40081. exports["default"] = unesc;
  40082. // Many thanks for this post which made this migration much easier.
  40083. // https://mathiasbynens.be/notes/css-escapes
  40084. /**
  40085. *
  40086. * @param {string} str
  40087. * @returns {[string, number]|undefined}
  40088. */
  40089. function gobbleHex(str) {
  40090. var lower = str.toLowerCase();
  40091. var hex = '';
  40092. var spaceTerminated = false;
  40093. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  40094. var code = lower.charCodeAt(i); // check to see if we are dealing with a valid hex char [a-f|0-9]
  40095. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57; // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  40096. spaceTerminated = code === 32;
  40097. if (!valid) {
  40098. break;
  40099. }
  40100. hex += lower[i];
  40101. }
  40102. if (hex.length === 0) {
  40103. return undefined;
  40104. }
  40105. var codePoint = parseInt(hex, 16);
  40106. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF; // Add special case for
  40107. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  40108. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  40109. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  40110. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  40111. }
  40112. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  40113. }
  40114. var CONTAINS_ESCAPE = /\\/;
  40115. function unesc(str) {
  40116. var needToProcess = CONTAINS_ESCAPE.test(str);
  40117. if (!needToProcess) {
  40118. return str;
  40119. }
  40120. var ret = "";
  40121. for (var i = 0; i < str.length; i++) {
  40122. if (str[i] === "\\") {
  40123. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  40124. if (gobbled !== undefined) {
  40125. ret += gobbled[0];
  40126. i += gobbled[1];
  40127. continue;
  40128. } // Retain a pair of \\ if double escaped `\\\\`
  40129. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  40130. if (str[i + 1] === "\\") {
  40131. ret += "\\";
  40132. i++;
  40133. continue;
  40134. } // if \\ is at the end of the string retain it
  40135. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  40136. if (str.length === i + 1) {
  40137. ret += str[i];
  40138. }
  40139. continue;
  40140. }
  40141. ret += str[i];
  40142. }
  40143. return ret;
  40144. }
  40145. module.exports = exports.default;
  40146. });
  40147. var getProp_1 = createCommonjsModule(function (module, exports) {
  40148. exports.__esModule = true;
  40149. exports["default"] = getProp;
  40150. function getProp(obj) {
  40151. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  40152. props[_key - 1] = arguments[_key];
  40153. }
  40154. while (props.length > 0) {
  40155. var prop = props.shift();
  40156. if (!obj[prop]) {
  40157. return undefined;
  40158. }
  40159. obj = obj[prop];
  40160. }
  40161. return obj;
  40162. }
  40163. module.exports = exports.default;
  40164. });
  40165. var ensureObject_1 = createCommonjsModule(function (module, exports) {
  40166. exports.__esModule = true;
  40167. exports["default"] = ensureObject;
  40168. function ensureObject(obj) {
  40169. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  40170. props[_key - 1] = arguments[_key];
  40171. }
  40172. while (props.length > 0) {
  40173. var prop = props.shift();
  40174. if (!obj[prop]) {
  40175. obj[prop] = {};
  40176. }
  40177. obj = obj[prop];
  40178. }
  40179. }
  40180. module.exports = exports.default;
  40181. });
  40182. var stripComments_1 = createCommonjsModule(function (module, exports) {
  40183. exports.__esModule = true;
  40184. exports["default"] = stripComments;
  40185. function stripComments(str) {
  40186. var s = "";
  40187. var commentStart = str.indexOf("/*");
  40188. var lastEnd = 0;
  40189. while (commentStart >= 0) {
  40190. s = s + str.slice(lastEnd, commentStart);
  40191. var commentEnd = str.indexOf("*/", commentStart + 2);
  40192. if (commentEnd < 0) {
  40193. return s;
  40194. }
  40195. lastEnd = commentEnd + 2;
  40196. commentStart = str.indexOf("/*", lastEnd);
  40197. }
  40198. s = s + str.slice(lastEnd);
  40199. return s;
  40200. }
  40201. module.exports = exports.default;
  40202. });
  40203. var util$2 = createCommonjsModule(function (module, exports) {
  40204. exports.__esModule = true;
  40205. exports.stripComments = exports.ensureObject = exports.getProp = exports.unesc = void 0;
  40206. var _unesc = _interopRequireDefault(unesc_1);
  40207. exports.unesc = _unesc["default"];
  40208. var _getProp = _interopRequireDefault(getProp_1);
  40209. exports.getProp = _getProp["default"];
  40210. var _ensureObject = _interopRequireDefault(ensureObject_1);
  40211. exports.ensureObject = _ensureObject["default"];
  40212. var _stripComments = _interopRequireDefault(stripComments_1);
  40213. exports.stripComments = _stripComments["default"];
  40214. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40215. });
  40216. var node = createCommonjsModule(function (module, exports) {
  40217. exports.__esModule = true;
  40218. exports["default"] = void 0;
  40219. 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); } }
  40220. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  40221. var cloneNode = function cloneNode(obj, parent) {
  40222. if (typeof obj !== 'object' || obj === null) {
  40223. return obj;
  40224. }
  40225. var cloned = new obj.constructor();
  40226. for (var i in obj) {
  40227. if (!obj.hasOwnProperty(i)) {
  40228. continue;
  40229. }
  40230. var value = obj[i];
  40231. var type = typeof value;
  40232. if (i === 'parent' && type === 'object') {
  40233. if (parent) {
  40234. cloned[i] = parent;
  40235. }
  40236. } else if (value instanceof Array) {
  40237. cloned[i] = value.map(function (j) {
  40238. return cloneNode(j, cloned);
  40239. });
  40240. } else {
  40241. cloned[i] = cloneNode(value, cloned);
  40242. }
  40243. }
  40244. return cloned;
  40245. };
  40246. var Node = /*#__PURE__*/function () {
  40247. function Node(opts) {
  40248. if (opts === void 0) {
  40249. opts = {};
  40250. }
  40251. Object.assign(this, opts);
  40252. this.spaces = this.spaces || {};
  40253. this.spaces.before = this.spaces.before || '';
  40254. this.spaces.after = this.spaces.after || '';
  40255. }
  40256. var _proto = Node.prototype;
  40257. _proto.remove = function remove() {
  40258. if (this.parent) {
  40259. this.parent.removeChild(this);
  40260. }
  40261. this.parent = undefined;
  40262. return this;
  40263. };
  40264. _proto.replaceWith = function replaceWith() {
  40265. if (this.parent) {
  40266. for (var index in arguments) {
  40267. this.parent.insertBefore(this, arguments[index]);
  40268. }
  40269. this.remove();
  40270. }
  40271. return this;
  40272. };
  40273. _proto.next = function next() {
  40274. return this.parent.at(this.parent.index(this) + 1);
  40275. };
  40276. _proto.prev = function prev() {
  40277. return this.parent.at(this.parent.index(this) - 1);
  40278. };
  40279. _proto.clone = function clone(overrides) {
  40280. if (overrides === void 0) {
  40281. overrides = {};
  40282. }
  40283. var cloned = cloneNode(this);
  40284. for (var name in overrides) {
  40285. cloned[name] = overrides[name];
  40286. }
  40287. return cloned;
  40288. }
  40289. /**
  40290. * Some non-standard syntax doesn't follow normal escaping rules for css.
  40291. * This allows non standard syntax to be appended to an existing property
  40292. * by specifying the escaped value. By specifying the escaped value,
  40293. * illegal characters are allowed to be directly inserted into css output.
  40294. * @param {string} name the property to set
  40295. * @param {any} value the unescaped value of the property
  40296. * @param {string} valueEscaped optional. the escaped value of the property.
  40297. */
  40298. ;
  40299. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  40300. if (!this.raws) {
  40301. this.raws = {};
  40302. }
  40303. var originalValue = this[name];
  40304. var originalEscaped = this.raws[name];
  40305. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  40306. if (originalEscaped || valueEscaped !== value) {
  40307. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  40308. } else {
  40309. delete this.raws[name]; // delete any escaped value that was created by the setter.
  40310. }
  40311. }
  40312. /**
  40313. * Some non-standard syntax doesn't follow normal escaping rules for css.
  40314. * This allows the escaped value to be specified directly, allowing illegal
  40315. * characters to be directly inserted into css output.
  40316. * @param {string} name the property to set
  40317. * @param {any} value the unescaped value of the property
  40318. * @param {string} valueEscaped the escaped value of the property.
  40319. */
  40320. ;
  40321. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  40322. if (!this.raws) {
  40323. this.raws = {};
  40324. }
  40325. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  40326. this.raws[name] = valueEscaped;
  40327. }
  40328. /**
  40329. * When you want a value to passed through to CSS directly. This method
  40330. * deletes the corresponding raw value causing the stringifier to fallback
  40331. * to the unescaped value.
  40332. * @param {string} name the property to set.
  40333. * @param {any} value The value that is both escaped and unescaped.
  40334. */
  40335. ;
  40336. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  40337. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  40338. if (this.raws) {
  40339. delete this.raws[name];
  40340. }
  40341. }
  40342. /**
  40343. *
  40344. * @param {number} line The number (starting with 1)
  40345. * @param {number} column The column number (starting with 1)
  40346. */
  40347. ;
  40348. _proto.isAtPosition = function isAtPosition(line, column) {
  40349. if (this.source && this.source.start && this.source.end) {
  40350. if (this.source.start.line > line) {
  40351. return false;
  40352. }
  40353. if (this.source.end.line < line) {
  40354. return false;
  40355. }
  40356. if (this.source.start.line === line && this.source.start.column > column) {
  40357. return false;
  40358. }
  40359. if (this.source.end.line === line && this.source.end.column < column) {
  40360. return false;
  40361. }
  40362. return true;
  40363. }
  40364. return undefined;
  40365. };
  40366. _proto.stringifyProperty = function stringifyProperty(name) {
  40367. return this.raws && this.raws[name] || this[name];
  40368. };
  40369. _proto.valueToString = function valueToString() {
  40370. return String(this.stringifyProperty("value"));
  40371. };
  40372. _proto.toString = function toString() {
  40373. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  40374. };
  40375. _createClass(Node, [{
  40376. key: "rawSpaceBefore",
  40377. get: function get() {
  40378. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  40379. if (rawSpace === undefined) {
  40380. rawSpace = this.spaces && this.spaces.before;
  40381. }
  40382. return rawSpace || "";
  40383. },
  40384. set: function set(raw) {
  40385. (0, util$2.ensureObject)(this, "raws", "spaces");
  40386. this.raws.spaces.before = raw;
  40387. }
  40388. }, {
  40389. key: "rawSpaceAfter",
  40390. get: function get() {
  40391. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  40392. if (rawSpace === undefined) {
  40393. rawSpace = this.spaces.after;
  40394. }
  40395. return rawSpace || "";
  40396. },
  40397. set: function set(raw) {
  40398. (0, util$2.ensureObject)(this, "raws", "spaces");
  40399. this.raws.spaces.after = raw;
  40400. }
  40401. }]);
  40402. return Node;
  40403. }();
  40404. exports["default"] = Node;
  40405. module.exports = exports.default;
  40406. });
  40407. var types$1 = createCommonjsModule(function (module, exports) {
  40408. exports.__esModule = true;
  40409. exports.UNIVERSAL = exports.ATTRIBUTE = exports.CLASS = exports.COMBINATOR = exports.COMMENT = exports.ID = exports.NESTING = exports.PSEUDO = exports.ROOT = exports.SELECTOR = exports.STRING = exports.TAG = void 0;
  40410. var TAG = 'tag';
  40411. exports.TAG = TAG;
  40412. var STRING = 'string';
  40413. exports.STRING = STRING;
  40414. var SELECTOR = 'selector';
  40415. exports.SELECTOR = SELECTOR;
  40416. var ROOT = 'root';
  40417. exports.ROOT = ROOT;
  40418. var PSEUDO = 'pseudo';
  40419. exports.PSEUDO = PSEUDO;
  40420. var NESTING = 'nesting';
  40421. exports.NESTING = NESTING;
  40422. var ID = 'id';
  40423. exports.ID = ID;
  40424. var COMMENT = 'comment';
  40425. exports.COMMENT = COMMENT;
  40426. var COMBINATOR = 'combinator';
  40427. exports.COMBINATOR = COMBINATOR;
  40428. var CLASS = 'class';
  40429. exports.CLASS = CLASS;
  40430. var ATTRIBUTE = 'attribute';
  40431. exports.ATTRIBUTE = ATTRIBUTE;
  40432. var UNIVERSAL = 'universal';
  40433. exports.UNIVERSAL = UNIVERSAL;
  40434. });
  40435. var container$1 = createCommonjsModule(function (module, exports) {
  40436. exports.__esModule = true;
  40437. exports["default"] = void 0;
  40438. var _node = _interopRequireDefault(node);
  40439. var types = _interopRequireWildcard(types$1);
  40440. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  40441. 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; }
  40442. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40443. 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); }
  40444. 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); }
  40445. 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; }
  40446. 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); } }
  40447. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  40448. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  40449. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  40450. var Container = /*#__PURE__*/function (_Node) {
  40451. _inheritsLoose(Container, _Node);
  40452. function Container(opts) {
  40453. var _this;
  40454. _this = _Node.call(this, opts) || this;
  40455. if (!_this.nodes) {
  40456. _this.nodes = [];
  40457. }
  40458. return _this;
  40459. }
  40460. var _proto = Container.prototype;
  40461. _proto.append = function append(selector) {
  40462. selector.parent = this;
  40463. this.nodes.push(selector);
  40464. return this;
  40465. };
  40466. _proto.prepend = function prepend(selector) {
  40467. selector.parent = this;
  40468. this.nodes.unshift(selector);
  40469. return this;
  40470. };
  40471. _proto.at = function at(index) {
  40472. return this.nodes[index];
  40473. };
  40474. _proto.index = function index(child) {
  40475. if (typeof child === 'number') {
  40476. return child;
  40477. }
  40478. return this.nodes.indexOf(child);
  40479. };
  40480. _proto.removeChild = function removeChild(child) {
  40481. child = this.index(child);
  40482. this.at(child).parent = undefined;
  40483. this.nodes.splice(child, 1);
  40484. var index;
  40485. for (var id in this.indexes) {
  40486. index = this.indexes[id];
  40487. if (index >= child) {
  40488. this.indexes[id] = index - 1;
  40489. }
  40490. }
  40491. return this;
  40492. };
  40493. _proto.removeAll = function removeAll() {
  40494. for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
  40495. var node = _step.value;
  40496. node.parent = undefined;
  40497. }
  40498. this.nodes = [];
  40499. return this;
  40500. };
  40501. _proto.empty = function empty() {
  40502. return this.removeAll();
  40503. };
  40504. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  40505. newNode.parent = this;
  40506. var oldIndex = this.index(oldNode);
  40507. this.nodes.splice(oldIndex + 1, 0, newNode);
  40508. newNode.parent = this;
  40509. var index;
  40510. for (var id in this.indexes) {
  40511. index = this.indexes[id];
  40512. if (oldIndex <= index) {
  40513. this.indexes[id] = index + 1;
  40514. }
  40515. }
  40516. return this;
  40517. };
  40518. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  40519. newNode.parent = this;
  40520. var oldIndex = this.index(oldNode);
  40521. this.nodes.splice(oldIndex, 0, newNode);
  40522. newNode.parent = this;
  40523. var index;
  40524. for (var id in this.indexes) {
  40525. index = this.indexes[id];
  40526. if (index <= oldIndex) {
  40527. this.indexes[id] = index + 1;
  40528. }
  40529. }
  40530. return this;
  40531. };
  40532. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  40533. var found = undefined;
  40534. this.each(function (node) {
  40535. if (node.atPosition) {
  40536. var foundChild = node.atPosition(line, col);
  40537. if (foundChild) {
  40538. found = foundChild;
  40539. return false;
  40540. }
  40541. } else if (node.isAtPosition(line, col)) {
  40542. found = node;
  40543. return false;
  40544. }
  40545. });
  40546. return found;
  40547. }
  40548. /**
  40549. * Return the most specific node at the line and column number given.
  40550. * The source location is based on the original parsed location, locations aren't
  40551. * updated as selector nodes are mutated.
  40552. *
  40553. * Note that this location is relative to the location of the first character
  40554. * of the selector, and not the location of the selector in the overall document
  40555. * when used in conjunction with postcss.
  40556. *
  40557. * If not found, returns undefined.
  40558. * @param {number} line The line number of the node to find. (1-based index)
  40559. * @param {number} col The column number of the node to find. (1-based index)
  40560. */
  40561. ;
  40562. _proto.atPosition = function atPosition(line, col) {
  40563. if (this.isAtPosition(line, col)) {
  40564. return this._findChildAtPosition(line, col) || this;
  40565. } else {
  40566. return undefined;
  40567. }
  40568. };
  40569. _proto._inferEndPosition = function _inferEndPosition() {
  40570. if (this.last && this.last.source && this.last.source.end) {
  40571. this.source = this.source || {};
  40572. this.source.end = this.source.end || {};
  40573. Object.assign(this.source.end, this.last.source.end);
  40574. }
  40575. };
  40576. _proto.each = function each(callback) {
  40577. if (!this.lastEach) {
  40578. this.lastEach = 0;
  40579. }
  40580. if (!this.indexes) {
  40581. this.indexes = {};
  40582. }
  40583. this.lastEach++;
  40584. var id = this.lastEach;
  40585. this.indexes[id] = 0;
  40586. if (!this.length) {
  40587. return undefined;
  40588. }
  40589. var index, result;
  40590. while (this.indexes[id] < this.length) {
  40591. index = this.indexes[id];
  40592. result = callback(this.at(index), index);
  40593. if (result === false) {
  40594. break;
  40595. }
  40596. this.indexes[id] += 1;
  40597. }
  40598. delete this.indexes[id];
  40599. if (result === false) {
  40600. return false;
  40601. }
  40602. };
  40603. _proto.walk = function walk(callback) {
  40604. return this.each(function (node, i) {
  40605. var result = callback(node, i);
  40606. if (result !== false && node.length) {
  40607. result = node.walk(callback);
  40608. }
  40609. if (result === false) {
  40610. return false;
  40611. }
  40612. });
  40613. };
  40614. _proto.walkAttributes = function walkAttributes(callback) {
  40615. var _this2 = this;
  40616. return this.walk(function (selector) {
  40617. if (selector.type === types.ATTRIBUTE) {
  40618. return callback.call(_this2, selector);
  40619. }
  40620. });
  40621. };
  40622. _proto.walkClasses = function walkClasses(callback) {
  40623. var _this3 = this;
  40624. return this.walk(function (selector) {
  40625. if (selector.type === types.CLASS) {
  40626. return callback.call(_this3, selector);
  40627. }
  40628. });
  40629. };
  40630. _proto.walkCombinators = function walkCombinators(callback) {
  40631. var _this4 = this;
  40632. return this.walk(function (selector) {
  40633. if (selector.type === types.COMBINATOR) {
  40634. return callback.call(_this4, selector);
  40635. }
  40636. });
  40637. };
  40638. _proto.walkComments = function walkComments(callback) {
  40639. var _this5 = this;
  40640. return this.walk(function (selector) {
  40641. if (selector.type === types.COMMENT) {
  40642. return callback.call(_this5, selector);
  40643. }
  40644. });
  40645. };
  40646. _proto.walkIds = function walkIds(callback) {
  40647. var _this6 = this;
  40648. return this.walk(function (selector) {
  40649. if (selector.type === types.ID) {
  40650. return callback.call(_this6, selector);
  40651. }
  40652. });
  40653. };
  40654. _proto.walkNesting = function walkNesting(callback) {
  40655. var _this7 = this;
  40656. return this.walk(function (selector) {
  40657. if (selector.type === types.NESTING) {
  40658. return callback.call(_this7, selector);
  40659. }
  40660. });
  40661. };
  40662. _proto.walkPseudos = function walkPseudos(callback) {
  40663. var _this8 = this;
  40664. return this.walk(function (selector) {
  40665. if (selector.type === types.PSEUDO) {
  40666. return callback.call(_this8, selector);
  40667. }
  40668. });
  40669. };
  40670. _proto.walkTags = function walkTags(callback) {
  40671. var _this9 = this;
  40672. return this.walk(function (selector) {
  40673. if (selector.type === types.TAG) {
  40674. return callback.call(_this9, selector);
  40675. }
  40676. });
  40677. };
  40678. _proto.walkUniversals = function walkUniversals(callback) {
  40679. var _this10 = this;
  40680. return this.walk(function (selector) {
  40681. if (selector.type === types.UNIVERSAL) {
  40682. return callback.call(_this10, selector);
  40683. }
  40684. });
  40685. };
  40686. _proto.split = function split(callback) {
  40687. var _this11 = this;
  40688. var current = [];
  40689. return this.reduce(function (memo, node, index) {
  40690. var split = callback.call(_this11, node);
  40691. current.push(node);
  40692. if (split) {
  40693. memo.push(current);
  40694. current = [];
  40695. } else if (index === _this11.length - 1) {
  40696. memo.push(current);
  40697. }
  40698. return memo;
  40699. }, []);
  40700. };
  40701. _proto.map = function map(callback) {
  40702. return this.nodes.map(callback);
  40703. };
  40704. _proto.reduce = function reduce(callback, memo) {
  40705. return this.nodes.reduce(callback, memo);
  40706. };
  40707. _proto.every = function every(callback) {
  40708. return this.nodes.every(callback);
  40709. };
  40710. _proto.some = function some(callback) {
  40711. return this.nodes.some(callback);
  40712. };
  40713. _proto.filter = function filter(callback) {
  40714. return this.nodes.filter(callback);
  40715. };
  40716. _proto.sort = function sort(callback) {
  40717. return this.nodes.sort(callback);
  40718. };
  40719. _proto.toString = function toString() {
  40720. return this.map(String).join('');
  40721. };
  40722. _createClass(Container, [{
  40723. key: "first",
  40724. get: function get() {
  40725. return this.at(0);
  40726. }
  40727. }, {
  40728. key: "last",
  40729. get: function get() {
  40730. return this.at(this.length - 1);
  40731. }
  40732. }, {
  40733. key: "length",
  40734. get: function get() {
  40735. return this.nodes.length;
  40736. }
  40737. }]);
  40738. return Container;
  40739. }(_node["default"]);
  40740. exports["default"] = Container;
  40741. module.exports = exports.default;
  40742. });
  40743. var root$1 = createCommonjsModule(function (module, exports) {
  40744. exports.__esModule = true;
  40745. exports["default"] = void 0;
  40746. var _container = _interopRequireDefault(container$1);
  40747. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40748. 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); } }
  40749. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  40750. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  40751. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  40752. var Root = /*#__PURE__*/function (_Container) {
  40753. _inheritsLoose(Root, _Container);
  40754. function Root(opts) {
  40755. var _this;
  40756. _this = _Container.call(this, opts) || this;
  40757. _this.type = types$1.ROOT;
  40758. return _this;
  40759. }
  40760. var _proto = Root.prototype;
  40761. _proto.toString = function toString() {
  40762. var str = this.reduce(function (memo, selector) {
  40763. memo.push(String(selector));
  40764. return memo;
  40765. }, []).join(',');
  40766. return this.trailingComma ? str + ',' : str;
  40767. };
  40768. _proto.error = function error(message, options) {
  40769. if (this._error) {
  40770. return this._error(message, options);
  40771. } else {
  40772. return new Error(message);
  40773. }
  40774. };
  40775. _createClass(Root, [{
  40776. key: "errorGenerator",
  40777. set: function set(handler) {
  40778. this._error = handler;
  40779. }
  40780. }]);
  40781. return Root;
  40782. }(_container["default"]);
  40783. exports["default"] = Root;
  40784. module.exports = exports.default;
  40785. });
  40786. var selector = createCommonjsModule(function (module, exports) {
  40787. exports.__esModule = true;
  40788. exports["default"] = void 0;
  40789. var _container = _interopRequireDefault(container$1);
  40790. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40791. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  40792. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  40793. var Selector = /*#__PURE__*/function (_Container) {
  40794. _inheritsLoose(Selector, _Container);
  40795. function Selector(opts) {
  40796. var _this;
  40797. _this = _Container.call(this, opts) || this;
  40798. _this.type = types$1.SELECTOR;
  40799. return _this;
  40800. }
  40801. return Selector;
  40802. }(_container["default"]);
  40803. exports["default"] = Selector;
  40804. module.exports = exports.default;
  40805. });
  40806. /*! https://mths.be/cssesc v3.0.0 by @mathias */
  40807. var object = {};
  40808. var hasOwnProperty$3 = object.hasOwnProperty;
  40809. var merge = function merge(options, defaults) {
  40810. if (!options) {
  40811. return defaults;
  40812. }
  40813. var result = {};
  40814. for (var key in defaults) {
  40815. // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
  40816. // only recognized option names are used.
  40817. result[key] = hasOwnProperty$3.call(options, key) ? options[key] : defaults[key];
  40818. }
  40819. return result;
  40820. };
  40821. var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
  40822. var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
  40823. var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
  40824. // https://mathiasbynens.be/notes/css-escapes#css
  40825. var cssesc = function cssesc(string, options) {
  40826. options = merge(options, cssesc.options);
  40827. if (options.quotes != 'single' && options.quotes != 'double') {
  40828. options.quotes = 'single';
  40829. }
  40830. var quote = options.quotes == 'double' ? '"' : '\'';
  40831. var isIdentifier = options.isIdentifier;
  40832. var firstChar = string.charAt(0);
  40833. var output = '';
  40834. var counter = 0;
  40835. var length = string.length;
  40836. while (counter < length) {
  40837. var character = string.charAt(counter++);
  40838. var codePoint = character.charCodeAt();
  40839. var value = void 0;
  40840. // If it’s not a printable ASCII character…
  40841. if (codePoint < 0x20 || codePoint > 0x7E) {
  40842. if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
  40843. // It’s a high surrogate, and there is a next character.
  40844. var extra = string.charCodeAt(counter++);
  40845. if ((extra & 0xFC00) == 0xDC00) {
  40846. // next character is low surrogate
  40847. codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
  40848. } else {
  40849. // It’s an unmatched surrogate; only append this code unit, in case
  40850. // the next code unit is the high surrogate of a surrogate pair.
  40851. counter--;
  40852. }
  40853. }
  40854. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  40855. } else {
  40856. if (options.escapeEverything) {
  40857. if (regexAnySingleEscape.test(character)) {
  40858. value = '\\' + character;
  40859. } else {
  40860. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  40861. }
  40862. } else if (/[\t\n\f\r\x0B]/.test(character)) {
  40863. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  40864. } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
  40865. value = '\\' + character;
  40866. } else {
  40867. value = character;
  40868. }
  40869. }
  40870. output += value;
  40871. }
  40872. if (isIdentifier) {
  40873. if (/^-[-\d]/.test(output)) {
  40874. output = '\\-' + output.slice(1);
  40875. } else if (/\d/.test(firstChar)) {
  40876. output = '\\3' + firstChar + ' ' + output.slice(1);
  40877. }
  40878. }
  40879. // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
  40880. // since they’re redundant. Note that this is only possible if the escape
  40881. // sequence isn’t preceded by an odd number of backslashes.
  40882. output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
  40883. if ($1 && $1.length % 2) {
  40884. // It’s not safe to remove the space, so don’t.
  40885. return $0;
  40886. }
  40887. // Strip the space.
  40888. return ($1 || '') + $2;
  40889. });
  40890. if (!isIdentifier && options.wrap) {
  40891. return quote + output + quote;
  40892. }
  40893. return output;
  40894. };
  40895. // Expose default options (so they can be overridden globally).
  40896. cssesc.options = {
  40897. 'escapeEverything': false,
  40898. 'isIdentifier': false,
  40899. 'quotes': 'single',
  40900. 'wrap': false
  40901. };
  40902. cssesc.version = '3.0.0';
  40903. var cssesc_1 = cssesc;
  40904. var className = createCommonjsModule(function (module, exports) {
  40905. exports.__esModule = true;
  40906. exports["default"] = void 0;
  40907. var _cssesc = _interopRequireDefault(cssesc_1);
  40908. var _node = _interopRequireDefault(node);
  40909. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40910. 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); } }
  40911. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  40912. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  40913. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  40914. var ClassName = /*#__PURE__*/function (_Node) {
  40915. _inheritsLoose(ClassName, _Node);
  40916. function ClassName(opts) {
  40917. var _this;
  40918. _this = _Node.call(this, opts) || this;
  40919. _this.type = types$1.CLASS;
  40920. _this._constructed = true;
  40921. return _this;
  40922. }
  40923. var _proto = ClassName.prototype;
  40924. _proto.valueToString = function valueToString() {
  40925. return '.' + _Node.prototype.valueToString.call(this);
  40926. };
  40927. _createClass(ClassName, [{
  40928. key: "value",
  40929. get: function get() {
  40930. return this._value;
  40931. },
  40932. set: function set(v) {
  40933. if (this._constructed) {
  40934. var escaped = (0, _cssesc["default"])(v, {
  40935. isIdentifier: true
  40936. });
  40937. if (escaped !== v) {
  40938. (0, util$2.ensureObject)(this, "raws");
  40939. this.raws.value = escaped;
  40940. } else if (this.raws) {
  40941. delete this.raws.value;
  40942. }
  40943. }
  40944. this._value = v;
  40945. }
  40946. }]);
  40947. return ClassName;
  40948. }(_node["default"]);
  40949. exports["default"] = ClassName;
  40950. module.exports = exports.default;
  40951. });
  40952. var comment$1 = createCommonjsModule(function (module, exports) {
  40953. exports.__esModule = true;
  40954. exports["default"] = void 0;
  40955. var _node = _interopRequireDefault(node);
  40956. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40957. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  40958. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  40959. var Comment = /*#__PURE__*/function (_Node) {
  40960. _inheritsLoose(Comment, _Node);
  40961. function Comment(opts) {
  40962. var _this;
  40963. _this = _Node.call(this, opts) || this;
  40964. _this.type = types$1.COMMENT;
  40965. return _this;
  40966. }
  40967. return Comment;
  40968. }(_node["default"]);
  40969. exports["default"] = Comment;
  40970. module.exports = exports.default;
  40971. });
  40972. var id = createCommonjsModule(function (module, exports) {
  40973. exports.__esModule = true;
  40974. exports["default"] = void 0;
  40975. var _node = _interopRequireDefault(node);
  40976. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40977. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  40978. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  40979. var ID = /*#__PURE__*/function (_Node) {
  40980. _inheritsLoose(ID, _Node);
  40981. function ID(opts) {
  40982. var _this;
  40983. _this = _Node.call(this, opts) || this;
  40984. _this.type = types$1.ID;
  40985. return _this;
  40986. }
  40987. var _proto = ID.prototype;
  40988. _proto.valueToString = function valueToString() {
  40989. return '#' + _Node.prototype.valueToString.call(this);
  40990. };
  40991. return ID;
  40992. }(_node["default"]);
  40993. exports["default"] = ID;
  40994. module.exports = exports.default;
  40995. });
  40996. var namespace = createCommonjsModule(function (module, exports) {
  40997. exports.__esModule = true;
  40998. exports["default"] = void 0;
  40999. var _cssesc = _interopRequireDefault(cssesc_1);
  41000. var _node = _interopRequireDefault(node);
  41001. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41002. 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); } }
  41003. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  41004. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41005. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41006. var Namespace = /*#__PURE__*/function (_Node) {
  41007. _inheritsLoose(Namespace, _Node);
  41008. function Namespace() {
  41009. return _Node.apply(this, arguments) || this;
  41010. }
  41011. var _proto = Namespace.prototype;
  41012. _proto.qualifiedName = function qualifiedName(value) {
  41013. if (this.namespace) {
  41014. return this.namespaceString + "|" + value;
  41015. } else {
  41016. return value;
  41017. }
  41018. };
  41019. _proto.valueToString = function valueToString() {
  41020. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  41021. };
  41022. _createClass(Namespace, [{
  41023. key: "namespace",
  41024. get: function get() {
  41025. return this._namespace;
  41026. },
  41027. set: function set(namespace) {
  41028. if (namespace === true || namespace === "*" || namespace === "&") {
  41029. this._namespace = namespace;
  41030. if (this.raws) {
  41031. delete this.raws.namespace;
  41032. }
  41033. return;
  41034. }
  41035. var escaped = (0, _cssesc["default"])(namespace, {
  41036. isIdentifier: true
  41037. });
  41038. this._namespace = namespace;
  41039. if (escaped !== namespace) {
  41040. (0, util$2.ensureObject)(this, "raws");
  41041. this.raws.namespace = escaped;
  41042. } else if (this.raws) {
  41043. delete this.raws.namespace;
  41044. }
  41045. }
  41046. }, {
  41047. key: "ns",
  41048. get: function get() {
  41049. return this._namespace;
  41050. },
  41051. set: function set(namespace) {
  41052. this.namespace = namespace;
  41053. }
  41054. }, {
  41055. key: "namespaceString",
  41056. get: function get() {
  41057. if (this.namespace) {
  41058. var ns = this.stringifyProperty("namespace");
  41059. if (ns === true) {
  41060. return '';
  41061. } else {
  41062. return ns;
  41063. }
  41064. } else {
  41065. return '';
  41066. }
  41067. }
  41068. }]);
  41069. return Namespace;
  41070. }(_node["default"]);
  41071. exports["default"] = Namespace;
  41072. module.exports = exports.default;
  41073. });
  41074. var tag = createCommonjsModule(function (module, exports) {
  41075. exports.__esModule = true;
  41076. exports["default"] = void 0;
  41077. var _namespace = _interopRequireDefault(namespace);
  41078. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41079. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41080. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41081. var Tag = /*#__PURE__*/function (_Namespace) {
  41082. _inheritsLoose(Tag, _Namespace);
  41083. function Tag(opts) {
  41084. var _this;
  41085. _this = _Namespace.call(this, opts) || this;
  41086. _this.type = types$1.TAG;
  41087. return _this;
  41088. }
  41089. return Tag;
  41090. }(_namespace["default"]);
  41091. exports["default"] = Tag;
  41092. module.exports = exports.default;
  41093. });
  41094. var string = createCommonjsModule(function (module, exports) {
  41095. exports.__esModule = true;
  41096. exports["default"] = void 0;
  41097. var _node = _interopRequireDefault(node);
  41098. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41099. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41100. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41101. var String = /*#__PURE__*/function (_Node) {
  41102. _inheritsLoose(String, _Node);
  41103. function String(opts) {
  41104. var _this;
  41105. _this = _Node.call(this, opts) || this;
  41106. _this.type = types$1.STRING;
  41107. return _this;
  41108. }
  41109. return String;
  41110. }(_node["default"]);
  41111. exports["default"] = String;
  41112. module.exports = exports.default;
  41113. });
  41114. var pseudo = createCommonjsModule(function (module, exports) {
  41115. exports.__esModule = true;
  41116. exports["default"] = void 0;
  41117. var _container = _interopRequireDefault(container$1);
  41118. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41119. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41120. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41121. var Pseudo = /*#__PURE__*/function (_Container) {
  41122. _inheritsLoose(Pseudo, _Container);
  41123. function Pseudo(opts) {
  41124. var _this;
  41125. _this = _Container.call(this, opts) || this;
  41126. _this.type = types$1.PSEUDO;
  41127. return _this;
  41128. }
  41129. var _proto = Pseudo.prototype;
  41130. _proto.toString = function toString() {
  41131. var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
  41132. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  41133. };
  41134. return Pseudo;
  41135. }(_container["default"]);
  41136. exports["default"] = Pseudo;
  41137. module.exports = exports.default;
  41138. });
  41139. /**
  41140. * For Node.js, simply re-export the core `util.deprecate` function.
  41141. */
  41142. var node$1 = require$$0.deprecate;
  41143. var attribute = createCommonjsModule(function (module, exports) {
  41144. exports.__esModule = true;
  41145. exports.unescapeValue = unescapeValue;
  41146. exports["default"] = void 0;
  41147. var _cssesc = _interopRequireDefault(cssesc_1);
  41148. var _unesc = _interopRequireDefault(unesc_1);
  41149. var _namespace = _interopRequireDefault(namespace);
  41150. var _CSSESC_QUOTE_OPTIONS;
  41151. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41152. 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); } }
  41153. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  41154. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41155. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41156. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  41157. var warnOfDeprecatedValueAssignment = node$1(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  41158. var warnOfDeprecatedQuotedAssignment = node$1(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  41159. var warnOfDeprecatedConstructor = node$1(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  41160. function unescapeValue(value) {
  41161. var deprecatedUsage = false;
  41162. var quoteMark = null;
  41163. var unescaped = value;
  41164. var m = unescaped.match(WRAPPED_IN_QUOTES);
  41165. if (m) {
  41166. quoteMark = m[1];
  41167. unescaped = m[2];
  41168. }
  41169. unescaped = (0, _unesc["default"])(unescaped);
  41170. if (unescaped !== value) {
  41171. deprecatedUsage = true;
  41172. }
  41173. return {
  41174. deprecatedUsage: deprecatedUsage,
  41175. unescaped: unescaped,
  41176. quoteMark: quoteMark
  41177. };
  41178. }
  41179. function handleDeprecatedContructorOpts(opts) {
  41180. if (opts.quoteMark !== undefined) {
  41181. return opts;
  41182. }
  41183. if (opts.value === undefined) {
  41184. return opts;
  41185. }
  41186. warnOfDeprecatedConstructor();
  41187. var _unescapeValue = unescapeValue(opts.value),
  41188. quoteMark = _unescapeValue.quoteMark,
  41189. unescaped = _unescapeValue.unescaped;
  41190. if (!opts.raws) {
  41191. opts.raws = {};
  41192. }
  41193. if (opts.raws.value === undefined) {
  41194. opts.raws.value = opts.value;
  41195. }
  41196. opts.value = unescaped;
  41197. opts.quoteMark = quoteMark;
  41198. return opts;
  41199. }
  41200. var Attribute = /*#__PURE__*/function (_Namespace) {
  41201. _inheritsLoose(Attribute, _Namespace);
  41202. function Attribute(opts) {
  41203. var _this;
  41204. if (opts === void 0) {
  41205. opts = {};
  41206. }
  41207. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  41208. _this.type = types$1.ATTRIBUTE;
  41209. _this.raws = _this.raws || {};
  41210. Object.defineProperty(_this.raws, 'unquoted', {
  41211. get: node$1(function () {
  41212. return _this.value;
  41213. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  41214. set: node$1(function () {
  41215. return _this.value;
  41216. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  41217. });
  41218. _this._constructed = true;
  41219. return _this;
  41220. }
  41221. /**
  41222. * Returns the Attribute's value quoted such that it would be legal to use
  41223. * in the value of a css file. The original value's quotation setting
  41224. * used for stringification is left unchanged. See `setValue(value, options)`
  41225. * if you want to control the quote settings of a new value for the attribute.
  41226. *
  41227. * You can also change the quotation used for the current value by setting quoteMark.
  41228. *
  41229. * Options:
  41230. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  41231. * option is not set, the original value for quoteMark will be used. If
  41232. * indeterminate, a double quote is used. The legal values are:
  41233. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  41234. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  41235. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  41236. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  41237. * over the quoteMark option value.
  41238. * * smart {boolean} - if true, will select a quote mark based on the value
  41239. * and the other options specified here. See the `smartQuoteMark()`
  41240. * method.
  41241. **/
  41242. var _proto = Attribute.prototype;
  41243. _proto.getQuotedValue = function getQuotedValue(options) {
  41244. if (options === void 0) {
  41245. options = {};
  41246. }
  41247. var quoteMark = this._determineQuoteMark(options);
  41248. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  41249. var escaped = (0, _cssesc["default"])(this._value, cssescopts);
  41250. return escaped;
  41251. };
  41252. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  41253. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  41254. }
  41255. /**
  41256. * Set the unescaped value with the specified quotation options. The value
  41257. * provided must not include any wrapping quote marks -- those quotes will
  41258. * be interpreted as part of the value and escaped accordingly.
  41259. */
  41260. ;
  41261. _proto.setValue = function setValue(value, options) {
  41262. if (options === void 0) {
  41263. options = {};
  41264. }
  41265. this._value = value;
  41266. this._quoteMark = this._determineQuoteMark(options);
  41267. this._syncRawValue();
  41268. }
  41269. /**
  41270. * Intelligently select a quoteMark value based on the value's contents. If
  41271. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  41272. * mark will be picked that minimizes the number of escapes.
  41273. *
  41274. * If there's no clear winner, the quote mark from these options is used,
  41275. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  41276. * true). If the quoteMark is unspecified, a double quote is used.
  41277. *
  41278. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  41279. * from the quoteValue method.
  41280. */
  41281. ;
  41282. _proto.smartQuoteMark = function smartQuoteMark(options) {
  41283. var v = this.value;
  41284. var numSingleQuotes = v.replace(/[^']/g, '').length;
  41285. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  41286. if (numSingleQuotes + numDoubleQuotes === 0) {
  41287. var escaped = (0, _cssesc["default"])(v, {
  41288. isIdentifier: true
  41289. });
  41290. if (escaped === v) {
  41291. return Attribute.NO_QUOTE;
  41292. } else {
  41293. var pref = this.preferredQuoteMark(options);
  41294. if (pref === Attribute.NO_QUOTE) {
  41295. // pick a quote mark that isn't none and see if it's smaller
  41296. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  41297. var opts = CSSESC_QUOTE_OPTIONS[quote];
  41298. var quoteValue = (0, _cssesc["default"])(v, opts);
  41299. if (quoteValue.length < escaped.length) {
  41300. return quote;
  41301. }
  41302. }
  41303. return pref;
  41304. }
  41305. } else if (numDoubleQuotes === numSingleQuotes) {
  41306. return this.preferredQuoteMark(options);
  41307. } else if (numDoubleQuotes < numSingleQuotes) {
  41308. return Attribute.DOUBLE_QUOTE;
  41309. } else {
  41310. return Attribute.SINGLE_QUOTE;
  41311. }
  41312. }
  41313. /**
  41314. * Selects the preferred quote mark based on the options and the current quote mark value.
  41315. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  41316. * instead.
  41317. */
  41318. ;
  41319. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  41320. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  41321. if (quoteMark === undefined) {
  41322. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  41323. }
  41324. if (quoteMark === undefined) {
  41325. quoteMark = Attribute.DOUBLE_QUOTE;
  41326. }
  41327. return quoteMark;
  41328. };
  41329. _proto._syncRawValue = function _syncRawValue() {
  41330. var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  41331. if (rawValue === this._value) {
  41332. if (this.raws) {
  41333. delete this.raws.value;
  41334. }
  41335. } else {
  41336. this.raws.value = rawValue;
  41337. }
  41338. };
  41339. _proto._handleEscapes = function _handleEscapes(prop, value) {
  41340. if (this._constructed) {
  41341. var escaped = (0, _cssesc["default"])(value, {
  41342. isIdentifier: true
  41343. });
  41344. if (escaped !== value) {
  41345. this.raws[prop] = escaped;
  41346. } else {
  41347. delete this.raws[prop];
  41348. }
  41349. }
  41350. };
  41351. _proto._spacesFor = function _spacesFor(name) {
  41352. var attrSpaces = {
  41353. before: '',
  41354. after: ''
  41355. };
  41356. var spaces = this.spaces[name] || {};
  41357. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  41358. return Object.assign(attrSpaces, spaces, rawSpaces);
  41359. };
  41360. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  41361. if (spaceName === void 0) {
  41362. spaceName = name;
  41363. }
  41364. if (concat === void 0) {
  41365. concat = defaultAttrConcat;
  41366. }
  41367. var attrSpaces = this._spacesFor(spaceName);
  41368. return concat(this.stringifyProperty(name), attrSpaces);
  41369. }
  41370. /**
  41371. * returns the offset of the attribute part specified relative to the
  41372. * start of the node of the output string.
  41373. *
  41374. * * "ns" - alias for "namespace"
  41375. * * "namespace" - the namespace if it exists.
  41376. * * "attribute" - the attribute name
  41377. * * "attributeNS" - the start of the attribute or its namespace
  41378. * * "operator" - the match operator of the attribute
  41379. * * "value" - The value (string or identifier)
  41380. * * "insensitive" - the case insensitivity flag;
  41381. * @param part One of the possible values inside an attribute.
  41382. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  41383. */
  41384. ;
  41385. _proto.offsetOf = function offsetOf(name) {
  41386. var count = 1;
  41387. var attributeSpaces = this._spacesFor("attribute");
  41388. count += attributeSpaces.before.length;
  41389. if (name === "namespace" || name === "ns") {
  41390. return this.namespace ? count : -1;
  41391. }
  41392. if (name === "attributeNS") {
  41393. return count;
  41394. }
  41395. count += this.namespaceString.length;
  41396. if (this.namespace) {
  41397. count += 1;
  41398. }
  41399. if (name === "attribute") {
  41400. return count;
  41401. }
  41402. count += this.stringifyProperty("attribute").length;
  41403. count += attributeSpaces.after.length;
  41404. var operatorSpaces = this._spacesFor("operator");
  41405. count += operatorSpaces.before.length;
  41406. var operator = this.stringifyProperty("operator");
  41407. if (name === "operator") {
  41408. return operator ? count : -1;
  41409. }
  41410. count += operator.length;
  41411. count += operatorSpaces.after.length;
  41412. var valueSpaces = this._spacesFor("value");
  41413. count += valueSpaces.before.length;
  41414. var value = this.stringifyProperty("value");
  41415. if (name === "value") {
  41416. return value ? count : -1;
  41417. }
  41418. count += value.length;
  41419. count += valueSpaces.after.length;
  41420. var insensitiveSpaces = this._spacesFor("insensitive");
  41421. count += insensitiveSpaces.before.length;
  41422. if (name === "insensitive") {
  41423. return this.insensitive ? count : -1;
  41424. }
  41425. return -1;
  41426. };
  41427. _proto.toString = function toString() {
  41428. var _this2 = this;
  41429. var selector = [this.rawSpaceBefore, '['];
  41430. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  41431. if (this.operator && (this.value || this.value === '')) {
  41432. selector.push(this._stringFor('operator'));
  41433. selector.push(this._stringFor('value'));
  41434. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  41435. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  41436. attrSpaces.before = " ";
  41437. }
  41438. return defaultAttrConcat(attrValue, attrSpaces);
  41439. }));
  41440. }
  41441. selector.push(']');
  41442. selector.push(this.rawSpaceAfter);
  41443. return selector.join('');
  41444. };
  41445. _createClass(Attribute, [{
  41446. key: "quoted",
  41447. get: function get() {
  41448. var qm = this.quoteMark;
  41449. return qm === "'" || qm === '"';
  41450. },
  41451. set: function set(value) {
  41452. warnOfDeprecatedQuotedAssignment();
  41453. }
  41454. /**
  41455. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  41456. * returns `null` if the value is not quoted.
  41457. * returns `undefined` if the quotation state is unknown (this can happen when
  41458. * the attribute is constructed without specifying a quote mark.)
  41459. */
  41460. }, {
  41461. key: "quoteMark",
  41462. get: function get() {
  41463. return this._quoteMark;
  41464. }
  41465. /**
  41466. * Set the quote mark to be used by this attribute's value.
  41467. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  41468. * value is updated accordingly.
  41469. *
  41470. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  41471. */
  41472. ,
  41473. set: function set(quoteMark) {
  41474. if (!this._constructed) {
  41475. this._quoteMark = quoteMark;
  41476. return;
  41477. }
  41478. if (this._quoteMark !== quoteMark) {
  41479. this._quoteMark = quoteMark;
  41480. this._syncRawValue();
  41481. }
  41482. }
  41483. }, {
  41484. key: "qualifiedAttribute",
  41485. get: function get() {
  41486. return this.qualifiedName(this.raws.attribute || this.attribute);
  41487. }
  41488. }, {
  41489. key: "insensitiveFlag",
  41490. get: function get() {
  41491. return this.insensitive ? 'i' : '';
  41492. }
  41493. }, {
  41494. key: "value",
  41495. get: function get() {
  41496. return this._value;
  41497. }
  41498. /**
  41499. * Before 3.0, the value had to be set to an escaped value including any wrapped
  41500. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  41501. * is unescaped during parsing and any quote marks are removed.
  41502. *
  41503. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  41504. * a deprecation warning is raised when the new value contains any characters that would
  41505. * require escaping (including if it contains wrapped quotes).
  41506. *
  41507. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  41508. * how the new value is quoted.
  41509. */
  41510. ,
  41511. set: function set(v) {
  41512. if (this._constructed) {
  41513. var _unescapeValue2 = unescapeValue(v),
  41514. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  41515. unescaped = _unescapeValue2.unescaped,
  41516. quoteMark = _unescapeValue2.quoteMark;
  41517. if (deprecatedUsage) {
  41518. warnOfDeprecatedValueAssignment();
  41519. }
  41520. if (unescaped === this._value && quoteMark === this._quoteMark) {
  41521. return;
  41522. }
  41523. this._value = unescaped;
  41524. this._quoteMark = quoteMark;
  41525. this._syncRawValue();
  41526. } else {
  41527. this._value = v;
  41528. }
  41529. }
  41530. }, {
  41531. key: "attribute",
  41532. get: function get() {
  41533. return this._attribute;
  41534. },
  41535. set: function set(name) {
  41536. this._handleEscapes("attribute", name);
  41537. this._attribute = name;
  41538. }
  41539. }]);
  41540. return Attribute;
  41541. }(_namespace["default"]);
  41542. exports["default"] = Attribute;
  41543. Attribute.NO_QUOTE = null;
  41544. Attribute.SINGLE_QUOTE = "'";
  41545. Attribute.DOUBLE_QUOTE = '"';
  41546. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  41547. "'": {
  41548. quotes: 'single',
  41549. wrap: true
  41550. },
  41551. '"': {
  41552. quotes: 'double',
  41553. wrap: true
  41554. }
  41555. }, _CSSESC_QUOTE_OPTIONS[null] = {
  41556. isIdentifier: true
  41557. }, _CSSESC_QUOTE_OPTIONS);
  41558. function defaultAttrConcat(attrValue, attrSpaces) {
  41559. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  41560. }
  41561. });
  41562. var universal = createCommonjsModule(function (module, exports) {
  41563. exports.__esModule = true;
  41564. exports["default"] = void 0;
  41565. var _namespace = _interopRequireDefault(namespace);
  41566. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41567. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41568. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41569. var Universal = /*#__PURE__*/function (_Namespace) {
  41570. _inheritsLoose(Universal, _Namespace);
  41571. function Universal(opts) {
  41572. var _this;
  41573. _this = _Namespace.call(this, opts) || this;
  41574. _this.type = types$1.UNIVERSAL;
  41575. _this.value = '*';
  41576. return _this;
  41577. }
  41578. return Universal;
  41579. }(_namespace["default"]);
  41580. exports["default"] = Universal;
  41581. module.exports = exports.default;
  41582. });
  41583. var combinator = createCommonjsModule(function (module, exports) {
  41584. exports.__esModule = true;
  41585. exports["default"] = void 0;
  41586. var _node = _interopRequireDefault(node);
  41587. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41588. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41589. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41590. var Combinator = /*#__PURE__*/function (_Node) {
  41591. _inheritsLoose(Combinator, _Node);
  41592. function Combinator(opts) {
  41593. var _this;
  41594. _this = _Node.call(this, opts) || this;
  41595. _this.type = types$1.COMBINATOR;
  41596. return _this;
  41597. }
  41598. return Combinator;
  41599. }(_node["default"]);
  41600. exports["default"] = Combinator;
  41601. module.exports = exports.default;
  41602. });
  41603. var nesting = createCommonjsModule(function (module, exports) {
  41604. exports.__esModule = true;
  41605. exports["default"] = void 0;
  41606. var _node = _interopRequireDefault(node);
  41607. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41608. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  41609. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  41610. var Nesting = /*#__PURE__*/function (_Node) {
  41611. _inheritsLoose(Nesting, _Node);
  41612. function Nesting(opts) {
  41613. var _this;
  41614. _this = _Node.call(this, opts) || this;
  41615. _this.type = types$1.NESTING;
  41616. _this.value = '&';
  41617. return _this;
  41618. }
  41619. return Nesting;
  41620. }(_node["default"]);
  41621. exports["default"] = Nesting;
  41622. module.exports = exports.default;
  41623. });
  41624. var sortAscending_1 = createCommonjsModule(function (module, exports) {
  41625. exports.__esModule = true;
  41626. exports["default"] = sortAscending;
  41627. function sortAscending(list) {
  41628. return list.sort(function (a, b) {
  41629. return a - b;
  41630. });
  41631. }
  41632. module.exports = exports.default;
  41633. });
  41634. var tokenTypes$1 = createCommonjsModule(function (module, exports) {
  41635. exports.__esModule = true;
  41636. exports.combinator = exports.word = exports.comment = exports.str = exports.tab = exports.newline = exports.feed = exports.cr = exports.backslash = exports.bang = exports.slash = exports.doubleQuote = exports.singleQuote = exports.space = exports.greaterThan = exports.pipe = exports.equals = exports.plus = exports.caret = exports.tilde = exports.dollar = exports.closeSquare = exports.openSquare = exports.closeParenthesis = exports.openParenthesis = exports.semicolon = exports.colon = exports.comma = exports.at = exports.asterisk = exports.ampersand = void 0;
  41637. var ampersand = 38; // `&`.charCodeAt(0);
  41638. exports.ampersand = ampersand;
  41639. var asterisk = 42; // `*`.charCodeAt(0);
  41640. exports.asterisk = asterisk;
  41641. var at = 64; // `@`.charCodeAt(0);
  41642. exports.at = at;
  41643. var comma = 44; // `,`.charCodeAt(0);
  41644. exports.comma = comma;
  41645. var colon = 58; // `:`.charCodeAt(0);
  41646. exports.colon = colon;
  41647. var semicolon = 59; // `;`.charCodeAt(0);
  41648. exports.semicolon = semicolon;
  41649. var openParenthesis = 40; // `(`.charCodeAt(0);
  41650. exports.openParenthesis = openParenthesis;
  41651. var closeParenthesis = 41; // `)`.charCodeAt(0);
  41652. exports.closeParenthesis = closeParenthesis;
  41653. var openSquare = 91; // `[`.charCodeAt(0);
  41654. exports.openSquare = openSquare;
  41655. var closeSquare = 93; // `]`.charCodeAt(0);
  41656. exports.closeSquare = closeSquare;
  41657. var dollar = 36; // `$`.charCodeAt(0);
  41658. exports.dollar = dollar;
  41659. var tilde = 126; // `~`.charCodeAt(0);
  41660. exports.tilde = tilde;
  41661. var caret = 94; // `^`.charCodeAt(0);
  41662. exports.caret = caret;
  41663. var plus = 43; // `+`.charCodeAt(0);
  41664. exports.plus = plus;
  41665. var equals = 61; // `=`.charCodeAt(0);
  41666. exports.equals = equals;
  41667. var pipe = 124; // `|`.charCodeAt(0);
  41668. exports.pipe = pipe;
  41669. var greaterThan = 62; // `>`.charCodeAt(0);
  41670. exports.greaterThan = greaterThan;
  41671. var space = 32; // ` `.charCodeAt(0);
  41672. exports.space = space;
  41673. var singleQuote = 39; // `'`.charCodeAt(0);
  41674. exports.singleQuote = singleQuote;
  41675. var doubleQuote = 34; // `"`.charCodeAt(0);
  41676. exports.doubleQuote = doubleQuote;
  41677. var slash = 47; // `/`.charCodeAt(0);
  41678. exports.slash = slash;
  41679. var bang = 33; // `!`.charCodeAt(0);
  41680. exports.bang = bang;
  41681. var backslash = 92; // '\\'.charCodeAt(0);
  41682. exports.backslash = backslash;
  41683. var cr = 13; // '\r'.charCodeAt(0);
  41684. exports.cr = cr;
  41685. var feed = 12; // '\f'.charCodeAt(0);
  41686. exports.feed = feed;
  41687. var newline = 10; // '\n'.charCodeAt(0);
  41688. exports.newline = newline;
  41689. var tab = 9; // '\t'.charCodeAt(0);
  41690. // Expose aliases primarily for readability.
  41691. exports.tab = tab;
  41692. var str = singleQuote; // No good single character representation!
  41693. exports.str = str;
  41694. var comment = -1;
  41695. exports.comment = comment;
  41696. var word = -2;
  41697. exports.word = word;
  41698. var combinator = -3;
  41699. exports.combinator = combinator;
  41700. });
  41701. var tokenize_1 = createCommonjsModule(function (module, exports) {
  41702. exports.__esModule = true;
  41703. exports["default"] = tokenize;
  41704. exports.FIELDS = void 0;
  41705. var t = _interopRequireWildcard(tokenTypes$1);
  41706. var _unescapable, _wordDelimiters;
  41707. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  41708. 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; }
  41709. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  41710. 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);
  41711. var hex = {};
  41712. var hexChars = "0123456789abcdefABCDEF";
  41713. for (var i = 0; i < hexChars.length; i++) {
  41714. hex[hexChars.charCodeAt(i)] = true;
  41715. }
  41716. /**
  41717. * Returns the last index of the bar css word
  41718. * @param {string} css The string in which the word begins
  41719. * @param {number} start The index into the string where word's first letter occurs
  41720. */
  41721. function consumeWord(css, start) {
  41722. var next = start;
  41723. var code;
  41724. do {
  41725. code = css.charCodeAt(next);
  41726. if (wordDelimiters[code]) {
  41727. return next - 1;
  41728. } else if (code === t.backslash) {
  41729. next = consumeEscape(css, next) + 1;
  41730. } else {
  41731. // All other characters are part of the word
  41732. next++;
  41733. }
  41734. } while (next < css.length);
  41735. return next - 1;
  41736. }
  41737. /**
  41738. * Returns the last index of the escape sequence
  41739. * @param {string} css The string in which the sequence begins
  41740. * @param {number} start The index into the string where escape character (`\`) occurs.
  41741. */
  41742. function consumeEscape(css, start) {
  41743. var next = start;
  41744. var code = css.charCodeAt(next + 1);
  41745. if (unescapable[code]) ; else if (hex[code]) {
  41746. var hexDigits = 0; // consume up to 6 hex chars
  41747. do {
  41748. next++;
  41749. hexDigits++;
  41750. code = css.charCodeAt(next + 1);
  41751. } while (hex[code] && hexDigits < 6); // if fewer than 6 hex chars, a trailing space ends the escape
  41752. if (hexDigits < 6 && code === t.space) {
  41753. next++;
  41754. }
  41755. } else {
  41756. // the next char is part of the current word
  41757. next++;
  41758. }
  41759. return next;
  41760. }
  41761. var FIELDS = {
  41762. TYPE: 0,
  41763. START_LINE: 1,
  41764. START_COL: 2,
  41765. END_LINE: 3,
  41766. END_COL: 4,
  41767. START_POS: 5,
  41768. END_POS: 6
  41769. };
  41770. exports.FIELDS = FIELDS;
  41771. function tokenize(input) {
  41772. var tokens = [];
  41773. var css = input.css.valueOf();
  41774. var _css = css,
  41775. length = _css.length;
  41776. var offset = -1;
  41777. var line = 1;
  41778. var start = 0;
  41779. var end = 0;
  41780. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  41781. function unclosed(what, fix) {
  41782. if (input.safe) {
  41783. // fyi: this is never set to true.
  41784. css += fix;
  41785. next = css.length - 1;
  41786. } else {
  41787. throw input.error('Unclosed ' + what, line, start - offset, start);
  41788. }
  41789. }
  41790. while (start < length) {
  41791. code = css.charCodeAt(start);
  41792. if (code === t.newline) {
  41793. offset = start;
  41794. line += 1;
  41795. }
  41796. switch (code) {
  41797. case t.space:
  41798. case t.tab:
  41799. case t.newline:
  41800. case t.cr:
  41801. case t.feed:
  41802. next = start;
  41803. do {
  41804. next += 1;
  41805. code = css.charCodeAt(next);
  41806. if (code === t.newline) {
  41807. offset = next;
  41808. line += 1;
  41809. }
  41810. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  41811. tokenType = t.space;
  41812. endLine = line;
  41813. endColumn = next - offset - 1;
  41814. end = next;
  41815. break;
  41816. case t.plus:
  41817. case t.greaterThan:
  41818. case t.tilde:
  41819. case t.pipe:
  41820. next = start;
  41821. do {
  41822. next += 1;
  41823. code = css.charCodeAt(next);
  41824. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  41825. tokenType = t.combinator;
  41826. endLine = line;
  41827. endColumn = start - offset;
  41828. end = next;
  41829. break;
  41830. // Consume these characters as single tokens.
  41831. case t.asterisk:
  41832. case t.ampersand:
  41833. case t.bang:
  41834. case t.comma:
  41835. case t.equals:
  41836. case t.dollar:
  41837. case t.caret:
  41838. case t.openSquare:
  41839. case t.closeSquare:
  41840. case t.colon:
  41841. case t.semicolon:
  41842. case t.openParenthesis:
  41843. case t.closeParenthesis:
  41844. next = start;
  41845. tokenType = code;
  41846. endLine = line;
  41847. endColumn = start - offset;
  41848. end = next + 1;
  41849. break;
  41850. case t.singleQuote:
  41851. case t.doubleQuote:
  41852. quote = code === t.singleQuote ? "'" : '"';
  41853. next = start;
  41854. do {
  41855. escaped = false;
  41856. next = css.indexOf(quote, next + 1);
  41857. if (next === -1) {
  41858. unclosed('quote', quote);
  41859. }
  41860. escapePos = next;
  41861. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  41862. escapePos -= 1;
  41863. escaped = !escaped;
  41864. }
  41865. } while (escaped);
  41866. tokenType = t.str;
  41867. endLine = line;
  41868. endColumn = start - offset;
  41869. end = next + 1;
  41870. break;
  41871. default:
  41872. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  41873. next = css.indexOf('*/', start + 2) + 1;
  41874. if (next === 0) {
  41875. unclosed('comment', '*/');
  41876. }
  41877. content = css.slice(start, next + 1);
  41878. lines = content.split('\n');
  41879. last = lines.length - 1;
  41880. if (last > 0) {
  41881. nextLine = line + last;
  41882. nextOffset = next - lines[last].length;
  41883. } else {
  41884. nextLine = line;
  41885. nextOffset = offset;
  41886. }
  41887. tokenType = t.comment;
  41888. line = nextLine;
  41889. endLine = nextLine;
  41890. endColumn = next - nextOffset;
  41891. } else if (code === t.slash) {
  41892. next = start;
  41893. tokenType = code;
  41894. endLine = line;
  41895. endColumn = start - offset;
  41896. end = next + 1;
  41897. } else {
  41898. next = consumeWord(css, start);
  41899. tokenType = t.word;
  41900. endLine = line;
  41901. endColumn = next - offset;
  41902. }
  41903. end = next + 1;
  41904. break;
  41905. } // Ensure that the token structure remains consistent
  41906. tokens.push([tokenType, // [0] Token type
  41907. line, // [1] Starting line
  41908. start - offset, // [2] Starting column
  41909. endLine, // [3] Ending line
  41910. endColumn, // [4] Ending column
  41911. start, // [5] Start position / Source index
  41912. end // [6] End position
  41913. ]); // Reset offset for the next token
  41914. if (nextOffset) {
  41915. offset = nextOffset;
  41916. nextOffset = null;
  41917. }
  41918. start = end;
  41919. }
  41920. return tokens;
  41921. }
  41922. });
  41923. var parser$1 = createCommonjsModule(function (module, exports) {
  41924. exports.__esModule = true;
  41925. exports["default"] = void 0;
  41926. var _root = _interopRequireDefault(root$1);
  41927. var _selector = _interopRequireDefault(selector);
  41928. var _className = _interopRequireDefault(className);
  41929. var _comment = _interopRequireDefault(comment$1);
  41930. var _id = _interopRequireDefault(id);
  41931. var _tag = _interopRequireDefault(tag);
  41932. var _string = _interopRequireDefault(string);
  41933. var _pseudo = _interopRequireDefault(pseudo);
  41934. var _attribute = _interopRequireWildcard(attribute);
  41935. var _universal = _interopRequireDefault(universal);
  41936. var _combinator = _interopRequireDefault(combinator);
  41937. var _nesting = _interopRequireDefault(nesting);
  41938. var _sortAscending = _interopRequireDefault(sortAscending_1);
  41939. var _tokenize = _interopRequireWildcard(tokenize_1);
  41940. var tokens = _interopRequireWildcard(tokenTypes$1);
  41941. var types = _interopRequireWildcard(types$1);
  41942. var _WHITESPACE_TOKENS, _Object$assign;
  41943. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  41944. 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; }
  41945. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41946. 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); } }
  41947. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  41948. 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);
  41949. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  41950. function tokenStart(token) {
  41951. return {
  41952. line: token[_tokenize.FIELDS.START_LINE],
  41953. column: token[_tokenize.FIELDS.START_COL]
  41954. };
  41955. }
  41956. function tokenEnd(token) {
  41957. return {
  41958. line: token[_tokenize.FIELDS.END_LINE],
  41959. column: token[_tokenize.FIELDS.END_COL]
  41960. };
  41961. }
  41962. function getSource(startLine, startColumn, endLine, endColumn) {
  41963. return {
  41964. start: {
  41965. line: startLine,
  41966. column: startColumn
  41967. },
  41968. end: {
  41969. line: endLine,
  41970. column: endColumn
  41971. }
  41972. };
  41973. }
  41974. function getTokenSource(token) {
  41975. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  41976. }
  41977. function getTokenSourceSpan(startToken, endToken) {
  41978. if (!startToken) {
  41979. return undefined;
  41980. }
  41981. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  41982. }
  41983. function unescapeProp(node, prop) {
  41984. var value = node[prop];
  41985. if (typeof value !== "string") {
  41986. return;
  41987. }
  41988. if (value.indexOf("\\") !== -1) {
  41989. (0, util$2.ensureObject)(node, 'raws');
  41990. node[prop] = (0, util$2.unesc)(value);
  41991. if (node.raws[prop] === undefined) {
  41992. node.raws[prop] = value;
  41993. }
  41994. }
  41995. return node;
  41996. }
  41997. function indexesOf(array, item) {
  41998. var i = -1;
  41999. var indexes = [];
  42000. while ((i = array.indexOf(item, i + 1)) !== -1) {
  42001. indexes.push(i);
  42002. }
  42003. return indexes;
  42004. }
  42005. function uniqs() {
  42006. var list = Array.prototype.concat.apply([], arguments);
  42007. return list.filter(function (item, i) {
  42008. return i === list.indexOf(item);
  42009. });
  42010. }
  42011. var Parser = /*#__PURE__*/function () {
  42012. function Parser(rule, options) {
  42013. if (options === void 0) {
  42014. options = {};
  42015. }
  42016. this.rule = rule;
  42017. this.options = Object.assign({
  42018. lossy: false,
  42019. safe: false
  42020. }, options);
  42021. this.position = 0;
  42022. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  42023. this.tokens = (0, _tokenize["default"])({
  42024. css: this.css,
  42025. error: this._errorGenerator(),
  42026. safe: this.options.safe
  42027. });
  42028. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  42029. this.root = new _root["default"]({
  42030. source: rootSource
  42031. });
  42032. this.root.errorGenerator = this._errorGenerator();
  42033. var selector = new _selector["default"]({
  42034. source: {
  42035. start: {
  42036. line: 1,
  42037. column: 1
  42038. }
  42039. }
  42040. });
  42041. this.root.append(selector);
  42042. this.current = selector;
  42043. this.loop();
  42044. }
  42045. var _proto = Parser.prototype;
  42046. _proto._errorGenerator = function _errorGenerator() {
  42047. var _this = this;
  42048. return function (message, errorOptions) {
  42049. if (typeof _this.rule === 'string') {
  42050. return new Error(message);
  42051. }
  42052. return _this.rule.error(message, errorOptions);
  42053. };
  42054. };
  42055. _proto.attribute = function attribute() {
  42056. var attr = [];
  42057. var startingToken = this.currToken;
  42058. this.position++;
  42059. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  42060. attr.push(this.currToken);
  42061. this.position++;
  42062. }
  42063. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  42064. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  42065. }
  42066. var len = attr.length;
  42067. var node = {
  42068. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  42069. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  42070. };
  42071. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  42072. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  42073. }
  42074. var pos = 0;
  42075. var spaceBefore = '';
  42076. var commentBefore = '';
  42077. var lastAdded = null;
  42078. var spaceAfterMeaningfulToken = false;
  42079. while (pos < len) {
  42080. var token = attr[pos];
  42081. var content = this.content(token);
  42082. var next = attr[pos + 1];
  42083. switch (token[_tokenize.FIELDS.TYPE]) {
  42084. case tokens.space:
  42085. // if (
  42086. // len === 1 ||
  42087. // pos === 0 && this.content(next) === '|'
  42088. // ) {
  42089. // return this.expected('attribute', token[TOKEN.START_POS], content);
  42090. // }
  42091. spaceAfterMeaningfulToken = true;
  42092. if (this.options.lossy) {
  42093. break;
  42094. }
  42095. if (lastAdded) {
  42096. (0, util$2.ensureObject)(node, 'spaces', lastAdded);
  42097. var prevContent = node.spaces[lastAdded].after || '';
  42098. node.spaces[lastAdded].after = prevContent + content;
  42099. var existingComment = (0, util$2.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  42100. if (existingComment) {
  42101. node.raws.spaces[lastAdded].after = existingComment + content;
  42102. }
  42103. } else {
  42104. spaceBefore = spaceBefore + content;
  42105. commentBefore = commentBefore + content;
  42106. }
  42107. break;
  42108. case tokens.asterisk:
  42109. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  42110. node.operator = content;
  42111. lastAdded = 'operator';
  42112. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  42113. if (spaceBefore) {
  42114. (0, util$2.ensureObject)(node, 'spaces', 'attribute');
  42115. node.spaces.attribute.before = spaceBefore;
  42116. spaceBefore = '';
  42117. }
  42118. if (commentBefore) {
  42119. (0, util$2.ensureObject)(node, 'raws', 'spaces', 'attribute');
  42120. node.raws.spaces.attribute.before = spaceBefore;
  42121. commentBefore = '';
  42122. }
  42123. node.namespace = (node.namespace || "") + content;
  42124. var rawValue = (0, util$2.getProp)(node, 'raws', 'namespace') || null;
  42125. if (rawValue) {
  42126. node.raws.namespace += content;
  42127. }
  42128. lastAdded = 'namespace';
  42129. }
  42130. spaceAfterMeaningfulToken = false;
  42131. break;
  42132. case tokens.dollar:
  42133. if (lastAdded === "value") {
  42134. var oldRawValue = (0, util$2.getProp)(node, 'raws', 'value');
  42135. node.value += "$";
  42136. if (oldRawValue) {
  42137. node.raws.value = oldRawValue + "$";
  42138. }
  42139. break;
  42140. }
  42141. // Falls through
  42142. case tokens.caret:
  42143. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  42144. node.operator = content;
  42145. lastAdded = 'operator';
  42146. }
  42147. spaceAfterMeaningfulToken = false;
  42148. break;
  42149. case tokens.combinator:
  42150. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  42151. node.operator = content;
  42152. lastAdded = 'operator';
  42153. }
  42154. if (content !== '|') {
  42155. spaceAfterMeaningfulToken = false;
  42156. break;
  42157. }
  42158. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  42159. node.operator = content;
  42160. lastAdded = 'operator';
  42161. } else if (!node.namespace && !node.attribute) {
  42162. node.namespace = true;
  42163. }
  42164. spaceAfterMeaningfulToken = false;
  42165. break;
  42166. case tokens.word:
  42167. 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.
  42168. !node.operator && !node.namespace) {
  42169. node.namespace = content;
  42170. lastAdded = 'namespace';
  42171. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  42172. if (spaceBefore) {
  42173. (0, util$2.ensureObject)(node, 'spaces', 'attribute');
  42174. node.spaces.attribute.before = spaceBefore;
  42175. spaceBefore = '';
  42176. }
  42177. if (commentBefore) {
  42178. (0, util$2.ensureObject)(node, 'raws', 'spaces', 'attribute');
  42179. node.raws.spaces.attribute.before = commentBefore;
  42180. commentBefore = '';
  42181. }
  42182. node.attribute = (node.attribute || "") + content;
  42183. var _rawValue = (0, util$2.getProp)(node, 'raws', 'attribute') || null;
  42184. if (_rawValue) {
  42185. node.raws.attribute += content;
  42186. }
  42187. lastAdded = 'attribute';
  42188. } else if (!node.value && node.value !== "" || lastAdded === "value" && !spaceAfterMeaningfulToken) {
  42189. var _unescaped = (0, util$2.unesc)(content);
  42190. var _oldRawValue = (0, util$2.getProp)(node, 'raws', 'value') || '';
  42191. var oldValue = node.value || '';
  42192. node.value = oldValue + _unescaped;
  42193. node.quoteMark = null;
  42194. if (_unescaped !== content || _oldRawValue) {
  42195. (0, util$2.ensureObject)(node, 'raws');
  42196. node.raws.value = (_oldRawValue || oldValue) + content;
  42197. }
  42198. lastAdded = 'value';
  42199. } else {
  42200. var insensitive = content === 'i' || content === "I";
  42201. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  42202. node.insensitive = insensitive;
  42203. if (!insensitive || content === "I") {
  42204. (0, util$2.ensureObject)(node, 'raws');
  42205. node.raws.insensitiveFlag = content;
  42206. }
  42207. lastAdded = 'insensitive';
  42208. if (spaceBefore) {
  42209. (0, util$2.ensureObject)(node, 'spaces', 'insensitive');
  42210. node.spaces.insensitive.before = spaceBefore;
  42211. spaceBefore = '';
  42212. }
  42213. if (commentBefore) {
  42214. (0, util$2.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  42215. node.raws.spaces.insensitive.before = commentBefore;
  42216. commentBefore = '';
  42217. }
  42218. } else if (node.value || node.value === '') {
  42219. lastAdded = 'value';
  42220. node.value += content;
  42221. if (node.raws.value) {
  42222. node.raws.value += content;
  42223. }
  42224. }
  42225. }
  42226. spaceAfterMeaningfulToken = false;
  42227. break;
  42228. case tokens.str:
  42229. if (!node.attribute || !node.operator) {
  42230. return this.error("Expected an attribute followed by an operator preceding the string.", {
  42231. index: token[_tokenize.FIELDS.START_POS]
  42232. });
  42233. }
  42234. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  42235. unescaped = _unescapeValue.unescaped,
  42236. quoteMark = _unescapeValue.quoteMark;
  42237. node.value = unescaped;
  42238. node.quoteMark = quoteMark;
  42239. lastAdded = 'value';
  42240. (0, util$2.ensureObject)(node, 'raws');
  42241. node.raws.value = content;
  42242. spaceAfterMeaningfulToken = false;
  42243. break;
  42244. case tokens.equals:
  42245. if (!node.attribute) {
  42246. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  42247. }
  42248. if (node.value) {
  42249. return this.error('Unexpected "=" found; an operator was already defined.', {
  42250. index: token[_tokenize.FIELDS.START_POS]
  42251. });
  42252. }
  42253. node.operator = node.operator ? node.operator + content : content;
  42254. lastAdded = 'operator';
  42255. spaceAfterMeaningfulToken = false;
  42256. break;
  42257. case tokens.comment:
  42258. if (lastAdded) {
  42259. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  42260. var lastComment = (0, util$2.getProp)(node, 'spaces', lastAdded, 'after') || '';
  42261. var rawLastComment = (0, util$2.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  42262. (0, util$2.ensureObject)(node, 'raws', 'spaces', lastAdded);
  42263. node.raws.spaces[lastAdded].after = rawLastComment + content;
  42264. } else {
  42265. var lastValue = node[lastAdded] || '';
  42266. var rawLastValue = (0, util$2.getProp)(node, 'raws', lastAdded) || lastValue;
  42267. (0, util$2.ensureObject)(node, 'raws');
  42268. node.raws[lastAdded] = rawLastValue + content;
  42269. }
  42270. } else {
  42271. commentBefore = commentBefore + content;
  42272. }
  42273. break;
  42274. default:
  42275. return this.error("Unexpected \"" + content + "\" found.", {
  42276. index: token[_tokenize.FIELDS.START_POS]
  42277. });
  42278. }
  42279. pos++;
  42280. }
  42281. unescapeProp(node, "attribute");
  42282. unescapeProp(node, "namespace");
  42283. this.newNode(new _attribute["default"](node));
  42284. this.position++;
  42285. }
  42286. /**
  42287. * return a node containing meaningless garbage up to (but not including) the specified token position.
  42288. * if the token position is negative, all remaining tokens are consumed.
  42289. *
  42290. * This returns an array containing a single string node if all whitespace,
  42291. * otherwise an array of comment nodes with space before and after.
  42292. *
  42293. * These tokens are not added to the current selector, the caller can add them or use them to amend
  42294. * a previous node's space metadata.
  42295. *
  42296. * In lossy mode, this returns only comments.
  42297. */
  42298. ;
  42299. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  42300. if (stopPosition < 0) {
  42301. stopPosition = this.tokens.length;
  42302. }
  42303. var startPosition = this.position;
  42304. var nodes = [];
  42305. var space = "";
  42306. var lastComment = undefined;
  42307. do {
  42308. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  42309. if (!this.options.lossy) {
  42310. space += this.content();
  42311. }
  42312. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  42313. var spaces = {};
  42314. if (space) {
  42315. spaces.before = space;
  42316. space = "";
  42317. }
  42318. lastComment = new _comment["default"]({
  42319. value: this.content(),
  42320. source: getTokenSource(this.currToken),
  42321. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  42322. spaces: spaces
  42323. });
  42324. nodes.push(lastComment);
  42325. }
  42326. } while (++this.position < stopPosition);
  42327. if (space) {
  42328. if (lastComment) {
  42329. lastComment.spaces.after = space;
  42330. } else if (!this.options.lossy) {
  42331. var firstToken = this.tokens[startPosition];
  42332. var lastToken = this.tokens[this.position - 1];
  42333. nodes.push(new _string["default"]({
  42334. value: '',
  42335. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  42336. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  42337. spaces: {
  42338. before: space,
  42339. after: ''
  42340. }
  42341. }));
  42342. }
  42343. }
  42344. return nodes;
  42345. }
  42346. /**
  42347. *
  42348. * @param {*} nodes
  42349. */
  42350. ;
  42351. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  42352. var _this2 = this;
  42353. if (requiredSpace === void 0) {
  42354. requiredSpace = false;
  42355. }
  42356. var space = "";
  42357. var rawSpace = "";
  42358. nodes.forEach(function (n) {
  42359. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  42360. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  42361. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  42362. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  42363. });
  42364. if (rawSpace === space) {
  42365. rawSpace = undefined;
  42366. }
  42367. var result = {
  42368. space: space,
  42369. rawSpace: rawSpace
  42370. };
  42371. return result;
  42372. };
  42373. _proto.isNamedCombinator = function isNamedCombinator(position) {
  42374. if (position === void 0) {
  42375. position = this.position;
  42376. }
  42377. 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;
  42378. };
  42379. _proto.namedCombinator = function namedCombinator() {
  42380. if (this.isNamedCombinator()) {
  42381. var nameRaw = this.content(this.tokens[this.position + 1]);
  42382. var name = (0, util$2.unesc)(nameRaw).toLowerCase();
  42383. var raws = {};
  42384. if (name !== nameRaw) {
  42385. raws.value = "/" + nameRaw + "/";
  42386. }
  42387. var node = new _combinator["default"]({
  42388. value: "/" + name + "/",
  42389. 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]),
  42390. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  42391. raws: raws
  42392. });
  42393. this.position = this.position + 3;
  42394. return node;
  42395. } else {
  42396. this.unexpected();
  42397. }
  42398. };
  42399. _proto.combinator = function combinator() {
  42400. var _this3 = this;
  42401. if (this.content() === '|') {
  42402. return this.namespace();
  42403. } // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  42404. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  42405. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma) {
  42406. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  42407. if (nodes.length > 0) {
  42408. var last = this.current.last;
  42409. if (last) {
  42410. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  42411. space = _this$convertWhitespa.space,
  42412. rawSpace = _this$convertWhitespa.rawSpace;
  42413. if (rawSpace !== undefined) {
  42414. last.rawSpaceAfter += rawSpace;
  42415. }
  42416. last.spaces.after += space;
  42417. } else {
  42418. nodes.forEach(function (n) {
  42419. return _this3.newNode(n);
  42420. });
  42421. }
  42422. }
  42423. return;
  42424. }
  42425. var firstToken = this.currToken;
  42426. var spaceOrDescendantSelectorNodes = undefined;
  42427. if (nextSigTokenPos > this.position) {
  42428. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  42429. }
  42430. var node;
  42431. if (this.isNamedCombinator()) {
  42432. node = this.namedCombinator();
  42433. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  42434. node = new _combinator["default"]({
  42435. value: this.content(),
  42436. source: getTokenSource(this.currToken),
  42437. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  42438. });
  42439. this.position++;
  42440. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  42441. this.unexpected();
  42442. }
  42443. if (node) {
  42444. if (spaceOrDescendantSelectorNodes) {
  42445. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  42446. _space = _this$convertWhitespa2.space,
  42447. _rawSpace = _this$convertWhitespa2.rawSpace;
  42448. node.spaces.before = _space;
  42449. node.rawSpaceBefore = _rawSpace;
  42450. }
  42451. } else {
  42452. // descendant combinator
  42453. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  42454. _space2 = _this$convertWhitespa3.space,
  42455. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  42456. if (!_rawSpace2) {
  42457. _rawSpace2 = _space2;
  42458. }
  42459. var spaces = {};
  42460. var raws = {
  42461. spaces: {}
  42462. };
  42463. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  42464. spaces.before = _space2.slice(0, _space2.length - 1);
  42465. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  42466. } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
  42467. spaces.after = _space2.slice(1);
  42468. raws.spaces.after = _rawSpace2.slice(1);
  42469. } else {
  42470. raws.value = _rawSpace2;
  42471. }
  42472. node = new _combinator["default"]({
  42473. value: ' ',
  42474. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  42475. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  42476. spaces: spaces,
  42477. raws: raws
  42478. });
  42479. }
  42480. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  42481. node.spaces.after = this.optionalSpace(this.content());
  42482. this.position++;
  42483. }
  42484. return this.newNode(node);
  42485. };
  42486. _proto.comma = function comma() {
  42487. if (this.position === this.tokens.length - 1) {
  42488. this.root.trailingComma = true;
  42489. this.position++;
  42490. return;
  42491. }
  42492. this.current._inferEndPosition();
  42493. var selector = new _selector["default"]({
  42494. source: {
  42495. start: tokenStart(this.tokens[this.position + 1])
  42496. }
  42497. });
  42498. this.current.parent.append(selector);
  42499. this.current = selector;
  42500. this.position++;
  42501. };
  42502. _proto.comment = function comment() {
  42503. var current = this.currToken;
  42504. this.newNode(new _comment["default"]({
  42505. value: this.content(),
  42506. source: getTokenSource(current),
  42507. sourceIndex: current[_tokenize.FIELDS.START_POS]
  42508. }));
  42509. this.position++;
  42510. };
  42511. _proto.error = function error(message, opts) {
  42512. throw this.root.error(message, opts);
  42513. };
  42514. _proto.missingBackslash = function missingBackslash() {
  42515. return this.error('Expected a backslash preceding the semicolon.', {
  42516. index: this.currToken[_tokenize.FIELDS.START_POS]
  42517. });
  42518. };
  42519. _proto.missingParenthesis = function missingParenthesis() {
  42520. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  42521. };
  42522. _proto.missingSquareBracket = function missingSquareBracket() {
  42523. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  42524. };
  42525. _proto.unexpected = function unexpected() {
  42526. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  42527. };
  42528. _proto.namespace = function namespace() {
  42529. var before = this.prevToken && this.content(this.prevToken) || true;
  42530. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  42531. this.position++;
  42532. return this.word(before);
  42533. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  42534. this.position++;
  42535. return this.universal(before);
  42536. }
  42537. };
  42538. _proto.nesting = function nesting() {
  42539. if (this.nextToken) {
  42540. var nextContent = this.content(this.nextToken);
  42541. if (nextContent === "|") {
  42542. this.position++;
  42543. return;
  42544. }
  42545. }
  42546. var current = this.currToken;
  42547. this.newNode(new _nesting["default"]({
  42548. value: this.content(),
  42549. source: getTokenSource(current),
  42550. sourceIndex: current[_tokenize.FIELDS.START_POS]
  42551. }));
  42552. this.position++;
  42553. };
  42554. _proto.parentheses = function parentheses() {
  42555. var last = this.current.last;
  42556. var unbalanced = 1;
  42557. this.position++;
  42558. if (last && last.type === types.PSEUDO) {
  42559. var selector = new _selector["default"]({
  42560. source: {
  42561. start: tokenStart(this.tokens[this.position - 1])
  42562. }
  42563. });
  42564. var cache = this.current;
  42565. last.append(selector);
  42566. this.current = selector;
  42567. while (this.position < this.tokens.length && unbalanced) {
  42568. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  42569. unbalanced++;
  42570. }
  42571. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  42572. unbalanced--;
  42573. }
  42574. if (unbalanced) {
  42575. this.parse();
  42576. } else {
  42577. this.current.source.end = tokenEnd(this.currToken);
  42578. this.current.parent.source.end = tokenEnd(this.currToken);
  42579. this.position++;
  42580. }
  42581. }
  42582. this.current = cache;
  42583. } else {
  42584. // I think this case should be an error. It's used to implement a basic parse of media queries
  42585. // but I don't think it's a good idea.
  42586. var parenStart = this.currToken;
  42587. var parenValue = "(";
  42588. var parenEnd;
  42589. while (this.position < this.tokens.length && unbalanced) {
  42590. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  42591. unbalanced++;
  42592. }
  42593. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  42594. unbalanced--;
  42595. }
  42596. parenEnd = this.currToken;
  42597. parenValue += this.parseParenthesisToken(this.currToken);
  42598. this.position++;
  42599. }
  42600. if (last) {
  42601. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  42602. } else {
  42603. this.newNode(new _string["default"]({
  42604. value: parenValue,
  42605. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  42606. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  42607. }));
  42608. }
  42609. }
  42610. if (unbalanced) {
  42611. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  42612. }
  42613. };
  42614. _proto.pseudo = function pseudo() {
  42615. var _this4 = this;
  42616. var pseudoStr = '';
  42617. var startingToken = this.currToken;
  42618. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  42619. pseudoStr += this.content();
  42620. this.position++;
  42621. }
  42622. if (!this.currToken) {
  42623. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  42624. }
  42625. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  42626. this.splitWord(false, function (first, length) {
  42627. pseudoStr += first;
  42628. _this4.newNode(new _pseudo["default"]({
  42629. value: pseudoStr,
  42630. source: getTokenSourceSpan(startingToken, _this4.currToken),
  42631. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  42632. }));
  42633. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  42634. _this4.error('Misplaced parenthesis.', {
  42635. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  42636. });
  42637. }
  42638. });
  42639. } else {
  42640. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  42641. }
  42642. };
  42643. _proto.space = function space() {
  42644. var content = this.content(); // Handle space before and after the selector
  42645. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  42646. return node.type === 'comment';
  42647. })) {
  42648. this.spaces = this.optionalSpace(content);
  42649. this.position++;
  42650. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  42651. this.current.last.spaces.after = this.optionalSpace(content);
  42652. this.position++;
  42653. } else {
  42654. this.combinator();
  42655. }
  42656. };
  42657. _proto.string = function string() {
  42658. var current = this.currToken;
  42659. this.newNode(new _string["default"]({
  42660. value: this.content(),
  42661. source: getTokenSource(current),
  42662. sourceIndex: current[_tokenize.FIELDS.START_POS]
  42663. }));
  42664. this.position++;
  42665. };
  42666. _proto.universal = function universal(namespace) {
  42667. var nextToken = this.nextToken;
  42668. if (nextToken && this.content(nextToken) === '|') {
  42669. this.position++;
  42670. return this.namespace();
  42671. }
  42672. var current = this.currToken;
  42673. this.newNode(new _universal["default"]({
  42674. value: this.content(),
  42675. source: getTokenSource(current),
  42676. sourceIndex: current[_tokenize.FIELDS.START_POS]
  42677. }), namespace);
  42678. this.position++;
  42679. };
  42680. _proto.splitWord = function splitWord(namespace, firstCallback) {
  42681. var _this5 = this;
  42682. var nextToken = this.nextToken;
  42683. var word = this.content();
  42684. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  42685. this.position++;
  42686. var current = this.content();
  42687. word += current;
  42688. if (current.lastIndexOf('\\') === current.length - 1) {
  42689. var next = this.nextToken;
  42690. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  42691. word += this.requiredSpace(this.content(next));
  42692. this.position++;
  42693. }
  42694. }
  42695. nextToken = this.nextToken;
  42696. }
  42697. var hasClass = indexesOf(word, '.').filter(function (i) {
  42698. // Allow escaped dot within class name
  42699. var escapedDot = word[i - 1] === '\\'; // Allow decimal numbers percent in @keyframes
  42700. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  42701. return !escapedDot && !isKeyframesPercent;
  42702. });
  42703. var hasId = indexesOf(word, '#').filter(function (i) {
  42704. return word[i - 1] !== '\\';
  42705. }); // Eliminate Sass interpolations from the list of id indexes
  42706. var interpolations = indexesOf(word, '#{');
  42707. if (interpolations.length) {
  42708. hasId = hasId.filter(function (hashIndex) {
  42709. return !~interpolations.indexOf(hashIndex);
  42710. });
  42711. }
  42712. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  42713. indices.forEach(function (ind, i) {
  42714. var index = indices[i + 1] || word.length;
  42715. var value = word.slice(ind, index);
  42716. if (i === 0 && firstCallback) {
  42717. return firstCallback.call(_this5, value, indices.length);
  42718. }
  42719. var node;
  42720. var current = _this5.currToken;
  42721. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  42722. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  42723. if (~hasClass.indexOf(ind)) {
  42724. var classNameOpts = {
  42725. value: value.slice(1),
  42726. source: source,
  42727. sourceIndex: sourceIndex
  42728. };
  42729. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  42730. } else if (~hasId.indexOf(ind)) {
  42731. var idOpts = {
  42732. value: value.slice(1),
  42733. source: source,
  42734. sourceIndex: sourceIndex
  42735. };
  42736. node = new _id["default"](unescapeProp(idOpts, "value"));
  42737. } else {
  42738. var tagOpts = {
  42739. value: value,
  42740. source: source,
  42741. sourceIndex: sourceIndex
  42742. };
  42743. unescapeProp(tagOpts, "value");
  42744. node = new _tag["default"](tagOpts);
  42745. }
  42746. _this5.newNode(node, namespace); // Ensure that the namespace is used only once
  42747. namespace = null;
  42748. });
  42749. this.position++;
  42750. };
  42751. _proto.word = function word(namespace) {
  42752. var nextToken = this.nextToken;
  42753. if (nextToken && this.content(nextToken) === '|') {
  42754. this.position++;
  42755. return this.namespace();
  42756. }
  42757. return this.splitWord(namespace);
  42758. };
  42759. _proto.loop = function loop() {
  42760. while (this.position < this.tokens.length) {
  42761. this.parse(true);
  42762. }
  42763. this.current._inferEndPosition();
  42764. return this.root;
  42765. };
  42766. _proto.parse = function parse(throwOnParenthesis) {
  42767. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  42768. case tokens.space:
  42769. this.space();
  42770. break;
  42771. case tokens.comment:
  42772. this.comment();
  42773. break;
  42774. case tokens.openParenthesis:
  42775. this.parentheses();
  42776. break;
  42777. case tokens.closeParenthesis:
  42778. if (throwOnParenthesis) {
  42779. this.missingParenthesis();
  42780. }
  42781. break;
  42782. case tokens.openSquare:
  42783. this.attribute();
  42784. break;
  42785. case tokens.dollar:
  42786. case tokens.caret:
  42787. case tokens.equals:
  42788. case tokens.word:
  42789. this.word();
  42790. break;
  42791. case tokens.colon:
  42792. this.pseudo();
  42793. break;
  42794. case tokens.comma:
  42795. this.comma();
  42796. break;
  42797. case tokens.asterisk:
  42798. this.universal();
  42799. break;
  42800. case tokens.ampersand:
  42801. this.nesting();
  42802. break;
  42803. case tokens.slash:
  42804. case tokens.combinator:
  42805. this.combinator();
  42806. break;
  42807. case tokens.str:
  42808. this.string();
  42809. break;
  42810. // These cases throw; no break needed.
  42811. case tokens.closeSquare:
  42812. this.missingSquareBracket();
  42813. case tokens.semicolon:
  42814. this.missingBackslash();
  42815. default:
  42816. this.unexpected();
  42817. }
  42818. }
  42819. /**
  42820. * Helpers
  42821. */
  42822. ;
  42823. _proto.expected = function expected(description, index, found) {
  42824. if (Array.isArray(description)) {
  42825. var last = description.pop();
  42826. description = description.join(', ') + " or " + last;
  42827. }
  42828. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  42829. if (!found) {
  42830. return this.error("Expected " + an + " " + description + ".", {
  42831. index: index
  42832. });
  42833. }
  42834. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  42835. index: index
  42836. });
  42837. };
  42838. _proto.requiredSpace = function requiredSpace(space) {
  42839. return this.options.lossy ? ' ' : space;
  42840. };
  42841. _proto.optionalSpace = function optionalSpace(space) {
  42842. return this.options.lossy ? '' : space;
  42843. };
  42844. _proto.lossySpace = function lossySpace(space, required) {
  42845. if (this.options.lossy) {
  42846. return required ? ' ' : '';
  42847. } else {
  42848. return space;
  42849. }
  42850. };
  42851. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  42852. var content = this.content(token);
  42853. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  42854. return this.requiredSpace(content);
  42855. } else {
  42856. return content;
  42857. }
  42858. };
  42859. _proto.newNode = function newNode(node, namespace) {
  42860. if (namespace) {
  42861. if (/^ +$/.test(namespace)) {
  42862. if (!this.options.lossy) {
  42863. this.spaces = (this.spaces || '') + namespace;
  42864. }
  42865. namespace = true;
  42866. }
  42867. node.namespace = namespace;
  42868. unescapeProp(node, "namespace");
  42869. }
  42870. if (this.spaces) {
  42871. node.spaces.before = this.spaces;
  42872. this.spaces = '';
  42873. }
  42874. return this.current.append(node);
  42875. };
  42876. _proto.content = function content(token) {
  42877. if (token === void 0) {
  42878. token = this.currToken;
  42879. }
  42880. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  42881. };
  42882. /**
  42883. * returns the index of the next non-whitespace, non-comment token.
  42884. * returns -1 if no meaningful token is found.
  42885. */
  42886. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  42887. if (startPosition === void 0) {
  42888. startPosition = this.position + 1;
  42889. }
  42890. var searchPosition = startPosition;
  42891. while (searchPosition < this.tokens.length) {
  42892. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  42893. searchPosition++;
  42894. continue;
  42895. } else {
  42896. return searchPosition;
  42897. }
  42898. }
  42899. return -1;
  42900. };
  42901. _createClass(Parser, [{
  42902. key: "currToken",
  42903. get: function get() {
  42904. return this.tokens[this.position];
  42905. }
  42906. }, {
  42907. key: "nextToken",
  42908. get: function get() {
  42909. return this.tokens[this.position + 1];
  42910. }
  42911. }, {
  42912. key: "prevToken",
  42913. get: function get() {
  42914. return this.tokens[this.position - 1];
  42915. }
  42916. }]);
  42917. return Parser;
  42918. }();
  42919. exports["default"] = Parser;
  42920. module.exports = exports.default;
  42921. });
  42922. var processor$1 = createCommonjsModule(function (module, exports) {
  42923. exports.__esModule = true;
  42924. exports["default"] = void 0;
  42925. var _parser = _interopRequireDefault(parser$1);
  42926. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  42927. var Processor = /*#__PURE__*/function () {
  42928. function Processor(func, options) {
  42929. this.func = func || function noop() {};
  42930. this.funcRes = null;
  42931. this.options = options;
  42932. }
  42933. var _proto = Processor.prototype;
  42934. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  42935. if (options === void 0) {
  42936. options = {};
  42937. }
  42938. var merged = Object.assign({}, this.options, options);
  42939. if (merged.updateSelector === false) {
  42940. return false;
  42941. } else {
  42942. return typeof rule !== "string";
  42943. }
  42944. };
  42945. _proto._isLossy = function _isLossy(options) {
  42946. if (options === void 0) {
  42947. options = {};
  42948. }
  42949. var merged = Object.assign({}, this.options, options);
  42950. if (merged.lossless === false) {
  42951. return true;
  42952. } else {
  42953. return false;
  42954. }
  42955. };
  42956. _proto._root = function _root(rule, options) {
  42957. if (options === void 0) {
  42958. options = {};
  42959. }
  42960. var parser = new _parser["default"](rule, this._parseOptions(options));
  42961. return parser.root;
  42962. };
  42963. _proto._parseOptions = function _parseOptions(options) {
  42964. return {
  42965. lossy: this._isLossy(options)
  42966. };
  42967. };
  42968. _proto._run = function _run(rule, options) {
  42969. var _this = this;
  42970. if (options === void 0) {
  42971. options = {};
  42972. }
  42973. return new Promise(function (resolve, reject) {
  42974. try {
  42975. var root = _this._root(rule, options);
  42976. Promise.resolve(_this.func(root)).then(function (transform) {
  42977. var string = undefined;
  42978. if (_this._shouldUpdateSelector(rule, options)) {
  42979. string = root.toString();
  42980. rule.selector = string;
  42981. }
  42982. return {
  42983. transform: transform,
  42984. root: root,
  42985. string: string
  42986. };
  42987. }).then(resolve, reject);
  42988. } catch (e) {
  42989. reject(e);
  42990. return;
  42991. }
  42992. });
  42993. };
  42994. _proto._runSync = function _runSync(rule, options) {
  42995. if (options === void 0) {
  42996. options = {};
  42997. }
  42998. var root = this._root(rule, options);
  42999. var transform = this.func(root);
  43000. if (transform && typeof transform.then === "function") {
  43001. throw new Error("Selector processor returned a promise to a synchronous call.");
  43002. }
  43003. var string = undefined;
  43004. if (options.updateSelector && typeof rule !== "string") {
  43005. string = root.toString();
  43006. rule.selector = string;
  43007. }
  43008. return {
  43009. transform: transform,
  43010. root: root,
  43011. string: string
  43012. };
  43013. }
  43014. /**
  43015. * Process rule into a selector AST.
  43016. *
  43017. * @param rule {postcss.Rule | string} The css selector to be processed
  43018. * @param options The options for processing
  43019. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  43020. */
  43021. ;
  43022. _proto.ast = function ast(rule, options) {
  43023. return this._run(rule, options).then(function (result) {
  43024. return result.root;
  43025. });
  43026. }
  43027. /**
  43028. * Process rule into a selector AST synchronously.
  43029. *
  43030. * @param rule {postcss.Rule | string} The css selector to be processed
  43031. * @param options The options for processing
  43032. * @returns {parser.Root} The AST of the selector after processing it.
  43033. */
  43034. ;
  43035. _proto.astSync = function astSync(rule, options) {
  43036. return this._runSync(rule, options).root;
  43037. }
  43038. /**
  43039. * Process a selector into a transformed value asynchronously
  43040. *
  43041. * @param rule {postcss.Rule | string} The css selector to be processed
  43042. * @param options The options for processing
  43043. * @returns {Promise<any>} The value returned by the processor.
  43044. */
  43045. ;
  43046. _proto.transform = function transform(rule, options) {
  43047. return this._run(rule, options).then(function (result) {
  43048. return result.transform;
  43049. });
  43050. }
  43051. /**
  43052. * Process a selector into a transformed value synchronously.
  43053. *
  43054. * @param rule {postcss.Rule | string} The css selector to be processed
  43055. * @param options The options for processing
  43056. * @returns {any} The value returned by the processor.
  43057. */
  43058. ;
  43059. _proto.transformSync = function transformSync(rule, options) {
  43060. return this._runSync(rule, options).transform;
  43061. }
  43062. /**
  43063. * Process a selector into a new selector string asynchronously.
  43064. *
  43065. * @param rule {postcss.Rule | string} The css selector to be processed
  43066. * @param options The options for processing
  43067. * @returns {string} the selector after processing.
  43068. */
  43069. ;
  43070. _proto.process = function process(rule, options) {
  43071. return this._run(rule, options).then(function (result) {
  43072. return result.string || result.root.toString();
  43073. });
  43074. }
  43075. /**
  43076. * Process a selector into a new selector string synchronously.
  43077. *
  43078. * @param rule {postcss.Rule | string} The css selector to be processed
  43079. * @param options The options for processing
  43080. * @returns {string} the selector after processing.
  43081. */
  43082. ;
  43083. _proto.processSync = function processSync(rule, options) {
  43084. var result = this._runSync(rule, options);
  43085. return result.string || result.root.toString();
  43086. };
  43087. return Processor;
  43088. }();
  43089. exports["default"] = Processor;
  43090. module.exports = exports.default;
  43091. });
  43092. /*@__PURE__*/getDefaultExportFromCjs(processor$1);
  43093. var constructors = createCommonjsModule(function (module, exports) {
  43094. exports.__esModule = true;
  43095. exports.universal = exports.tag = exports.string = exports.selector = exports.root = exports.pseudo = exports.nesting = exports.id = exports.comment = exports.combinator = exports.className = exports.attribute = void 0;
  43096. var _attribute = _interopRequireDefault(attribute);
  43097. var _className = _interopRequireDefault(className);
  43098. var _combinator = _interopRequireDefault(combinator);
  43099. var _comment = _interopRequireDefault(comment$1);
  43100. var _id = _interopRequireDefault(id);
  43101. var _nesting = _interopRequireDefault(nesting);
  43102. var _pseudo = _interopRequireDefault(pseudo);
  43103. var _root = _interopRequireDefault(root$1);
  43104. var _selector = _interopRequireDefault(selector);
  43105. var _string = _interopRequireDefault(string);
  43106. var _tag = _interopRequireDefault(tag);
  43107. var _universal = _interopRequireDefault(universal);
  43108. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  43109. var attribute$1 = function attribute(opts) {
  43110. return new _attribute["default"](opts);
  43111. };
  43112. exports.attribute = attribute$1;
  43113. var className$1 = function className(opts) {
  43114. return new _className["default"](opts);
  43115. };
  43116. exports.className = className$1;
  43117. var combinator$1 = function combinator(opts) {
  43118. return new _combinator["default"](opts);
  43119. };
  43120. exports.combinator = combinator$1;
  43121. var comment = function comment(opts) {
  43122. return new _comment["default"](opts);
  43123. };
  43124. exports.comment = comment;
  43125. var id$1 = function id(opts) {
  43126. return new _id["default"](opts);
  43127. };
  43128. exports.id = id$1;
  43129. var nesting$1 = function nesting(opts) {
  43130. return new _nesting["default"](opts);
  43131. };
  43132. exports.nesting = nesting$1;
  43133. var pseudo$1 = function pseudo(opts) {
  43134. return new _pseudo["default"](opts);
  43135. };
  43136. exports.pseudo = pseudo$1;
  43137. var root = function root(opts) {
  43138. return new _root["default"](opts);
  43139. };
  43140. exports.root = root;
  43141. var selector$1 = function selector(opts) {
  43142. return new _selector["default"](opts);
  43143. };
  43144. exports.selector = selector$1;
  43145. var string$1 = function string(opts) {
  43146. return new _string["default"](opts);
  43147. };
  43148. exports.string = string$1;
  43149. var tag$1 = function tag(opts) {
  43150. return new _tag["default"](opts);
  43151. };
  43152. exports.tag = tag$1;
  43153. var universal$1 = function universal(opts) {
  43154. return new _universal["default"](opts);
  43155. };
  43156. exports.universal = universal$1;
  43157. });
  43158. var guards = createCommonjsModule(function (module, exports) {
  43159. exports.__esModule = true;
  43160. exports.isNode = isNode;
  43161. exports.isPseudoElement = isPseudoElement;
  43162. exports.isPseudoClass = isPseudoClass;
  43163. exports.isContainer = isContainer;
  43164. exports.isNamespace = isNamespace;
  43165. exports.isUniversal = exports.isTag = exports.isString = exports.isSelector = exports.isRoot = exports.isPseudo = exports.isNesting = exports.isIdentifier = exports.isComment = exports.isCombinator = exports.isClassName = exports.isAttribute = void 0;
  43166. var _IS_TYPE;
  43167. var IS_TYPE = (_IS_TYPE = {}, _IS_TYPE[types$1.ATTRIBUTE] = true, _IS_TYPE[types$1.CLASS] = true, _IS_TYPE[types$1.COMBINATOR] = true, _IS_TYPE[types$1.COMMENT] = true, _IS_TYPE[types$1.ID] = true, _IS_TYPE[types$1.NESTING] = true, _IS_TYPE[types$1.PSEUDO] = true, _IS_TYPE[types$1.ROOT] = true, _IS_TYPE[types$1.SELECTOR] = true, _IS_TYPE[types$1.STRING] = true, _IS_TYPE[types$1.TAG] = true, _IS_TYPE[types$1.UNIVERSAL] = true, _IS_TYPE);
  43168. function isNode(node) {
  43169. return typeof node === "object" && IS_TYPE[node.type];
  43170. }
  43171. function isNodeType(type, node) {
  43172. return isNode(node) && node.type === type;
  43173. }
  43174. var isAttribute = isNodeType.bind(null, types$1.ATTRIBUTE);
  43175. exports.isAttribute = isAttribute;
  43176. var isClassName = isNodeType.bind(null, types$1.CLASS);
  43177. exports.isClassName = isClassName;
  43178. var isCombinator = isNodeType.bind(null, types$1.COMBINATOR);
  43179. exports.isCombinator = isCombinator;
  43180. var isComment = isNodeType.bind(null, types$1.COMMENT);
  43181. exports.isComment = isComment;
  43182. var isIdentifier = isNodeType.bind(null, types$1.ID);
  43183. exports.isIdentifier = isIdentifier;
  43184. var isNesting = isNodeType.bind(null, types$1.NESTING);
  43185. exports.isNesting = isNesting;
  43186. var isPseudo = isNodeType.bind(null, types$1.PSEUDO);
  43187. exports.isPseudo = isPseudo;
  43188. var isRoot = isNodeType.bind(null, types$1.ROOT);
  43189. exports.isRoot = isRoot;
  43190. var isSelector = isNodeType.bind(null, types$1.SELECTOR);
  43191. exports.isSelector = isSelector;
  43192. var isString = isNodeType.bind(null, types$1.STRING);
  43193. exports.isString = isString;
  43194. var isTag = isNodeType.bind(null, types$1.TAG);
  43195. exports.isTag = isTag;
  43196. var isUniversal = isNodeType.bind(null, types$1.UNIVERSAL);
  43197. exports.isUniversal = isUniversal;
  43198. function isPseudoElement(node) {
  43199. return isPseudo(node) && node.value && (node.value.startsWith("::") || node.value.toLowerCase() === ":before" || node.value.toLowerCase() === ":after");
  43200. }
  43201. function isPseudoClass(node) {
  43202. return isPseudo(node) && !isPseudoElement(node);
  43203. }
  43204. function isContainer(node) {
  43205. return !!(isNode(node) && node.walk);
  43206. }
  43207. function isNamespace(node) {
  43208. return isAttribute(node) || isTag(node);
  43209. }
  43210. });
  43211. var selectors = createCommonjsModule(function (module, exports) {
  43212. exports.__esModule = true;
  43213. Object.keys(types$1).forEach(function (key) {
  43214. if (key === "default" || key === "__esModule") return;
  43215. if (key in exports && exports[key] === types$1[key]) return;
  43216. exports[key] = types$1[key];
  43217. });
  43218. Object.keys(constructors).forEach(function (key) {
  43219. if (key === "default" || key === "__esModule") return;
  43220. if (key in exports && exports[key] === constructors[key]) return;
  43221. exports[key] = constructors[key];
  43222. });
  43223. Object.keys(guards).forEach(function (key) {
  43224. if (key === "default" || key === "__esModule") return;
  43225. if (key in exports && exports[key] === guards[key]) return;
  43226. exports[key] = guards[key];
  43227. });
  43228. });
  43229. var dist = createCommonjsModule(function (module, exports) {
  43230. exports.__esModule = true;
  43231. exports["default"] = void 0;
  43232. var _processor = _interopRequireDefault(processor$1);
  43233. var selectors$1 = _interopRequireWildcard(selectors);
  43234. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  43235. 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; }
  43236. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  43237. var parser = function parser(processor) {
  43238. return new _processor["default"](processor);
  43239. };
  43240. Object.assign(parser, selectors$1);
  43241. delete parser.__esModule;
  43242. var _default = parser;
  43243. exports["default"] = _default;
  43244. module.exports = exports.default;
  43245. });
  43246. var selectorParser = /*@__PURE__*/getDefaultExportFromCjs(dist);
  43247. const animationNameRE = /^(-\w+-)?animation-name$/;
  43248. const animationRE = /^(-\w+-)?animation$/;
  43249. const scopedPlugin = (id = '') => {
  43250. const keyframes = Object.create(null);
  43251. const shortId = id.replace(/^data-v-/, '');
  43252. return {
  43253. postcssPlugin: 'vue-sfc-scoped',
  43254. Rule(rule) {
  43255. processRule(id, rule);
  43256. },
  43257. AtRule(node) {
  43258. if (/-?keyframes$/.test(node.name) &&
  43259. !node.params.endsWith(`-${shortId}`)) {
  43260. // register keyframes
  43261. keyframes[node.params] = node.params = node.params + '-' + shortId;
  43262. }
  43263. },
  43264. OnceExit(root) {
  43265. if (Object.keys(keyframes).length) {
  43266. // If keyframes are found in this <style>, find and rewrite animation names
  43267. // in declarations.
  43268. // Caveat: this only works for keyframes and animation rules in the same
  43269. // <style> element.
  43270. // individual animation-name declaration
  43271. root.walkDecls(decl => {
  43272. if (animationNameRE.test(decl.prop)) {
  43273. decl.value = decl.value
  43274. .split(',')
  43275. .map(v => keyframes[v.trim()] || v.trim())
  43276. .join(',');
  43277. }
  43278. // shorthand
  43279. if (animationRE.test(decl.prop)) {
  43280. decl.value = decl.value
  43281. .split(',')
  43282. .map(v => {
  43283. const vals = v.trim().split(/\s+/);
  43284. const i = vals.findIndex(val => keyframes[val]);
  43285. if (i !== -1) {
  43286. vals.splice(i, 1, keyframes[vals[i]]);
  43287. return vals.join(' ');
  43288. }
  43289. else {
  43290. return v;
  43291. }
  43292. })
  43293. .join(',');
  43294. }
  43295. });
  43296. }
  43297. }
  43298. };
  43299. };
  43300. const processedRules = new WeakSet();
  43301. function processRule(id, rule) {
  43302. if (processedRules.has(rule) ||
  43303. (rule.parent &&
  43304. rule.parent.type === 'atrule' &&
  43305. /-?keyframes$/.test(rule.parent.name))) {
  43306. return;
  43307. }
  43308. processedRules.add(rule);
  43309. rule.selector = selectorParser(selectorRoot => {
  43310. selectorRoot.each(selector => {
  43311. rewriteSelector(id, selector, selectorRoot);
  43312. });
  43313. }).processSync(rule.selector);
  43314. }
  43315. function rewriteSelector(id, selector, selectorRoot, slotted = false) {
  43316. let node = null;
  43317. let shouldInject = true;
  43318. // find the last child node to insert attribute selector
  43319. selector.each(n => {
  43320. // DEPRECATED ">>>" and "/deep/" combinator
  43321. if (n.type === 'combinator' &&
  43322. (n.value === '>>>' || n.value === '/deep/')) {
  43323. n.value = ' ';
  43324. n.spaces.before = n.spaces.after = '';
  43325. warn(`the >>> and /deep/ combinators have been deprecated. ` +
  43326. `Use :deep() instead.`);
  43327. return false;
  43328. }
  43329. if (n.type === 'pseudo') {
  43330. const { value } = n;
  43331. // deep: inject [id] attribute at the node before the ::v-deep
  43332. // combinator.
  43333. if (value === ':deep' || value === '::v-deep') {
  43334. if (n.nodes.length) {
  43335. // .foo ::v-deep(.bar) -> .foo[xxxxxxx] .bar
  43336. // replace the current node with ::v-deep's inner selector
  43337. let last = n;
  43338. n.nodes[0].each(ss => {
  43339. selector.insertAfter(last, ss);
  43340. last = ss;
  43341. });
  43342. // insert a space combinator before if it doesn't already have one
  43343. const prev = selector.at(selector.index(n) - 1);
  43344. if (!prev || !isSpaceCombinator(prev)) {
  43345. selector.insertAfter(n, selectorParser.combinator({
  43346. value: ' '
  43347. }));
  43348. }
  43349. selector.removeChild(n);
  43350. }
  43351. else {
  43352. // DEPRECATED usage
  43353. // .foo ::v-deep .bar -> .foo[xxxxxxx] .bar
  43354. warn(`::v-deep usage as a combinator has ` +
  43355. `been deprecated. Use :deep(<inner-selector>) instead.`);
  43356. const prev = selector.at(selector.index(n) - 1);
  43357. if (prev && isSpaceCombinator(prev)) {
  43358. selector.removeChild(prev);
  43359. }
  43360. selector.removeChild(n);
  43361. }
  43362. return false;
  43363. }
  43364. // slot: use selector inside `::v-slotted` and inject [id + '-s']
  43365. // instead.
  43366. // ::v-slotted(.foo) -> .foo[xxxxxxx-s]
  43367. if (value === ':slotted' || value === '::v-slotted') {
  43368. rewriteSelector(id, n.nodes[0], selectorRoot, true /* slotted */);
  43369. let last = n;
  43370. n.nodes[0].each(ss => {
  43371. selector.insertAfter(last, ss);
  43372. last = ss;
  43373. });
  43374. // selector.insertAfter(n, n.nodes[0])
  43375. selector.removeChild(n);
  43376. // since slotted attribute already scopes the selector there's no
  43377. // need for the non-slot attribute.
  43378. shouldInject = false;
  43379. return false;
  43380. }
  43381. // global: replace with inner selector and do not inject [id].
  43382. // ::v-global(.foo) -> .foo
  43383. if (value === ':global' || value === '::v-global') {
  43384. selectorRoot.insertAfter(selector, n.nodes[0]);
  43385. selectorRoot.removeChild(selector);
  43386. return false;
  43387. }
  43388. }
  43389. if (n.type !== 'pseudo' && n.type !== 'combinator') {
  43390. node = n;
  43391. }
  43392. });
  43393. if (node) {
  43394. node.spaces.after = '';
  43395. }
  43396. else {
  43397. // For deep selectors & standalone pseudo selectors,
  43398. // the attribute selectors are prepended rather than appended.
  43399. // So all leading spaces must be eliminated to avoid problems.
  43400. selector.first.spaces.before = '';
  43401. }
  43402. if (shouldInject) {
  43403. const idToAdd = slotted ? id + '-s' : id;
  43404. selector.insertAfter(
  43405. // If node is null it means we need to inject [id] at the start
  43406. // insertAfter can handle `null` here
  43407. node, selectorParser.attribute({
  43408. attribute: idToAdd,
  43409. value: idToAdd,
  43410. raws: {},
  43411. quoteMark: `"`
  43412. }));
  43413. }
  43414. }
  43415. function isSpaceCombinator(node) {
  43416. return node.type === 'combinator' && /^\s+$/.test(node.value);
  43417. }
  43418. scopedPlugin.postcss = true;
  43419. var SourceMapConsumer$7 = sourceMap.SourceMapConsumer;
  43420. var SourceMapGenerator$9 = sourceMap.SourceMapGenerator;
  43421. var mergeSourceMap = merge$1;
  43422. /**
  43423. * Merge old source map and new source map and return merged.
  43424. * If old or new source map value is falsy, return another one as it is.
  43425. *
  43426. * @param {object|string} [oldMap] old source map object
  43427. * @param {object|string} [newmap] new source map object
  43428. * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
  43429. */
  43430. function merge$1(oldMap, newMap) {
  43431. if (!oldMap) return newMap
  43432. if (!newMap) return oldMap
  43433. var oldMapConsumer = new SourceMapConsumer$7(oldMap);
  43434. var newMapConsumer = new SourceMapConsumer$7(newMap);
  43435. var mergedMapGenerator = new SourceMapGenerator$9();
  43436. // iterate on new map and overwrite original position of new map with one of old map
  43437. newMapConsumer.eachMapping(function(m) {
  43438. // pass when `originalLine` is null.
  43439. // It occurs in case that the node does not have origin in original code.
  43440. if (m.originalLine == null) return
  43441. var origPosInOldMap = oldMapConsumer.originalPositionFor({
  43442. line: m.originalLine,
  43443. column: m.originalColumn
  43444. });
  43445. if (origPosInOldMap.source == null) return
  43446. mergedMapGenerator.addMapping({
  43447. original: {
  43448. line: origPosInOldMap.line,
  43449. column: origPosInOldMap.column
  43450. },
  43451. generated: {
  43452. line: m.generatedLine,
  43453. column: m.generatedColumn
  43454. },
  43455. source: origPosInOldMap.source,
  43456. name: origPosInOldMap.name
  43457. });
  43458. });
  43459. var consumers = [oldMapConsumer, newMapConsumer];
  43460. consumers.forEach(function(consumer) {
  43461. consumer.sources.forEach(function(sourceFile) {
  43462. mergedMapGenerator._sources.add(sourceFile);
  43463. var sourceContent = consumer.sourceContentFor(sourceFile);
  43464. if (sourceContent != null) {
  43465. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  43466. }
  43467. });
  43468. });
  43469. mergedMapGenerator._sourceRoot = oldMap.sourceRoot;
  43470. mergedMapGenerator._file = oldMap.file;
  43471. return JSON.parse(mergedMapGenerator.toString())
  43472. }
  43473. // .scss/.sass processor
  43474. const scss = (source, map, options, load = require) => {
  43475. const nodeSass = load('sass');
  43476. const finalOptions = Object.assign(Object.assign({}, options), { data: getSource(source, options.filename, options.additionalData), file: options.filename, outFile: options.filename, sourceMap: !!map });
  43477. try {
  43478. const result = nodeSass.renderSync(finalOptions);
  43479. const dependencies = result.stats.includedFiles;
  43480. if (map) {
  43481. return {
  43482. code: result.css.toString(),
  43483. map: mergeSourceMap(map, JSON.parse(result.map.toString())),
  43484. errors: [],
  43485. dependencies
  43486. };
  43487. }
  43488. return { code: result.css.toString(), errors: [], dependencies };
  43489. }
  43490. catch (e) {
  43491. return { code: '', errors: [e], dependencies: [] };
  43492. }
  43493. };
  43494. const sass = (source, map, options, load) => scss(source, map, Object.assign(Object.assign({}, options), { indentedSyntax: true }), load);
  43495. // .less
  43496. const less = (source, map, options, load = require) => {
  43497. const nodeLess = load('less');
  43498. let result;
  43499. let error = null;
  43500. nodeLess.render(getSource(source, options.filename, options.additionalData), Object.assign(Object.assign({}, options), { syncImport: true }), (err, output) => {
  43501. error = err;
  43502. result = output;
  43503. });
  43504. if (error)
  43505. return { code: '', errors: [error], dependencies: [] };
  43506. const dependencies = result.imports;
  43507. if (map) {
  43508. return {
  43509. code: result.css.toString(),
  43510. map: mergeSourceMap(map, result.map),
  43511. errors: [],
  43512. dependencies: dependencies
  43513. };
  43514. }
  43515. return {
  43516. code: result.css.toString(),
  43517. errors: [],
  43518. dependencies: dependencies
  43519. };
  43520. };
  43521. // .styl
  43522. const styl = (source, map, options, load = require) => {
  43523. const nodeStylus = load('stylus');
  43524. try {
  43525. const ref = nodeStylus(source);
  43526. Object.keys(options).forEach(key => ref.set(key, options[key]));
  43527. if (map)
  43528. ref.set('sourcemap', { inline: false, comment: false });
  43529. const result = ref.render();
  43530. const dependencies = ref.deps();
  43531. if (map) {
  43532. return {
  43533. code: result,
  43534. map: mergeSourceMap(map, ref.sourcemap),
  43535. errors: [],
  43536. dependencies
  43537. };
  43538. }
  43539. return { code: result, errors: [], dependencies };
  43540. }
  43541. catch (e) {
  43542. return { code: '', errors: [e], dependencies: [] };
  43543. }
  43544. };
  43545. function getSource(source, filename, additionalData) {
  43546. if (!additionalData)
  43547. return source;
  43548. if (isFunction(additionalData)) {
  43549. return additionalData(source, filename);
  43550. }
  43551. return additionalData + source;
  43552. }
  43553. const processors = {
  43554. less,
  43555. sass,
  43556. scss,
  43557. styl,
  43558. stylus: styl
  43559. };
  43560. function compileStyle(options) {
  43561. return doCompileStyle(Object.assign(Object.assign({}, options), { isAsync: false }));
  43562. }
  43563. function compileStyleAsync(options) {
  43564. return doCompileStyle(Object.assign(Object.assign({}, options), { isAsync: true }));
  43565. }
  43566. function doCompileStyle(options) {
  43567. const { filename, id, scoped = false, trim = true, isProd = false, modules = false, modulesOptions = {}, preprocessLang, postcssOptions, postcssPlugins } = options;
  43568. const preprocessor = preprocessLang && processors[preprocessLang];
  43569. const preProcessedSource = preprocessor && preprocess$1(options, preprocessor);
  43570. const map = preProcessedSource
  43571. ? preProcessedSource.map
  43572. : options.inMap || options.map;
  43573. const source = preProcessedSource ? preProcessedSource.code : options.source;
  43574. const shortId = id.replace(/^data-v-/, '');
  43575. const longId = `data-v-${shortId}`;
  43576. const plugins = (postcssPlugins || []).slice();
  43577. plugins.unshift(cssVarsPlugin({ id: shortId, isProd }));
  43578. if (trim) {
  43579. plugins.push(trimPlugin());
  43580. }
  43581. if (scoped) {
  43582. plugins.push(scopedPlugin(longId));
  43583. }
  43584. let cssModules;
  43585. if (modules) {
  43586. {
  43587. throw new Error('[@vue/compiler-sfc] `modules` option is not supported in the browser build.');
  43588. }
  43589. }
  43590. const postCSSOptions = Object.assign(Object.assign({}, postcssOptions), { to: filename, from: filename });
  43591. if (map) {
  43592. postCSSOptions.map = {
  43593. inline: false,
  43594. annotation: false,
  43595. prev: map
  43596. };
  43597. }
  43598. let result;
  43599. let code;
  43600. let outMap;
  43601. // stylus output include plain css. so need remove the repeat item
  43602. const dependencies = new Set(preProcessedSource ? preProcessedSource.dependencies : []);
  43603. // sass has filename self when provided filename option
  43604. dependencies.delete(filename);
  43605. const errors = [];
  43606. if (preProcessedSource && preProcessedSource.errors.length) {
  43607. errors.push(...preProcessedSource.errors);
  43608. }
  43609. const recordPlainCssDependencies = (messages) => {
  43610. messages.forEach(msg => {
  43611. if (msg.type === 'dependency') {
  43612. // postcss output path is absolute position path
  43613. dependencies.add(msg.file);
  43614. }
  43615. });
  43616. return dependencies;
  43617. };
  43618. try {
  43619. result = postcss_1(plugins).process(source, postCSSOptions);
  43620. // In async mode, return a promise.
  43621. if (options.isAsync) {
  43622. return result
  43623. .then(result => ({
  43624. code: result.css || '',
  43625. map: result.map && result.map.toJSON(),
  43626. errors,
  43627. modules: cssModules,
  43628. rawResult: result,
  43629. dependencies: recordPlainCssDependencies(result.messages)
  43630. }))
  43631. .catch(error => ({
  43632. code: '',
  43633. map: undefined,
  43634. errors: [...errors, error],
  43635. rawResult: undefined,
  43636. dependencies
  43637. }));
  43638. }
  43639. recordPlainCssDependencies(result.messages);
  43640. // force synchronous transform (we know we only have sync plugins)
  43641. code = result.css;
  43642. outMap = result.map;
  43643. }
  43644. catch (e) {
  43645. errors.push(e);
  43646. }
  43647. return {
  43648. code: code || ``,
  43649. map: outMap && outMap.toJSON(),
  43650. errors,
  43651. rawResult: result,
  43652. dependencies
  43653. };
  43654. }
  43655. function preprocess$1(options, preprocessor) {
  43656. if (!options.preprocessCustomRequire) {
  43657. throw new Error(`[@vue/compiler-sfc] Style preprocessing in the browser build must ` +
  43658. `provide the \`preprocessCustomRequire\` option to return the in-browser ` +
  43659. `version of the preprocessor.`);
  43660. }
  43661. return preprocessor(options.source, options.inMap || options.map, Object.assign({ filename: options.filename }, options.preprocessOptions), options.preprocessCustomRequire);
  43662. }
  43663. // API
  43664. const walk$2 = walk$1;
  43665. export { MagicString, parse_1 as babelParse, compileScript, compileStyle, compileStyleAsync, compileTemplate, extractIdentifiers, generateCodeFrame, isInDestructureAssignment, isStaticProperty, parse$4 as parse, rewriteDefault, shouldTransform as shouldTransformRef, transform$1 as transformRef, transformAST as transformRefAST, walk$2 as walk, walkIdentifiers };