compiler-sfc.esm-browser.js 1.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966
  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 /* TEXT */]: `TEXT`,
  21. [2 /* CLASS */]: `CLASS`,
  22. [4 /* STYLE */]: `STYLE`,
  23. [8 /* PROPS */]: `PROPS`,
  24. [16 /* FULL_PROPS */]: `FULL_PROPS`,
  25. [32 /* HYDRATE_EVENTS */]: `HYDRATE_EVENTS`,
  26. [64 /* STABLE_FRAGMENT */]: `STABLE_FRAGMENT`,
  27. [128 /* KEYED_FRAGMENT */]: `KEYED_FRAGMENT`,
  28. [256 /* UNKEYED_FRAGMENT */]: `UNKEYED_FRAGMENT`,
  29. [512 /* NEED_PATCH */]: `NEED_PATCH`,
  30. [1024 /* DYNAMIC_SLOTS */]: `DYNAMIC_SLOTS`,
  31. [2048 /* DEV_ROOT_FRAGMENT */]: `DEV_ROOT_FRAGMENT`,
  32. [-1 /* HOISTED */]: `HOISTED`,
  33. [-2 /* BAIL */]: `BAIL`
  34. };
  35. /**
  36. * Dev only
  37. */
  38. const slotFlagsText = {
  39. [1 /* STABLE */]: 'STABLE',
  40. [2 /* DYNAMIC */]: 'DYNAMIC',
  41. [3 /* 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. /**
  91. * On the client we only need to offer special cases for boolean attributes that
  92. * have different names from their corresponding dom properties:
  93. * - itemscope -> N/A
  94. * - allowfullscreen -> allowFullscreen
  95. * - formnovalidate -> formNoValidate
  96. * - ismap -> isMap
  97. * - nomodule -> noModule
  98. * - novalidate -> noValidate
  99. * - readonly -> readOnly
  100. */
  101. const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
  102. /**
  103. * The full list is needed during SSR to produce the correct initial markup.
  104. */
  105. const isBooleanAttr = /*#__PURE__*/ makeMap(specialBooleanAttrs +
  106. `,async,autofocus,autoplay,controls,default,defer,disabled,hidden,` +
  107. `loop,open,required,reversed,scoped,seamless,` +
  108. `checked,muted,multiple,selected`);
  109. const unsafeAttrCharRE = /[>/="'\u0009\u000a\u000c\u0020]/;
  110. const attrValidationCache = {};
  111. function isSSRSafeAttrName(name) {
  112. if (attrValidationCache.hasOwnProperty(name)) {
  113. return attrValidationCache[name];
  114. }
  115. const isUnsafe = unsafeAttrCharRE.test(name);
  116. if (isUnsafe) {
  117. console.error(`unsafe attribute name: ${name}`);
  118. }
  119. return (attrValidationCache[name] = !isUnsafe);
  120. }
  121. const propsToAttrMap = {
  122. acceptCharset: 'accept-charset',
  123. className: 'class',
  124. htmlFor: 'for',
  125. httpEquiv: 'http-equiv'
  126. };
  127. /**
  128. * CSS properties that accept plain numbers
  129. */
  130. const isNoUnitNumericStyleProp = /*#__PURE__*/ makeMap(`animation-iteration-count,border-image-outset,border-image-slice,` +
  131. `border-image-width,box-flex,box-flex-group,box-ordinal-group,column-count,` +
  132. `columns,flex,flex-grow,flex-positive,flex-shrink,flex-negative,flex-order,` +
  133. `grid-row,grid-row-end,grid-row-span,grid-row-start,grid-column,` +
  134. `grid-column-end,grid-column-span,grid-column-start,font-weight,line-clamp,` +
  135. `line-height,opacity,order,orphans,tab-size,widows,z-index,zoom,` +
  136. // SVG
  137. `fill-opacity,flood-opacity,stop-opacity,stroke-dasharray,stroke-dashoffset,` +
  138. `stroke-miterlimit,stroke-opacity,stroke-width`);
  139. /**
  140. * Known attributes, this is used for stringification of runtime static nodes
  141. * so that we don't stringify bindings that cannot be set from HTML.
  142. * Don't also forget to allow `data-*` and `aria-*`!
  143. * Generated from https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes
  144. */
  145. const isKnownHtmlAttr = /*#__PURE__*/ makeMap(`accept,accept-charset,accesskey,action,align,allow,alt,async,` +
  146. `autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,` +
  147. `border,buffered,capture,challenge,charset,checked,cite,class,code,` +
  148. `codebase,color,cols,colspan,content,contenteditable,contextmenu,controls,` +
  149. `coords,crossorigin,csp,data,datetime,decoding,default,defer,dir,dirname,` +
  150. `disabled,download,draggable,dropzone,enctype,enterkeyhint,for,form,` +
  151. `formaction,formenctype,formmethod,formnovalidate,formtarget,headers,` +
  152. `height,hidden,high,href,hreflang,http-equiv,icon,id,importance,integrity,` +
  153. `ismap,itemprop,keytype,kind,label,lang,language,loading,list,loop,low,` +
  154. `manifest,max,maxlength,minlength,media,min,multiple,muted,name,novalidate,` +
  155. `open,optimum,pattern,ping,placeholder,poster,preload,radiogroup,readonly,` +
  156. `referrerpolicy,rel,required,reversed,rows,rowspan,sandbox,scope,scoped,` +
  157. `selected,shape,size,sizes,slot,span,spellcheck,src,srcdoc,srclang,srcset,` +
  158. `start,step,style,summary,tabindex,target,title,translate,type,usemap,` +
  159. `value,width,wrap`);
  160. /**
  161. * Generated from https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute
  162. */
  163. const isKnownSvgAttr = /*#__PURE__*/ makeMap(`xmlns,accent-height,accumulate,additive,alignment-baseline,alphabetic,amplitude,` +
  164. `arabic-form,ascent,attributeName,attributeType,azimuth,baseFrequency,` +
  165. `baseline-shift,baseProfile,bbox,begin,bias,by,calcMode,cap-height,class,` +
  166. `clip,clipPathUnits,clip-path,clip-rule,color,color-interpolation,` +
  167. `color-interpolation-filters,color-profile,color-rendering,` +
  168. `contentScriptType,contentStyleType,crossorigin,cursor,cx,cy,d,decelerate,` +
  169. `descent,diffuseConstant,direction,display,divisor,dominant-baseline,dur,dx,` +
  170. `dy,edgeMode,elevation,enable-background,end,exponent,fill,fill-opacity,` +
  171. `fill-rule,filter,filterRes,filterUnits,flood-color,flood-opacity,` +
  172. `font-family,font-size,font-size-adjust,font-stretch,font-style,` +
  173. `font-variant,font-weight,format,from,fr,fx,fy,g1,g2,glyph-name,` +
  174. `glyph-orientation-horizontal,glyph-orientation-vertical,glyphRef,` +
  175. `gradientTransform,gradientUnits,hanging,height,href,hreflang,horiz-adv-x,` +
  176. `horiz-origin-x,id,ideographic,image-rendering,in,in2,intercept,k,k1,k2,k3,` +
  177. `k4,kernelMatrix,kernelUnitLength,kerning,keyPoints,keySplines,keyTimes,` +
  178. `lang,lengthAdjust,letter-spacing,lighting-color,limitingConeAngle,local,` +
  179. `marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,` +
  180. `mask,maskContentUnits,maskUnits,mathematical,max,media,method,min,mode,` +
  181. `name,numOctaves,offset,opacity,operator,order,orient,orientation,origin,` +
  182. `overflow,overline-position,overline-thickness,panose-1,paint-order,path,` +
  183. `pathLength,patternContentUnits,patternTransform,patternUnits,ping,` +
  184. `pointer-events,points,pointsAtX,pointsAtY,pointsAtZ,preserveAlpha,` +
  185. `preserveAspectRatio,primitiveUnits,r,radius,referrerPolicy,refX,refY,rel,` +
  186. `rendering-intent,repeatCount,repeatDur,requiredExtensions,requiredFeatures,` +
  187. `restart,result,rotate,rx,ry,scale,seed,shape-rendering,slope,spacing,` +
  188. `specularConstant,specularExponent,speed,spreadMethod,startOffset,` +
  189. `stdDeviation,stemh,stemv,stitchTiles,stop-color,stop-opacity,` +
  190. `strikethrough-position,strikethrough-thickness,string,stroke,` +
  191. `stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,` +
  192. `stroke-miterlimit,stroke-opacity,stroke-width,style,surfaceScale,` +
  193. `systemLanguage,tabindex,tableValues,target,targetX,targetY,text-anchor,` +
  194. `text-decoration,text-rendering,textLength,to,transform,transform-origin,` +
  195. `type,u1,u2,underline-position,underline-thickness,unicode,unicode-bidi,` +
  196. `unicode-range,units-per-em,v-alphabetic,v-hanging,v-ideographic,` +
  197. `v-mathematical,values,vector-effect,version,vert-adv-y,vert-origin-x,` +
  198. `vert-origin-y,viewBox,viewTarget,visibility,width,widths,word-spacing,` +
  199. `writing-mode,x,x-height,x1,x2,xChannelSelector,xlink:actuate,xlink:arcrole,` +
  200. `xlink:href,xlink:role,xlink:show,xlink:title,xlink:type,xml:base,xml:lang,` +
  201. `xml:space,y,y1,y2,yChannelSelector,z,zoomAndPan`);
  202. function normalizeStyle(value) {
  203. if (isArray(value)) {
  204. const res = {};
  205. for (let i = 0; i < value.length; i++) {
  206. const item = value[i];
  207. const normalized = isString(item)
  208. ? parseStringStyle(item)
  209. : normalizeStyle(item);
  210. if (normalized) {
  211. for (const key in normalized) {
  212. res[key] = normalized[key];
  213. }
  214. }
  215. }
  216. return res;
  217. }
  218. else if (isString(value)) {
  219. return value;
  220. }
  221. else if (isObject(value)) {
  222. return value;
  223. }
  224. }
  225. const listDelimiterRE = /;(?![^(]*\))/g;
  226. const propertyDelimiterRE = /:(.+)/;
  227. function parseStringStyle(cssText) {
  228. const ret = {};
  229. cssText.split(listDelimiterRE).forEach(item => {
  230. if (item) {
  231. const tmp = item.split(propertyDelimiterRE);
  232. tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
  233. }
  234. });
  235. return ret;
  236. }
  237. function stringifyStyle(styles) {
  238. let ret = '';
  239. if (!styles || isString(styles)) {
  240. return ret;
  241. }
  242. for (const key in styles) {
  243. const value = styles[key];
  244. const normalizedKey = key.startsWith(`--`) ? key : hyphenate(key);
  245. if (isString(value) ||
  246. (typeof value === 'number' && isNoUnitNumericStyleProp(normalizedKey))) {
  247. // only render valid values
  248. ret += `${normalizedKey}:${value};`;
  249. }
  250. }
  251. return ret;
  252. }
  253. function normalizeClass(value) {
  254. let res = '';
  255. if (isString(value)) {
  256. res = value;
  257. }
  258. else if (isArray(value)) {
  259. for (let i = 0; i < value.length; i++) {
  260. const normalized = normalizeClass(value[i]);
  261. if (normalized) {
  262. res += normalized + ' ';
  263. }
  264. }
  265. }
  266. else if (isObject(value)) {
  267. for (const name in value) {
  268. if (value[name]) {
  269. res += name + ' ';
  270. }
  271. }
  272. }
  273. return res.trim();
  274. }
  275. // These tag configs are shared between compiler-dom and runtime-dom, so they
  276. // https://developer.mozilla.org/en-US/docs/Web/HTML/Element
  277. const HTML_TAGS = 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +
  278. 'header,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,' +
  279. 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +
  280. 'data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,' +
  281. 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +
  282. 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +
  283. 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +
  284. 'option,output,progress,select,textarea,details,dialog,menu,' +
  285. 'summary,template,blockquote,iframe,tfoot';
  286. // https://developer.mozilla.org/en-US/docs/Web/SVG/Element
  287. const SVG_TAGS = 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +
  288. 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +
  289. 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +
  290. 'feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +
  291. 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +
  292. 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +
  293. 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +
  294. 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +
  295. 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +
  296. 'text,textPath,title,tspan,unknown,use,view';
  297. const VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';
  298. const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
  299. const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
  300. const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
  301. const escapeRE = /["'&<>]/;
  302. function escapeHtml(string) {
  303. const str = '' + string;
  304. const match = escapeRE.exec(str);
  305. if (!match) {
  306. return str;
  307. }
  308. let html = '';
  309. let escaped;
  310. let index;
  311. let lastIndex = 0;
  312. for (index = match.index; index < str.length; index++) {
  313. switch (str.charCodeAt(index)) {
  314. case 34: // "
  315. escaped = '&quot;';
  316. break;
  317. case 38: // &
  318. escaped = '&amp;';
  319. break;
  320. case 39: // '
  321. escaped = '&#39;';
  322. break;
  323. case 60: // <
  324. escaped = '&lt;';
  325. break;
  326. case 62: // >
  327. escaped = '&gt;';
  328. break;
  329. default:
  330. continue;
  331. }
  332. if (lastIndex !== index) {
  333. html += str.slice(lastIndex, index);
  334. }
  335. lastIndex = index + 1;
  336. html += escaped;
  337. }
  338. return lastIndex !== index ? html + str.slice(lastIndex, index) : html;
  339. }
  340. /**
  341. * For converting {{ interpolation }} values to displayed strings.
  342. * @private
  343. */
  344. const toDisplayString = (val) => {
  345. return val == null
  346. ? ''
  347. : isArray(val) ||
  348. (isObject(val) &&
  349. (val.toString === objectToString || !isFunction(val.toString)))
  350. ? JSON.stringify(val, replacer, 2)
  351. : String(val);
  352. };
  353. const replacer = (_key, val) => {
  354. // can't use isRef here since @vue/shared has no deps
  355. if (val && val.__v_isRef) {
  356. return replacer(_key, val.value);
  357. }
  358. else if (isMap(val)) {
  359. return {
  360. [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
  361. entries[`${key} =>`] = val;
  362. return entries;
  363. }, {})
  364. };
  365. }
  366. else if (isSet(val)) {
  367. return {
  368. [`Set(${val.size})`]: [...val.values()]
  369. };
  370. }
  371. else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
  372. return String(val);
  373. }
  374. return val;
  375. };
  376. const EMPTY_OBJ = Object.freeze({})
  377. ;
  378. Object.freeze([]) ;
  379. const NOOP = () => { };
  380. /**
  381. * Always return false.
  382. */
  383. const NO = () => false;
  384. const onRE = /^on[^a-z]/;
  385. const isOn = (key) => onRE.test(key);
  386. const extend = Object.assign;
  387. const hasOwnProperty = Object.prototype.hasOwnProperty;
  388. const hasOwn = (val, key) => hasOwnProperty.call(val, key);
  389. const isArray = Array.isArray;
  390. const isMap = (val) => toTypeString(val) === '[object Map]';
  391. const isSet = (val) => toTypeString(val) === '[object Set]';
  392. const isFunction = (val) => typeof val === 'function';
  393. const isString = (val) => typeof val === 'string';
  394. const isSymbol = (val) => typeof val === 'symbol';
  395. const isObject = (val) => val !== null && typeof val === 'object';
  396. const objectToString = Object.prototype.toString;
  397. const toTypeString = (value) => objectToString.call(value);
  398. const isPlainObject = (val) => toTypeString(val) === '[object Object]';
  399. const isReservedProp = /*#__PURE__*/ makeMap(
  400. // the leading comma is intentional so empty string "" is also included
  401. ',key,ref,ref_for,ref_key,' +
  402. 'onVnodeBeforeMount,onVnodeMounted,' +
  403. 'onVnodeBeforeUpdate,onVnodeUpdated,' +
  404. 'onVnodeBeforeUnmount,onVnodeUnmounted');
  405. const cacheStringFunction = (fn) => {
  406. const cache = Object.create(null);
  407. return ((str) => {
  408. const hit = cache[str];
  409. return hit || (cache[str] = fn(str));
  410. });
  411. };
  412. const camelizeRE = /-(\w)/g;
  413. /**
  414. * @private
  415. */
  416. const camelize = cacheStringFunction((str) => {
  417. return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
  418. });
  419. const hyphenateRE = /\B([A-Z])/g;
  420. /**
  421. * @private
  422. */
  423. const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
  424. /**
  425. * @private
  426. */
  427. const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
  428. /**
  429. * @private
  430. */
  431. const toHandlerKey = cacheStringFunction((str) => str ? `on${capitalize(str)}` : ``);
  432. function defaultOnError(error) {
  433. throw error;
  434. }
  435. function defaultOnWarn(msg) {
  436. console.warn(`[Vue warn] ${msg.message}`);
  437. }
  438. function createCompilerError(code, loc, messages, additionalMessage) {
  439. const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
  440. ;
  441. const error = new SyntaxError(String(msg));
  442. error.code = code;
  443. error.loc = loc;
  444. return error;
  445. }
  446. const errorMessages = {
  447. // parse errors
  448. [0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
  449. [1 /* CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
  450. [2 /* DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
  451. [3 /* END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
  452. [4 /* END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
  453. [5 /* EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
  454. [6 /* EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
  455. [7 /* EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
  456. [8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
  457. [9 /* EOF_IN_TAG */]: 'Unexpected EOF in tag.',
  458. [10 /* INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
  459. [11 /* INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
  460. [12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
  461. [13 /* MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
  462. [14 /* MISSING_END_TAG_NAME */]: 'End tag name was expected.',
  463. [15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
  464. [16 /* NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
  465. [17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
  466. [18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
  467. [19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
  468. [21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
  469. [20 /* UNEXPECTED_NULL_CHARACTER */]: `Unexpected null character.`,
  470. [22 /* UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
  471. // Vue-specific parse errors
  472. [23 /* X_INVALID_END_TAG */]: 'Invalid end tag.',
  473. [24 /* X_MISSING_END_TAG */]: 'Element is missing end tag.',
  474. [25 /* X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
  475. [27 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
  476. 'Note that dynamic directive argument cannot contain spaces.',
  477. [26 /* X_MISSING_DIRECTIVE_NAME */]: 'Legal directive name was expected.',
  478. // transform errors
  479. [28 /* X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
  480. [29 /* X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
  481. [30 /* X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if or v-else-if.`,
  482. [31 /* X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
  483. [32 /* X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
  484. [33 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
  485. [34 /* X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
  486. [35 /* X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
  487. [36 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
  488. [37 /* X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
  489. `When there are multiple named slots, all slots should use <template> ` +
  490. `syntax to avoid scope ambiguity.`,
  491. [38 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
  492. [39 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
  493. `default slot. These children will be ignored.`,
  494. [40 /* X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
  495. [41 /* X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
  496. [42 /* X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
  497. [43 /* X_V_MODEL_ON_SCOPE_VARIABLE */]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,
  498. [44 /* X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
  499. [45 /* X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
  500. // generic errors
  501. [46 /* X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
  502. [47 /* X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
  503. [48 /* X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
  504. [49 /* X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`,
  505. // just to fulfill types
  506. [50 /* __EXTEND_POINT__ */]: ``
  507. };
  508. const FRAGMENT = Symbol(`Fragment` );
  509. const TELEPORT = Symbol(`Teleport` );
  510. const SUSPENSE = Symbol(`Suspense` );
  511. const KEEP_ALIVE = Symbol(`KeepAlive` );
  512. const BASE_TRANSITION = Symbol(`BaseTransition` );
  513. const OPEN_BLOCK = Symbol(`openBlock` );
  514. const CREATE_BLOCK = Symbol(`createBlock` );
  515. const CREATE_ELEMENT_BLOCK = Symbol(`createElementBlock` );
  516. const CREATE_VNODE = Symbol(`createVNode` );
  517. const CREATE_ELEMENT_VNODE = Symbol(`createElementVNode` );
  518. const CREATE_COMMENT = Symbol(`createCommentVNode` );
  519. const CREATE_TEXT = Symbol(`createTextVNode` );
  520. const CREATE_STATIC = Symbol(`createStaticVNode` );
  521. const RESOLVE_COMPONENT = Symbol(`resolveComponent` );
  522. const RESOLVE_DYNAMIC_COMPONENT = Symbol(`resolveDynamicComponent` );
  523. const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` );
  524. const RESOLVE_FILTER = Symbol(`resolveFilter` );
  525. const WITH_DIRECTIVES = Symbol(`withDirectives` );
  526. const RENDER_LIST = Symbol(`renderList` );
  527. const RENDER_SLOT = Symbol(`renderSlot` );
  528. const CREATE_SLOTS = Symbol(`createSlots` );
  529. const TO_DISPLAY_STRING = Symbol(`toDisplayString` );
  530. const MERGE_PROPS = Symbol(`mergeProps` );
  531. const NORMALIZE_CLASS = Symbol(`normalizeClass` );
  532. const NORMALIZE_STYLE = Symbol(`normalizeStyle` );
  533. const NORMALIZE_PROPS = Symbol(`normalizeProps` );
  534. const GUARD_REACTIVE_PROPS = Symbol(`guardReactiveProps` );
  535. const TO_HANDLERS = Symbol(`toHandlers` );
  536. const CAMELIZE = Symbol(`camelize` );
  537. const CAPITALIZE = Symbol(`capitalize` );
  538. const TO_HANDLER_KEY = Symbol(`toHandlerKey` );
  539. const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` );
  540. const PUSH_SCOPE_ID = Symbol(`pushScopeId` );
  541. const POP_SCOPE_ID = Symbol(`popScopeId` );
  542. const WITH_CTX = Symbol(`withCtx` );
  543. const UNREF = Symbol(`unref` );
  544. const IS_REF = Symbol(`isRef` );
  545. const WITH_MEMO = Symbol(`withMemo` );
  546. const IS_MEMO_SAME = Symbol(`isMemoSame` );
  547. // Name mapping for runtime helpers that need to be imported from 'vue' in
  548. // generated code. Make sure these are correctly exported in the runtime!
  549. // Using `any` here because TS doesn't allow symbols as index type.
  550. const helperNameMap = {
  551. [FRAGMENT]: `Fragment`,
  552. [TELEPORT]: `Teleport`,
  553. [SUSPENSE]: `Suspense`,
  554. [KEEP_ALIVE]: `KeepAlive`,
  555. [BASE_TRANSITION]: `BaseTransition`,
  556. [OPEN_BLOCK]: `openBlock`,
  557. [CREATE_BLOCK]: `createBlock`,
  558. [CREATE_ELEMENT_BLOCK]: `createElementBlock`,
  559. [CREATE_VNODE]: `createVNode`,
  560. [CREATE_ELEMENT_VNODE]: `createElementVNode`,
  561. [CREATE_COMMENT]: `createCommentVNode`,
  562. [CREATE_TEXT]: `createTextVNode`,
  563. [CREATE_STATIC]: `createStaticVNode`,
  564. [RESOLVE_COMPONENT]: `resolveComponent`,
  565. [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
  566. [RESOLVE_DIRECTIVE]: `resolveDirective`,
  567. [RESOLVE_FILTER]: `resolveFilter`,
  568. [WITH_DIRECTIVES]: `withDirectives`,
  569. [RENDER_LIST]: `renderList`,
  570. [RENDER_SLOT]: `renderSlot`,
  571. [CREATE_SLOTS]: `createSlots`,
  572. [TO_DISPLAY_STRING]: `toDisplayString`,
  573. [MERGE_PROPS]: `mergeProps`,
  574. [NORMALIZE_CLASS]: `normalizeClass`,
  575. [NORMALIZE_STYLE]: `normalizeStyle`,
  576. [NORMALIZE_PROPS]: `normalizeProps`,
  577. [GUARD_REACTIVE_PROPS]: `guardReactiveProps`,
  578. [TO_HANDLERS]: `toHandlers`,
  579. [CAMELIZE]: `camelize`,
  580. [CAPITALIZE]: `capitalize`,
  581. [TO_HANDLER_KEY]: `toHandlerKey`,
  582. [SET_BLOCK_TRACKING]: `setBlockTracking`,
  583. [PUSH_SCOPE_ID]: `pushScopeId`,
  584. [POP_SCOPE_ID]: `popScopeId`,
  585. [WITH_CTX]: `withCtx`,
  586. [UNREF]: `unref`,
  587. [IS_REF]: `isRef`,
  588. [WITH_MEMO]: `withMemo`,
  589. [IS_MEMO_SAME]: `isMemoSame`
  590. };
  591. function registerRuntimeHelpers(helpers) {
  592. Object.getOwnPropertySymbols(helpers).forEach(s => {
  593. helperNameMap[s] = helpers[s];
  594. });
  595. }
  596. // AST Utilities ---------------------------------------------------------------
  597. // Some expressions, e.g. sequence and conditional expressions, are never
  598. // associated with template nodes, so their source locations are just a stub.
  599. // Container types like CompoundExpression also don't need a real location.
  600. const locStub = {
  601. source: '',
  602. start: { line: 1, column: 1, offset: 0 },
  603. end: { line: 1, column: 1, offset: 0 }
  604. };
  605. function createRoot(children, loc = locStub) {
  606. return {
  607. type: 0 /* ROOT */,
  608. children,
  609. helpers: [],
  610. components: [],
  611. directives: [],
  612. hoists: [],
  613. imports: [],
  614. cached: 0,
  615. temps: 0,
  616. codegenNode: undefined,
  617. loc
  618. };
  619. }
  620. function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent = false, loc = locStub) {
  621. if (context) {
  622. if (isBlock) {
  623. context.helper(OPEN_BLOCK);
  624. context.helper(getVNodeBlockHelper(context.inSSR, isComponent));
  625. }
  626. else {
  627. context.helper(getVNodeHelper(context.inSSR, isComponent));
  628. }
  629. if (directives) {
  630. context.helper(WITH_DIRECTIVES);
  631. }
  632. }
  633. return {
  634. type: 13 /* VNODE_CALL */,
  635. tag,
  636. props,
  637. children,
  638. patchFlag,
  639. dynamicProps,
  640. directives,
  641. isBlock,
  642. disableTracking,
  643. isComponent,
  644. loc
  645. };
  646. }
  647. function createArrayExpression(elements, loc = locStub) {
  648. return {
  649. type: 17 /* JS_ARRAY_EXPRESSION */,
  650. loc,
  651. elements
  652. };
  653. }
  654. function createObjectExpression(properties, loc = locStub) {
  655. return {
  656. type: 15 /* JS_OBJECT_EXPRESSION */,
  657. loc,
  658. properties
  659. };
  660. }
  661. function createObjectProperty(key, value) {
  662. return {
  663. type: 16 /* JS_PROPERTY */,
  664. loc: locStub,
  665. key: isString(key) ? createSimpleExpression(key, true) : key,
  666. value
  667. };
  668. }
  669. function createSimpleExpression(content, isStatic = false, loc = locStub, constType = 0 /* NOT_CONSTANT */) {
  670. return {
  671. type: 4 /* SIMPLE_EXPRESSION */,
  672. loc,
  673. content,
  674. isStatic,
  675. constType: isStatic ? 3 /* CAN_STRINGIFY */ : constType
  676. };
  677. }
  678. function createInterpolation(content, loc) {
  679. return {
  680. type: 5 /* INTERPOLATION */,
  681. loc,
  682. content: isString(content)
  683. ? createSimpleExpression(content, false, loc)
  684. : content
  685. };
  686. }
  687. function createCompoundExpression(children, loc = locStub) {
  688. return {
  689. type: 8 /* COMPOUND_EXPRESSION */,
  690. loc,
  691. children
  692. };
  693. }
  694. function createCallExpression(callee, args = [], loc = locStub) {
  695. return {
  696. type: 14 /* JS_CALL_EXPRESSION */,
  697. loc,
  698. callee,
  699. arguments: args
  700. };
  701. }
  702. function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
  703. return {
  704. type: 18 /* JS_FUNCTION_EXPRESSION */,
  705. params,
  706. returns,
  707. newline,
  708. isSlot,
  709. loc
  710. };
  711. }
  712. function createConditionalExpression(test, consequent, alternate, newline = true) {
  713. return {
  714. type: 19 /* JS_CONDITIONAL_EXPRESSION */,
  715. test,
  716. consequent,
  717. alternate,
  718. newline,
  719. loc: locStub
  720. };
  721. }
  722. function createCacheExpression(index, value, isVNode = false) {
  723. return {
  724. type: 20 /* JS_CACHE_EXPRESSION */,
  725. index,
  726. value,
  727. isVNode,
  728. loc: locStub
  729. };
  730. }
  731. function createBlockStatement(body) {
  732. return {
  733. type: 21 /* JS_BLOCK_STATEMENT */,
  734. body,
  735. loc: locStub
  736. };
  737. }
  738. function createTemplateLiteral(elements) {
  739. return {
  740. type: 22 /* JS_TEMPLATE_LITERAL */,
  741. elements,
  742. loc: locStub
  743. };
  744. }
  745. function createIfStatement(test, consequent, alternate) {
  746. return {
  747. type: 23 /* JS_IF_STATEMENT */,
  748. test,
  749. consequent,
  750. alternate,
  751. loc: locStub
  752. };
  753. }
  754. function createAssignmentExpression(left, right) {
  755. return {
  756. type: 24 /* JS_ASSIGNMENT_EXPRESSION */,
  757. left,
  758. right,
  759. loc: locStub
  760. };
  761. }
  762. function createSequenceExpression(expressions) {
  763. return {
  764. type: 25 /* JS_SEQUENCE_EXPRESSION */,
  765. expressions,
  766. loc: locStub
  767. };
  768. }
  769. function createReturnStatement(returns) {
  770. return {
  771. type: 26 /* JS_RETURN_STATEMENT */,
  772. returns,
  773. loc: locStub
  774. };
  775. }
  776. const lineBreak = /\r\n?|[\n\u2028\u2029]/;
  777. const lineBreakG = new RegExp(lineBreak.source, "g");
  778. function isNewLine(code) {
  779. switch (code) {
  780. case 10:
  781. case 13:
  782. case 8232:
  783. case 8233:
  784. return true;
  785. default:
  786. return false;
  787. }
  788. }
  789. const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  790. const skipWhiteSpaceInLine = /(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/y;
  791. const skipWhiteSpaceToLineBreak = new RegExp("(?=(" + skipWhiteSpaceInLine.source + "))\\1" + /(?=[\n\r\u2028\u2029]|\/\*(?!.*?\*\/)|$)/.source, "y");
  792. function isWhitespace(code) {
  793. switch (code) {
  794. case 0x0009:
  795. case 0x000b:
  796. case 0x000c:
  797. case 32:
  798. case 160:
  799. case 5760:
  800. case 0x2000:
  801. case 0x2001:
  802. case 0x2002:
  803. case 0x2003:
  804. case 0x2004:
  805. case 0x2005:
  806. case 0x2006:
  807. case 0x2007:
  808. case 0x2008:
  809. case 0x2009:
  810. case 0x200a:
  811. case 0x202f:
  812. case 0x205f:
  813. case 0x3000:
  814. case 0xfeff:
  815. return true;
  816. default:
  817. return false;
  818. }
  819. }
  820. class Position {
  821. constructor(line, col) {
  822. this.line = void 0;
  823. this.column = void 0;
  824. this.line = line;
  825. this.column = col;
  826. }
  827. }
  828. class SourceLocation {
  829. constructor(start, end) {
  830. this.start = void 0;
  831. this.end = void 0;
  832. this.filename = void 0;
  833. this.identifierName = void 0;
  834. this.start = start;
  835. this.end = end;
  836. }
  837. }
  838. function getLineInfo(input, offset) {
  839. let line = 1;
  840. let lineStart = 0;
  841. let match;
  842. lineBreakG.lastIndex = 0;
  843. while ((match = lineBreakG.exec(input)) && match.index < offset) {
  844. line++;
  845. lineStart = lineBreakG.lastIndex;
  846. }
  847. return new Position(line, offset - lineStart);
  848. }
  849. class BaseParser {
  850. constructor() {
  851. this.sawUnambiguousESM = false;
  852. this.ambiguousScriptDifferentAst = false;
  853. }
  854. hasPlugin(name) {
  855. return this.plugins.has(name);
  856. }
  857. getPluginOption(plugin, name) {
  858. if (this.hasPlugin(plugin)) return this.plugins.get(plugin)[name];
  859. }
  860. }
  861. function setTrailingComments(node, comments) {
  862. if (node.trailingComments === undefined) {
  863. node.trailingComments = comments;
  864. } else {
  865. node.trailingComments.unshift(...comments);
  866. }
  867. }
  868. function setLeadingComments(node, comments) {
  869. if (node.leadingComments === undefined) {
  870. node.leadingComments = comments;
  871. } else {
  872. node.leadingComments.unshift(...comments);
  873. }
  874. }
  875. function setInnerComments(node, comments) {
  876. if (node.innerComments === undefined) {
  877. node.innerComments = comments;
  878. } else {
  879. node.innerComments.unshift(...comments);
  880. }
  881. }
  882. function adjustInnerComments(node, elements, commentWS) {
  883. let lastElement = null;
  884. let i = elements.length;
  885. while (lastElement === null && i > 0) {
  886. lastElement = elements[--i];
  887. }
  888. if (lastElement === null || lastElement.start > commentWS.start) {
  889. setInnerComments(node, commentWS.comments);
  890. } else {
  891. setTrailingComments(lastElement, commentWS.comments);
  892. }
  893. }
  894. class CommentsParser extends BaseParser {
  895. addComment(comment) {
  896. if (this.filename) comment.loc.filename = this.filename;
  897. this.state.comments.push(comment);
  898. }
  899. processComment(node) {
  900. const {
  901. commentStack
  902. } = this.state;
  903. const commentStackLength = commentStack.length;
  904. if (commentStackLength === 0) return;
  905. let i = commentStackLength - 1;
  906. const lastCommentWS = commentStack[i];
  907. if (lastCommentWS.start === node.end) {
  908. lastCommentWS.leadingNode = node;
  909. i--;
  910. }
  911. const {
  912. start: nodeStart
  913. } = node;
  914. for (; i >= 0; i--) {
  915. const commentWS = commentStack[i];
  916. const commentEnd = commentWS.end;
  917. if (commentEnd > nodeStart) {
  918. commentWS.containingNode = node;
  919. this.finalizeComment(commentWS);
  920. commentStack.splice(i, 1);
  921. } else {
  922. if (commentEnd === nodeStart) {
  923. commentWS.trailingNode = node;
  924. }
  925. break;
  926. }
  927. }
  928. }
  929. finalizeComment(commentWS) {
  930. const {
  931. comments
  932. } = commentWS;
  933. if (commentWS.leadingNode !== null || commentWS.trailingNode !== null) {
  934. if (commentWS.leadingNode !== null) {
  935. setTrailingComments(commentWS.leadingNode, comments);
  936. }
  937. if (commentWS.trailingNode !== null) {
  938. setLeadingComments(commentWS.trailingNode, comments);
  939. }
  940. } else {
  941. const {
  942. containingNode: node,
  943. start: commentStart
  944. } = commentWS;
  945. if (this.input.charCodeAt(commentStart - 1) === 44) {
  946. switch (node.type) {
  947. case "ObjectExpression":
  948. case "ObjectPattern":
  949. case "RecordExpression":
  950. adjustInnerComments(node, node.properties, commentWS);
  951. break;
  952. case "CallExpression":
  953. case "OptionalCallExpression":
  954. adjustInnerComments(node, node.arguments, commentWS);
  955. break;
  956. case "FunctionDeclaration":
  957. case "FunctionExpression":
  958. case "ArrowFunctionExpression":
  959. case "ObjectMethod":
  960. case "ClassMethod":
  961. case "ClassPrivateMethod":
  962. adjustInnerComments(node, node.params, commentWS);
  963. break;
  964. case "ArrayExpression":
  965. case "ArrayPattern":
  966. case "TupleExpression":
  967. adjustInnerComments(node, node.elements, commentWS);
  968. break;
  969. case "ExportNamedDeclaration":
  970. case "ImportDeclaration":
  971. adjustInnerComments(node, node.specifiers, commentWS);
  972. break;
  973. default:
  974. {
  975. setInnerComments(node, comments);
  976. }
  977. }
  978. } else {
  979. setInnerComments(node, comments);
  980. }
  981. }
  982. }
  983. finalizeRemainingComments() {
  984. const {
  985. commentStack
  986. } = this.state;
  987. for (let i = commentStack.length - 1; i >= 0; i--) {
  988. this.finalizeComment(commentStack[i]);
  989. }
  990. this.state.commentStack = [];
  991. }
  992. resetPreviousNodeTrailingComments(node) {
  993. const {
  994. commentStack
  995. } = this.state;
  996. const {
  997. length
  998. } = commentStack;
  999. if (length === 0) return;
  1000. const commentWS = commentStack[length - 1];
  1001. if (commentWS.leadingNode === node) {
  1002. commentWS.leadingNode = null;
  1003. }
  1004. }
  1005. takeSurroundingComments(node, start, end) {
  1006. const {
  1007. commentStack
  1008. } = this.state;
  1009. const commentStackLength = commentStack.length;
  1010. if (commentStackLength === 0) return;
  1011. let i = commentStackLength - 1;
  1012. for (; i >= 0; i--) {
  1013. const commentWS = commentStack[i];
  1014. const commentEnd = commentWS.end;
  1015. const commentStart = commentWS.start;
  1016. if (commentStart === end) {
  1017. commentWS.leadingNode = node;
  1018. } else if (commentEnd === start) {
  1019. commentWS.trailingNode = node;
  1020. } else if (commentEnd < start) {
  1021. break;
  1022. }
  1023. }
  1024. }
  1025. }
  1026. const ErrorCodes = Object.freeze({
  1027. SyntaxError: "BABEL_PARSER_SYNTAX_ERROR",
  1028. SourceTypeModuleError: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  1029. });
  1030. const ErrorMessages = makeErrorTemplates({
  1031. AccessorIsGenerator: "A %0ter cannot be a generator.",
  1032. ArgumentsInClass: "'arguments' is only allowed in functions and class methods.",
  1033. AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block.",
  1034. AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function.",
  1035. AwaitBindingIdentifierInStaticBlock: "Can not use 'await' as identifier inside a static block.",
  1036. AwaitExpressionFormalParameter: "'await' is not allowed in async function parameters.",
  1037. AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules.",
  1038. AwaitNotInAsyncFunction: "'await' is only allowed within async functions.",
  1039. BadGetterArity: "A 'get' accesor must not have any formal parameters.",
  1040. BadSetterArity: "A 'set' accesor must have exactly one formal parameter.",
  1041. BadSetterRestParameter: "A 'set' accesor function argument must not be a rest parameter.",
  1042. ConstructorClassField: "Classes may not have a field named 'constructor'.",
  1043. ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'.",
  1044. ConstructorIsAccessor: "Class constructor may not be an accessor.",
  1045. ConstructorIsAsync: "Constructor can't be an async function.",
  1046. ConstructorIsGenerator: "Constructor can't be a generator.",
  1047. DeclarationMissingInitializer: "'%0' require an initialization value.",
  1048. DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. You can set the 'decoratorsBeforeExport' option to false to use the 'export @decorator class {}' syntax.",
  1049. DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",
  1050. DecoratorExportClass: "Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class` instead.",
  1051. DecoratorSemicolon: "Decorators must not be followed by a semicolon.",
  1052. DecoratorStaticBlock: "Decorators can't be used with a static block.",
  1053. DeletePrivateField: "Deleting a private field is not allowed.",
  1054. DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.",
  1055. DuplicateConstructor: "Duplicate constructor in the same class.",
  1056. DuplicateDefaultExport: "Only one default export allowed per module.",
  1057. DuplicateExport: "`%0` has already been exported. Exported identifiers must be unique.",
  1058. DuplicateProto: "Redefinition of __proto__ property.",
  1059. DuplicateRegExpFlags: "Duplicate regular expression flag.",
  1060. ElementAfterRest: "Rest element must be last element.",
  1061. EscapedCharNotAnIdentifier: "Invalid Unicode escape.",
  1062. ExportBindingIsString: "A string literal cannot be used as an exported binding without `from`.\n- Did you mean `export { '%0' as '%1' } from 'some-module'`?",
  1063. ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'.",
  1064. ForInOfLoopInitializer: "'%0' loop variable declaration may not have an initializer.",
  1065. ForOfAsync: "The left-hand side of a for-of loop may not be 'async'.",
  1066. ForOfLet: "The left-hand side of a for-of loop may not start with 'let'.",
  1067. GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block.",
  1068. IllegalBreakContinue: "Unsyntactic %0.",
  1069. IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list.",
  1070. IllegalReturn: "'return' outside of function.",
  1071. ImportBindingIsString: 'A string literal cannot be used as an imported binding.\n- Did you mean `import { "%0" as foo }`?',
  1072. ImportCallArgumentTrailingComma: "Trailing comma is disallowed inside import(...) arguments.",
  1073. ImportCallArity: "`import()` requires exactly %0.",
  1074. ImportCallNotNewExpression: "Cannot use new with import(...).",
  1075. ImportCallSpreadArgument: "`...` is not allowed in `import()`.",
  1076. InvalidBigIntLiteral: "Invalid BigIntLiteral.",
  1077. InvalidCodePoint: "Code point out of bounds.",
  1078. InvalidDecimal: "Invalid decimal.",
  1079. InvalidDigit: "Expected number in radix %0.",
  1080. InvalidEscapeSequence: "Bad character escape sequence.",
  1081. InvalidEscapeSequenceTemplate: "Invalid escape sequence in template.",
  1082. InvalidEscapedReservedWord: "Escape sequence in keyword %0.",
  1083. InvalidIdentifier: "Invalid identifier %0.",
  1084. InvalidLhs: "Invalid left-hand side in %0.",
  1085. InvalidLhsBinding: "Binding invalid left-hand side in %0.",
  1086. InvalidNumber: "Invalid number.",
  1087. InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'.",
  1088. InvalidOrUnexpectedToken: "Unexpected character '%0'.",
  1089. InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern.",
  1090. InvalidPrivateFieldResolution: "Private name #%0 is not defined.",
  1091. InvalidPropertyBindingPattern: "Binding member expression.",
  1092. InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions.",
  1093. InvalidRestAssignmentPattern: "Invalid rest operator's argument.",
  1094. LabelRedeclaration: "Label '%0' is already declared.",
  1095. LetInLexicalBinding: "'let' is not allowed to be used as a name in 'let' or 'const' declarations.",
  1096. LineTerminatorBeforeArrow: "No line break is allowed before '=>'.",
  1097. MalformedRegExpFlags: "Invalid regular expression flag.",
  1098. MissingClassName: "A class name is required.",
  1099. MissingEqInAssignment: "Only '=' operator can be used for specifying default value.",
  1100. MissingSemicolon: "Missing semicolon.",
  1101. MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX.",
  1102. MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators.",
  1103. ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`.",
  1104. ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values.",
  1105. ModuleAttributesWithDuplicateKeys: 'Duplicate key "%0" is not allowed in module attributes.',
  1106. ModuleExportNameHasLoneSurrogate: "An export name cannot include a lone surrogate, found '\\u%0'.",
  1107. ModuleExportUndefined: "Export '%0' is not defined.",
  1108. MultipleDefaultsInSwitch: "Multiple default clauses.",
  1109. NewlineAfterThrow: "Illegal newline after throw.",
  1110. NoCatchOrFinally: "Missing catch or finally clause.",
  1111. NumberIdentifier: "Identifier directly after number.",
  1112. NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.",
  1113. ObsoleteAwaitStar: "'await*' has been removed from the async functions proposal. Use Promise.all() instead.",
  1114. OptionalChainingNoNew: "Constructors in/after an Optional Chain are not allowed.",
  1115. OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain.",
  1116. OverrideOnConstructor: "'override' modifier cannot appear on a constructor declaration.",
  1117. ParamDupe: "Argument name clash.",
  1118. PatternHasAccessor: "Object pattern can't contain getter or setter.",
  1119. PatternHasMethod: "Object pattern can't contain methods.",
  1120. PipeBodyIsTighter: "Unexpected %0 after pipeline body; any %0 expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.",
  1121. PipeTopicRequiresHackPipes: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.',
  1122. PipeTopicUnbound: "Topic reference is unbound; it must be inside a pipe body.",
  1123. 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" }.',
  1124. PipeTopicUnused: "Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.",
  1125. PipeUnparenthesizedBody: "Hack-style pipe body cannot be an unparenthesized %0 expression; please wrap it in parentheses.",
  1126. PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized.',
  1127. PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression.",
  1128. PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression.",
  1129. PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference.",
  1130. PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding.",
  1131. PrimaryTopicRequiresSmartPipeline: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.',
  1132. PrivateInExpectedIn: "Private names are only allowed in property accesses (`obj.#%0`) or in `in` expressions (`#%0 in obj`).",
  1133. PrivateNameRedeclaration: "Duplicate private name #%0.",
  1134. RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  1135. RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  1136. RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",
  1137. RecordNoProto: "'__proto__' is not allowed in Record expressions.",
  1138. RestTrailingComma: "Unexpected trailing comma after rest element.",
  1139. 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.",
  1140. StaticPrototype: "Classes may not have static property named prototype.",
  1141. StrictDelete: "Deleting local variable in strict mode.",
  1142. StrictEvalArguments: "Assigning to '%0' in strict mode.",
  1143. StrictEvalArgumentsBinding: "Binding '%0' in strict mode.",
  1144. StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block.",
  1145. StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'.",
  1146. StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode.",
  1147. StrictWith: "'with' in strict mode.",
  1148. 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?",
  1149. SuperPrivateField: "Private fields can't be accessed on super.",
  1150. TrailingDecorator: "Decorators must be attached to a class element.",
  1151. TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  1152. TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  1153. TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",
  1154. UnexpectedArgumentPlaceholder: "Unexpected argument placeholder.",
  1155. UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal.',
  1156. UnexpectedDigitAfterHash: "Unexpected digit after hash token.",
  1157. UnexpectedImportExport: "'import' and 'export' may only appear at the top level.",
  1158. UnexpectedKeyword: "Unexpected keyword '%0'.",
  1159. UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration.",
  1160. UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context.",
  1161. UnexpectedNewTarget: "`new.target` can only be used in functions or class properties.",
  1162. UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits.",
  1163. 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).",
  1164. UnexpectedReservedWord: "Unexpected reserved word '%0'.",
  1165. UnexpectedSuper: "'super' is only allowed in object methods and classes.",
  1166. UnexpectedToken: "Unexpected token '%0'.",
  1167. UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",
  1168. UnsupportedBind: "Binding should be performed on object property.",
  1169. UnsupportedDecoratorExport: "A decorated export must export a class declaration.",
  1170. UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.",
  1171. UnsupportedImport: "`import` can only be used in `import()` or `import.meta`.",
  1172. UnsupportedMetaProperty: "The only valid meta property for %0 is %0.%1.",
  1173. UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters.",
  1174. UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties.",
  1175. UnsupportedSuper: "'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).",
  1176. UnterminatedComment: "Unterminated comment.",
  1177. UnterminatedRegExp: "Unterminated regular expression.",
  1178. UnterminatedString: "Unterminated string constant.",
  1179. UnterminatedTemplate: "Unterminated template.",
  1180. VarRedeclaration: "Identifier '%0' has already been declared.",
  1181. YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator.",
  1182. YieldInParameter: "Yield expression is not allowed in formal parameters.",
  1183. ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0."
  1184. }, ErrorCodes.SyntaxError);
  1185. const SourceTypeModuleErrorMessages = makeErrorTemplates({
  1186. ImportMetaOutsideModule: `import.meta may appear only with 'sourceType: "module"'`,
  1187. ImportOutsideModule: `'import' and 'export' may appear only with 'sourceType: "module"'`
  1188. }, ErrorCodes.SourceTypeModuleError);
  1189. function keepReasonCodeCompat(reasonCode, syntaxPlugin) {
  1190. {
  1191. if (syntaxPlugin === "flow" && reasonCode === "PatternIsOptional") {
  1192. return "OptionalBindingPattern";
  1193. }
  1194. }
  1195. return reasonCode;
  1196. }
  1197. function makeErrorTemplates(messages, code, syntaxPlugin) {
  1198. const templates = {};
  1199. Object.keys(messages).forEach(reasonCode => {
  1200. templates[reasonCode] = Object.freeze({
  1201. code,
  1202. reasonCode: keepReasonCodeCompat(reasonCode, syntaxPlugin),
  1203. template: messages[reasonCode]
  1204. });
  1205. });
  1206. return Object.freeze(templates);
  1207. }
  1208. class ParserError extends CommentsParser {
  1209. getLocationForPosition(pos) {
  1210. let loc;
  1211. 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);
  1212. return loc;
  1213. }
  1214. raise(pos, {
  1215. code,
  1216. reasonCode,
  1217. template
  1218. }, ...params) {
  1219. return this.raiseWithData(pos, {
  1220. code,
  1221. reasonCode
  1222. }, template, ...params);
  1223. }
  1224. raiseOverwrite(pos, {
  1225. code,
  1226. template
  1227. }, ...params) {
  1228. const loc = this.getLocationForPosition(pos);
  1229. const message = template.replace(/%(\d+)/g, (_, i) => params[i]) + ` (${loc.line}:${loc.column})`;
  1230. if (this.options.errorRecovery) {
  1231. const errors = this.state.errors;
  1232. for (let i = errors.length - 1; i >= 0; i--) {
  1233. const error = errors[i];
  1234. if (error.pos === pos) {
  1235. return Object.assign(error, {
  1236. message
  1237. });
  1238. } else if (error.pos < pos) {
  1239. break;
  1240. }
  1241. }
  1242. }
  1243. return this._raise({
  1244. code,
  1245. loc,
  1246. pos
  1247. }, message);
  1248. }
  1249. raiseWithData(pos, data, errorTemplate, ...params) {
  1250. const loc = this.getLocationForPosition(pos);
  1251. const message = errorTemplate.replace(/%(\d+)/g, (_, i) => params[i]) + ` (${loc.line}:${loc.column})`;
  1252. return this._raise(Object.assign({
  1253. loc,
  1254. pos
  1255. }, data), message);
  1256. }
  1257. _raise(errorContext, message) {
  1258. const err = new SyntaxError(message);
  1259. Object.assign(err, errorContext);
  1260. if (this.options.errorRecovery) {
  1261. if (!this.isLookahead) this.state.errors.push(err);
  1262. return err;
  1263. } else {
  1264. throw err;
  1265. }
  1266. }
  1267. }
  1268. var estree = (superClass => class extends superClass {
  1269. parseRegExpLiteral({
  1270. pattern,
  1271. flags
  1272. }) {
  1273. let regex = null;
  1274. try {
  1275. regex = new RegExp(pattern, flags);
  1276. } catch (e) {}
  1277. const node = this.estreeParseLiteral(regex);
  1278. node.regex = {
  1279. pattern,
  1280. flags
  1281. };
  1282. return node;
  1283. }
  1284. parseBigIntLiteral(value) {
  1285. let bigInt;
  1286. try {
  1287. bigInt = BigInt(value);
  1288. } catch (_unused) {
  1289. bigInt = null;
  1290. }
  1291. const node = this.estreeParseLiteral(bigInt);
  1292. node.bigint = String(node.value || value);
  1293. return node;
  1294. }
  1295. parseDecimalLiteral(value) {
  1296. const decimal = null;
  1297. const node = this.estreeParseLiteral(decimal);
  1298. node.decimal = String(node.value || value);
  1299. return node;
  1300. }
  1301. estreeParseLiteral(value) {
  1302. return this.parseLiteral(value, "Literal");
  1303. }
  1304. parseStringLiteral(value) {
  1305. return this.estreeParseLiteral(value);
  1306. }
  1307. parseNumericLiteral(value) {
  1308. return this.estreeParseLiteral(value);
  1309. }
  1310. parseNullLiteral() {
  1311. return this.estreeParseLiteral(null);
  1312. }
  1313. parseBooleanLiteral(value) {
  1314. return this.estreeParseLiteral(value);
  1315. }
  1316. directiveToStmt(directive) {
  1317. const directiveLiteral = directive.value;
  1318. const stmt = this.startNodeAt(directive.start, directive.loc.start);
  1319. const expression = this.startNodeAt(directiveLiteral.start, directiveLiteral.loc.start);
  1320. expression.value = directiveLiteral.extra.expressionValue;
  1321. expression.raw = directiveLiteral.extra.raw;
  1322. stmt.expression = this.finishNodeAt(expression, "Literal", directiveLiteral.end, directiveLiteral.loc.end);
  1323. stmt.directive = directiveLiteral.extra.raw.slice(1, -1);
  1324. return this.finishNodeAt(stmt, "ExpressionStatement", directive.end, directive.loc.end);
  1325. }
  1326. initFunction(node, isAsync) {
  1327. super.initFunction(node, isAsync);
  1328. node.expression = false;
  1329. }
  1330. checkDeclaration(node) {
  1331. if (node != null && this.isObjectProperty(node)) {
  1332. this.checkDeclaration(node.value);
  1333. } else {
  1334. super.checkDeclaration(node);
  1335. }
  1336. }
  1337. getObjectOrClassMethodParams(method) {
  1338. return method.value.params;
  1339. }
  1340. isValidDirective(stmt) {
  1341. var _stmt$expression$extr;
  1342. return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && !((_stmt$expression$extr = stmt.expression.extra) != null && _stmt$expression$extr.parenthesized);
  1343. }
  1344. parseBlockBody(node, ...args) {
  1345. super.parseBlockBody(node, ...args);
  1346. const directiveStatements = node.directives.map(d => this.directiveToStmt(d));
  1347. node.body = directiveStatements.concat(node.body);
  1348. delete node.directives;
  1349. }
  1350. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  1351. this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true);
  1352. if (method.typeParameters) {
  1353. method.value.typeParameters = method.typeParameters;
  1354. delete method.typeParameters;
  1355. }
  1356. classBody.body.push(method);
  1357. }
  1358. parsePrivateName() {
  1359. const node = super.parsePrivateName();
  1360. {
  1361. if (!this.getPluginOption("estree", "classFeatures")) {
  1362. return node;
  1363. }
  1364. }
  1365. return this.convertPrivateNameToPrivateIdentifier(node);
  1366. }
  1367. convertPrivateNameToPrivateIdentifier(node) {
  1368. const name = super.getPrivateNameSV(node);
  1369. node = node;
  1370. delete node.id;
  1371. node.name = name;
  1372. node.type = "PrivateIdentifier";
  1373. return node;
  1374. }
  1375. isPrivateName(node) {
  1376. {
  1377. if (!this.getPluginOption("estree", "classFeatures")) {
  1378. return super.isPrivateName(node);
  1379. }
  1380. }
  1381. return node.type === "PrivateIdentifier";
  1382. }
  1383. getPrivateNameSV(node) {
  1384. {
  1385. if (!this.getPluginOption("estree", "classFeatures")) {
  1386. return super.getPrivateNameSV(node);
  1387. }
  1388. }
  1389. return node.name;
  1390. }
  1391. parseLiteral(value, type) {
  1392. const node = super.parseLiteral(value, type);
  1393. node.raw = node.extra.raw;
  1394. delete node.extra;
  1395. return node;
  1396. }
  1397. parseFunctionBody(node, allowExpression, isMethod = false) {
  1398. super.parseFunctionBody(node, allowExpression, isMethod);
  1399. node.expression = node.body.type !== "BlockStatement";
  1400. }
  1401. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  1402. let funcNode = this.startNode();
  1403. funcNode.kind = node.kind;
  1404. funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  1405. funcNode.type = "FunctionExpression";
  1406. delete funcNode.kind;
  1407. node.value = funcNode;
  1408. if (type === "ClassPrivateMethod") {
  1409. node.computed = false;
  1410. }
  1411. type = "MethodDefinition";
  1412. return this.finishNode(node, type);
  1413. }
  1414. parseClassProperty(...args) {
  1415. const propertyNode = super.parseClassProperty(...args);
  1416. {
  1417. if (!this.getPluginOption("estree", "classFeatures")) {
  1418. return propertyNode;
  1419. }
  1420. }
  1421. propertyNode.type = "PropertyDefinition";
  1422. return propertyNode;
  1423. }
  1424. parseClassPrivateProperty(...args) {
  1425. const propertyNode = super.parseClassPrivateProperty(...args);
  1426. {
  1427. if (!this.getPluginOption("estree", "classFeatures")) {
  1428. return propertyNode;
  1429. }
  1430. }
  1431. propertyNode.type = "PropertyDefinition";
  1432. propertyNode.computed = false;
  1433. return propertyNode;
  1434. }
  1435. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  1436. const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor);
  1437. if (node) {
  1438. node.type = "Property";
  1439. if (node.kind === "method") node.kind = "init";
  1440. node.shorthand = false;
  1441. }
  1442. return node;
  1443. }
  1444. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  1445. const node = super.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  1446. if (node) {
  1447. node.kind = "init";
  1448. node.type = "Property";
  1449. }
  1450. return node;
  1451. }
  1452. isAssignable(node, isBinding) {
  1453. if (node != null && this.isObjectProperty(node)) {
  1454. return this.isAssignable(node.value, isBinding);
  1455. }
  1456. return super.isAssignable(node, isBinding);
  1457. }
  1458. toAssignable(node, isLHS = false) {
  1459. if (node != null && this.isObjectProperty(node)) {
  1460. this.toAssignable(node.value, isLHS);
  1461. return node;
  1462. }
  1463. return super.toAssignable(node, isLHS);
  1464. }
  1465. toAssignableObjectExpressionProp(prop, ...args) {
  1466. if (prop.kind === "get" || prop.kind === "set") {
  1467. this.raise(prop.key.start, ErrorMessages.PatternHasAccessor);
  1468. } else if (prop.method) {
  1469. this.raise(prop.key.start, ErrorMessages.PatternHasMethod);
  1470. } else {
  1471. super.toAssignableObjectExpressionProp(prop, ...args);
  1472. }
  1473. }
  1474. finishCallExpression(node, optional) {
  1475. super.finishCallExpression(node, optional);
  1476. if (node.callee.type === "Import") {
  1477. node.type = "ImportExpression";
  1478. node.source = node.arguments[0];
  1479. if (this.hasPlugin("importAssertions")) {
  1480. var _node$arguments$;
  1481. node.attributes = (_node$arguments$ = node.arguments[1]) != null ? _node$arguments$ : null;
  1482. }
  1483. delete node.arguments;
  1484. delete node.callee;
  1485. }
  1486. return node;
  1487. }
  1488. toReferencedArguments(node) {
  1489. if (node.type === "ImportExpression") {
  1490. return;
  1491. }
  1492. super.toReferencedArguments(node);
  1493. }
  1494. parseExport(node) {
  1495. super.parseExport(node);
  1496. switch (node.type) {
  1497. case "ExportAllDeclaration":
  1498. node.exported = null;
  1499. break;
  1500. case "ExportNamedDeclaration":
  1501. if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") {
  1502. node.type = "ExportAllDeclaration";
  1503. node.exported = node.specifiers[0].exported;
  1504. delete node.specifiers;
  1505. }
  1506. break;
  1507. }
  1508. return node;
  1509. }
  1510. parseSubscript(base, startPos, startLoc, noCalls, state) {
  1511. const node = super.parseSubscript(base, startPos, startLoc, noCalls, state);
  1512. if (state.optionalChainMember) {
  1513. if (node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression") {
  1514. node.type = node.type.substring(8);
  1515. }
  1516. if (state.stop) {
  1517. const chain = this.startNodeAtNode(node);
  1518. chain.expression = node;
  1519. return this.finishNode(chain, "ChainExpression");
  1520. }
  1521. } else if (node.type === "MemberExpression" || node.type === "CallExpression") {
  1522. node.optional = false;
  1523. }
  1524. return node;
  1525. }
  1526. hasPropertyAsPrivateName(node) {
  1527. if (node.type === "ChainExpression") {
  1528. node = node.expression;
  1529. }
  1530. return super.hasPropertyAsPrivateName(node);
  1531. }
  1532. isOptionalChain(node) {
  1533. return node.type === "ChainExpression";
  1534. }
  1535. isObjectProperty(node) {
  1536. return node.type === "Property" && node.kind === "init" && !node.method;
  1537. }
  1538. isObjectMethod(node) {
  1539. return node.method || node.kind === "get" || node.kind === "set";
  1540. }
  1541. });
  1542. class TokContext {
  1543. constructor(token, preserveSpace) {
  1544. this.token = void 0;
  1545. this.preserveSpace = void 0;
  1546. this.token = token;
  1547. this.preserveSpace = !!preserveSpace;
  1548. }
  1549. }
  1550. const types = {
  1551. brace: new TokContext("{"),
  1552. template: new TokContext("`", true)
  1553. };
  1554. const beforeExpr = true;
  1555. const startsExpr = true;
  1556. const isLoop = true;
  1557. const isAssign = true;
  1558. const prefix = true;
  1559. const postfix = true;
  1560. class ExportedTokenType {
  1561. constructor(label, conf = {}) {
  1562. this.label = void 0;
  1563. this.keyword = void 0;
  1564. this.beforeExpr = void 0;
  1565. this.startsExpr = void 0;
  1566. this.rightAssociative = void 0;
  1567. this.isLoop = void 0;
  1568. this.isAssign = void 0;
  1569. this.prefix = void 0;
  1570. this.postfix = void 0;
  1571. this.binop = void 0;
  1572. this.label = label;
  1573. this.keyword = conf.keyword;
  1574. this.beforeExpr = !!conf.beforeExpr;
  1575. this.startsExpr = !!conf.startsExpr;
  1576. this.rightAssociative = !!conf.rightAssociative;
  1577. this.isLoop = !!conf.isLoop;
  1578. this.isAssign = !!conf.isAssign;
  1579. this.prefix = !!conf.prefix;
  1580. this.postfix = !!conf.postfix;
  1581. this.binop = conf.binop != null ? conf.binop : null;
  1582. {
  1583. this.updateContext = null;
  1584. }
  1585. }
  1586. }
  1587. const keywords$1 = new Map();
  1588. function createKeyword(name, options = {}) {
  1589. options.keyword = name;
  1590. const token = createToken(name, options);
  1591. keywords$1.set(name, token);
  1592. return token;
  1593. }
  1594. function createBinop(name, binop) {
  1595. return createToken(name, {
  1596. beforeExpr,
  1597. binop
  1598. });
  1599. }
  1600. let tokenTypeCounter = -1;
  1601. const tokenTypes = [];
  1602. const tokenLabels = [];
  1603. const tokenBinops = [];
  1604. const tokenBeforeExprs = [];
  1605. const tokenStartsExprs = [];
  1606. const tokenPrefixes = [];
  1607. function createToken(name, options = {}) {
  1608. var _options$binop, _options$beforeExpr, _options$startsExpr, _options$prefix;
  1609. ++tokenTypeCounter;
  1610. tokenLabels.push(name);
  1611. tokenBinops.push((_options$binop = options.binop) != null ? _options$binop : -1);
  1612. tokenBeforeExprs.push((_options$beforeExpr = options.beforeExpr) != null ? _options$beforeExpr : false);
  1613. tokenStartsExprs.push((_options$startsExpr = options.startsExpr) != null ? _options$startsExpr : false);
  1614. tokenPrefixes.push((_options$prefix = options.prefix) != null ? _options$prefix : false);
  1615. tokenTypes.push(new ExportedTokenType(name, options));
  1616. return tokenTypeCounter;
  1617. }
  1618. function createKeywordLike(name, options = {}) {
  1619. var _options$binop2, _options$beforeExpr2, _options$startsExpr2, _options$prefix2;
  1620. ++tokenTypeCounter;
  1621. keywords$1.set(name, tokenTypeCounter);
  1622. tokenLabels.push(name);
  1623. tokenBinops.push((_options$binop2 = options.binop) != null ? _options$binop2 : -1);
  1624. tokenBeforeExprs.push((_options$beforeExpr2 = options.beforeExpr) != null ? _options$beforeExpr2 : false);
  1625. tokenStartsExprs.push((_options$startsExpr2 = options.startsExpr) != null ? _options$startsExpr2 : false);
  1626. tokenPrefixes.push((_options$prefix2 = options.prefix) != null ? _options$prefix2 : false);
  1627. tokenTypes.push(new ExportedTokenType("name", options));
  1628. return tokenTypeCounter;
  1629. }
  1630. const tt = {
  1631. bracketL: createToken("[", {
  1632. beforeExpr,
  1633. startsExpr
  1634. }),
  1635. bracketHashL: createToken("#[", {
  1636. beforeExpr,
  1637. startsExpr
  1638. }),
  1639. bracketBarL: createToken("[|", {
  1640. beforeExpr,
  1641. startsExpr
  1642. }),
  1643. bracketR: createToken("]"),
  1644. bracketBarR: createToken("|]"),
  1645. braceL: createToken("{", {
  1646. beforeExpr,
  1647. startsExpr
  1648. }),
  1649. braceBarL: createToken("{|", {
  1650. beforeExpr,
  1651. startsExpr
  1652. }),
  1653. braceHashL: createToken("#{", {
  1654. beforeExpr,
  1655. startsExpr
  1656. }),
  1657. braceR: createToken("}", {
  1658. beforeExpr
  1659. }),
  1660. braceBarR: createToken("|}"),
  1661. parenL: createToken("(", {
  1662. beforeExpr,
  1663. startsExpr
  1664. }),
  1665. parenR: createToken(")"),
  1666. comma: createToken(",", {
  1667. beforeExpr
  1668. }),
  1669. semi: createToken(";", {
  1670. beforeExpr
  1671. }),
  1672. colon: createToken(":", {
  1673. beforeExpr
  1674. }),
  1675. doubleColon: createToken("::", {
  1676. beforeExpr
  1677. }),
  1678. dot: createToken("."),
  1679. question: createToken("?", {
  1680. beforeExpr
  1681. }),
  1682. questionDot: createToken("?."),
  1683. arrow: createToken("=>", {
  1684. beforeExpr
  1685. }),
  1686. template: createToken("template"),
  1687. ellipsis: createToken("...", {
  1688. beforeExpr
  1689. }),
  1690. backQuote: createToken("`", {
  1691. startsExpr
  1692. }),
  1693. dollarBraceL: createToken("${", {
  1694. beforeExpr,
  1695. startsExpr
  1696. }),
  1697. at: createToken("@"),
  1698. hash: createToken("#", {
  1699. startsExpr
  1700. }),
  1701. interpreterDirective: createToken("#!..."),
  1702. eq: createToken("=", {
  1703. beforeExpr,
  1704. isAssign
  1705. }),
  1706. assign: createToken("_=", {
  1707. beforeExpr,
  1708. isAssign
  1709. }),
  1710. slashAssign: createToken("_=", {
  1711. beforeExpr,
  1712. isAssign
  1713. }),
  1714. xorAssign: createToken("_=", {
  1715. beforeExpr,
  1716. isAssign
  1717. }),
  1718. moduloAssign: createToken("_=", {
  1719. beforeExpr,
  1720. isAssign
  1721. }),
  1722. incDec: createToken("++/--", {
  1723. prefix,
  1724. postfix,
  1725. startsExpr
  1726. }),
  1727. bang: createToken("!", {
  1728. beforeExpr,
  1729. prefix,
  1730. startsExpr
  1731. }),
  1732. tilde: createToken("~", {
  1733. beforeExpr,
  1734. prefix,
  1735. startsExpr
  1736. }),
  1737. pipeline: createBinop("|>", 0),
  1738. nullishCoalescing: createBinop("??", 1),
  1739. logicalOR: createBinop("||", 1),
  1740. logicalAND: createBinop("&&", 2),
  1741. bitwiseOR: createBinop("|", 3),
  1742. bitwiseXOR: createBinop("^", 4),
  1743. bitwiseAND: createBinop("&", 5),
  1744. equality: createBinop("==/!=/===/!==", 6),
  1745. lt: createBinop("</>/<=/>=", 7),
  1746. gt: createBinop("</>/<=/>=", 7),
  1747. relational: createBinop("</>/<=/>=", 7),
  1748. bitShift: createBinop("<</>>/>>>", 8),
  1749. plusMin: createToken("+/-", {
  1750. beforeExpr,
  1751. binop: 9,
  1752. prefix,
  1753. startsExpr
  1754. }),
  1755. modulo: createToken("%", {
  1756. binop: 10,
  1757. startsExpr
  1758. }),
  1759. star: createToken("*", {
  1760. binop: 10
  1761. }),
  1762. slash: createBinop("/", 10),
  1763. exponent: createToken("**", {
  1764. beforeExpr,
  1765. binop: 11,
  1766. rightAssociative: true
  1767. }),
  1768. _in: createKeyword("in", {
  1769. beforeExpr,
  1770. binop: 7
  1771. }),
  1772. _instanceof: createKeyword("instanceof", {
  1773. beforeExpr,
  1774. binop: 7
  1775. }),
  1776. _break: createKeyword("break"),
  1777. _case: createKeyword("case", {
  1778. beforeExpr
  1779. }),
  1780. _catch: createKeyword("catch"),
  1781. _continue: createKeyword("continue"),
  1782. _debugger: createKeyword("debugger"),
  1783. _default: createKeyword("default", {
  1784. beforeExpr
  1785. }),
  1786. _else: createKeyword("else", {
  1787. beforeExpr
  1788. }),
  1789. _finally: createKeyword("finally"),
  1790. _function: createKeyword("function", {
  1791. startsExpr
  1792. }),
  1793. _if: createKeyword("if"),
  1794. _return: createKeyword("return", {
  1795. beforeExpr
  1796. }),
  1797. _switch: createKeyword("switch"),
  1798. _throw: createKeyword("throw", {
  1799. beforeExpr,
  1800. prefix,
  1801. startsExpr
  1802. }),
  1803. _try: createKeyword("try"),
  1804. _var: createKeyword("var"),
  1805. _const: createKeyword("const"),
  1806. _with: createKeyword("with"),
  1807. _new: createKeyword("new", {
  1808. beforeExpr,
  1809. startsExpr
  1810. }),
  1811. _this: createKeyword("this", {
  1812. startsExpr
  1813. }),
  1814. _super: createKeyword("super", {
  1815. startsExpr
  1816. }),
  1817. _class: createKeyword("class", {
  1818. startsExpr
  1819. }),
  1820. _extends: createKeyword("extends", {
  1821. beforeExpr
  1822. }),
  1823. _export: createKeyword("export"),
  1824. _import: createKeyword("import", {
  1825. startsExpr
  1826. }),
  1827. _null: createKeyword("null", {
  1828. startsExpr
  1829. }),
  1830. _true: createKeyword("true", {
  1831. startsExpr
  1832. }),
  1833. _false: createKeyword("false", {
  1834. startsExpr
  1835. }),
  1836. _typeof: createKeyword("typeof", {
  1837. beforeExpr,
  1838. prefix,
  1839. startsExpr
  1840. }),
  1841. _void: createKeyword("void", {
  1842. beforeExpr,
  1843. prefix,
  1844. startsExpr
  1845. }),
  1846. _delete: createKeyword("delete", {
  1847. beforeExpr,
  1848. prefix,
  1849. startsExpr
  1850. }),
  1851. _do: createKeyword("do", {
  1852. isLoop,
  1853. beforeExpr
  1854. }),
  1855. _for: createKeyword("for", {
  1856. isLoop
  1857. }),
  1858. _while: createKeyword("while", {
  1859. isLoop
  1860. }),
  1861. _as: createKeywordLike("as", {
  1862. startsExpr
  1863. }),
  1864. _assert: createKeywordLike("assert", {
  1865. startsExpr
  1866. }),
  1867. _async: createKeywordLike("async", {
  1868. startsExpr
  1869. }),
  1870. _await: createKeywordLike("await", {
  1871. startsExpr
  1872. }),
  1873. _from: createKeywordLike("from", {
  1874. startsExpr
  1875. }),
  1876. _get: createKeywordLike("get", {
  1877. startsExpr
  1878. }),
  1879. _let: createKeywordLike("let", {
  1880. startsExpr
  1881. }),
  1882. _meta: createKeywordLike("meta", {
  1883. startsExpr
  1884. }),
  1885. _of: createKeywordLike("of", {
  1886. startsExpr
  1887. }),
  1888. _sent: createKeywordLike("sent", {
  1889. startsExpr
  1890. }),
  1891. _set: createKeywordLike("set", {
  1892. startsExpr
  1893. }),
  1894. _static: createKeywordLike("static", {
  1895. startsExpr
  1896. }),
  1897. _yield: createKeywordLike("yield", {
  1898. startsExpr
  1899. }),
  1900. _asserts: createKeywordLike("asserts", {
  1901. startsExpr
  1902. }),
  1903. _checks: createKeywordLike("checks", {
  1904. startsExpr
  1905. }),
  1906. _exports: createKeywordLike("exports", {
  1907. startsExpr
  1908. }),
  1909. _global: createKeywordLike("global", {
  1910. startsExpr
  1911. }),
  1912. _implements: createKeywordLike("implements", {
  1913. startsExpr
  1914. }),
  1915. _intrinsic: createKeywordLike("intrinsic", {
  1916. startsExpr
  1917. }),
  1918. _infer: createKeywordLike("infer", {
  1919. startsExpr
  1920. }),
  1921. _is: createKeywordLike("is", {
  1922. startsExpr
  1923. }),
  1924. _mixins: createKeywordLike("mixins", {
  1925. startsExpr
  1926. }),
  1927. _proto: createKeywordLike("proto", {
  1928. startsExpr
  1929. }),
  1930. _require: createKeywordLike("require", {
  1931. startsExpr
  1932. }),
  1933. _keyof: createKeywordLike("keyof", {
  1934. startsExpr
  1935. }),
  1936. _readonly: createKeywordLike("readonly", {
  1937. startsExpr
  1938. }),
  1939. _unique: createKeywordLike("unique", {
  1940. startsExpr
  1941. }),
  1942. _abstract: createKeywordLike("abstract", {
  1943. startsExpr
  1944. }),
  1945. _declare: createKeywordLike("declare", {
  1946. startsExpr
  1947. }),
  1948. _enum: createKeywordLike("enum", {
  1949. startsExpr
  1950. }),
  1951. _module: createKeywordLike("module", {
  1952. startsExpr
  1953. }),
  1954. _namespace: createKeywordLike("namespace", {
  1955. startsExpr
  1956. }),
  1957. _interface: createKeywordLike("interface", {
  1958. startsExpr
  1959. }),
  1960. _type: createKeywordLike("type", {
  1961. startsExpr
  1962. }),
  1963. _opaque: createKeywordLike("opaque", {
  1964. startsExpr
  1965. }),
  1966. name: createToken("name", {
  1967. startsExpr
  1968. }),
  1969. string: createToken("string", {
  1970. startsExpr
  1971. }),
  1972. num: createToken("num", {
  1973. startsExpr
  1974. }),
  1975. bigint: createToken("bigint", {
  1976. startsExpr
  1977. }),
  1978. decimal: createToken("decimal", {
  1979. startsExpr
  1980. }),
  1981. regexp: createToken("regexp", {
  1982. startsExpr
  1983. }),
  1984. privateName: createToken("#name", {
  1985. startsExpr
  1986. }),
  1987. eof: createToken("eof"),
  1988. jsxName: createToken("jsxName"),
  1989. jsxText: createToken("jsxText", {
  1990. beforeExpr: true
  1991. }),
  1992. jsxTagStart: createToken("jsxTagStart", {
  1993. startsExpr: true
  1994. }),
  1995. jsxTagEnd: createToken("jsxTagEnd"),
  1996. placeholder: createToken("%%", {
  1997. startsExpr: true
  1998. })
  1999. };
  2000. function tokenIsIdentifier(token) {
  2001. return token >= 87 && token <= 122;
  2002. }
  2003. function tokenKeywordOrIdentifierIsKeyword(token) {
  2004. return token <= 86;
  2005. }
  2006. function tokenIsKeywordOrIdentifier(token) {
  2007. return token >= 52 && token <= 122;
  2008. }
  2009. function tokenIsLiteralPropertyName(token) {
  2010. return token >= 52 && token <= 126;
  2011. }
  2012. function tokenComesBeforeExpression(token) {
  2013. return tokenBeforeExprs[token];
  2014. }
  2015. function tokenCanStartExpression(token) {
  2016. return tokenStartsExprs[token];
  2017. }
  2018. function tokenIsAssignment(token) {
  2019. return token >= 27 && token <= 31;
  2020. }
  2021. function tokenIsFlowInterfaceOrTypeOrOpaque(token) {
  2022. return token >= 119 && token <= 121;
  2023. }
  2024. function tokenIsLoop(token) {
  2025. return token >= 84 && token <= 86;
  2026. }
  2027. function tokenIsKeyword(token) {
  2028. return token >= 52 && token <= 86;
  2029. }
  2030. function tokenIsOperator(token) {
  2031. return token >= 35 && token <= 53;
  2032. }
  2033. function tokenIsPostfix(token) {
  2034. return token === 32;
  2035. }
  2036. function tokenIsPrefix(token) {
  2037. return tokenPrefixes[token];
  2038. }
  2039. function tokenIsTSTypeOperator(token) {
  2040. return token >= 111 && token <= 113;
  2041. }
  2042. function tokenIsTSDeclarationStart(token) {
  2043. return token >= 114 && token <= 120;
  2044. }
  2045. function tokenLabelName(token) {
  2046. return tokenLabels[token];
  2047. }
  2048. function tokenOperatorPrecedence(token) {
  2049. return tokenBinops[token];
  2050. }
  2051. function tokenIsRightAssociative(token) {
  2052. return token === 51;
  2053. }
  2054. function getExportedToken(token) {
  2055. return tokenTypes[token];
  2056. }
  2057. function isTokenType(obj) {
  2058. return typeof obj === "number";
  2059. }
  2060. {
  2061. tokenTypes[8].updateContext = context => {
  2062. context.pop();
  2063. };
  2064. tokenTypes[5].updateContext = tokenTypes[7].updateContext = tokenTypes[23].updateContext = context => {
  2065. context.push(types.brace);
  2066. };
  2067. tokenTypes[22].updateContext = context => {
  2068. if (context[context.length - 1] === types.template) {
  2069. context.pop();
  2070. } else {
  2071. context.push(types.template);
  2072. }
  2073. };
  2074. tokenTypes[132].updateContext = context => {
  2075. context.push(types.j_expr, types.j_oTag);
  2076. };
  2077. }
  2078. 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";
  2079. 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";
  2080. const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  2081. const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  2082. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  2083. 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];
  2084. 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];
  2085. function isInAstralSet(code, set) {
  2086. let pos = 0x10000;
  2087. for (let i = 0, length = set.length; i < length; i += 2) {
  2088. pos += set[i];
  2089. if (pos > code) return false;
  2090. pos += set[i + 1];
  2091. if (pos >= code) return true;
  2092. }
  2093. return false;
  2094. }
  2095. function isIdentifierStart(code) {
  2096. if (code < 65) return code === 36;
  2097. if (code <= 90) return true;
  2098. if (code < 97) return code === 95;
  2099. if (code <= 122) return true;
  2100. if (code <= 0xffff) {
  2101. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  2102. }
  2103. return isInAstralSet(code, astralIdentifierStartCodes);
  2104. }
  2105. function isIdentifierChar(code) {
  2106. if (code < 48) return code === 36;
  2107. if (code < 58) return true;
  2108. if (code < 65) return false;
  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 && nonASCIIidentifier.test(String.fromCharCode(code));
  2114. }
  2115. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
  2116. }
  2117. const reservedWords = {
  2118. 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"],
  2119. strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
  2120. strictBind: ["eval", "arguments"]
  2121. };
  2122. const keywords = new Set(reservedWords.keyword);
  2123. const reservedWordsStrictSet = new Set(reservedWords.strict);
  2124. const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
  2125. function isReservedWord(word, inModule) {
  2126. return inModule && word === "await" || word === "enum";
  2127. }
  2128. function isStrictReservedWord(word, inModule) {
  2129. return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
  2130. }
  2131. function isStrictBindOnlyReservedWord(word) {
  2132. return reservedWordsStrictBindSet.has(word);
  2133. }
  2134. function isStrictBindReservedWord(word, inModule) {
  2135. return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
  2136. }
  2137. function isKeyword(word) {
  2138. return keywords.has(word);
  2139. }
  2140. function isIteratorStart(current, next) {
  2141. return current === 64 && next === 64;
  2142. }
  2143. 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"]);
  2144. function canBeReservedWord(word) {
  2145. return reservedWordLikeSet.has(word);
  2146. }
  2147. const SCOPE_OTHER = 0b000000000,
  2148. SCOPE_PROGRAM = 0b000000001,
  2149. SCOPE_FUNCTION = 0b000000010,
  2150. SCOPE_ARROW = 0b000000100,
  2151. SCOPE_SIMPLE_CATCH = 0b000001000,
  2152. SCOPE_SUPER = 0b000010000,
  2153. SCOPE_DIRECT_SUPER = 0b000100000,
  2154. SCOPE_CLASS = 0b001000000,
  2155. SCOPE_STATIC_BLOCK = 0b010000000,
  2156. SCOPE_TS_MODULE = 0b100000000,
  2157. SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION | SCOPE_TS_MODULE;
  2158. const BIND_KIND_VALUE = 0b000000000001,
  2159. BIND_KIND_TYPE = 0b000000000010,
  2160. BIND_SCOPE_VAR = 0b000000000100,
  2161. BIND_SCOPE_LEXICAL = 0b000000001000,
  2162. BIND_SCOPE_FUNCTION = 0b000000010000,
  2163. BIND_FLAGS_NONE = 0b000001000000,
  2164. BIND_FLAGS_CLASS = 0b000010000000,
  2165. BIND_FLAGS_TS_ENUM = 0b000100000000,
  2166. BIND_FLAGS_TS_CONST_ENUM = 0b001000000000,
  2167. BIND_FLAGS_TS_EXPORT_ONLY = 0b010000000000,
  2168. BIND_FLAGS_FLOW_DECLARE_FN = 0b100000000000;
  2169. const BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS,
  2170. BIND_LEXICAL = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0,
  2171. BIND_VAR = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0,
  2172. BIND_FUNCTION = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0,
  2173. BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS,
  2174. BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0,
  2175. BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM,
  2176. BIND_TS_AMBIENT = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
  2177. BIND_NONE = 0 | 0 | 0 | BIND_FLAGS_NONE,
  2178. BIND_OUTSIDE = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE,
  2179. BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM,
  2180. BIND_TS_NAMESPACE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
  2181. BIND_FLOW_DECLARE_FN = BIND_FLAGS_FLOW_DECLARE_FN;
  2182. const CLASS_ELEMENT_FLAG_STATIC = 0b100,
  2183. CLASS_ELEMENT_KIND_GETTER = 0b010,
  2184. CLASS_ELEMENT_KIND_SETTER = 0b001,
  2185. CLASS_ELEMENT_KIND_ACCESSOR = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_KIND_SETTER;
  2186. const CLASS_ELEMENT_STATIC_GETTER = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_FLAG_STATIC,
  2187. CLASS_ELEMENT_STATIC_SETTER = CLASS_ELEMENT_KIND_SETTER | CLASS_ELEMENT_FLAG_STATIC,
  2188. CLASS_ELEMENT_INSTANCE_GETTER = CLASS_ELEMENT_KIND_GETTER,
  2189. CLASS_ELEMENT_INSTANCE_SETTER = CLASS_ELEMENT_KIND_SETTER,
  2190. CLASS_ELEMENT_OTHER = 0;
  2191. class Scope {
  2192. constructor(flags) {
  2193. this.var = new Set();
  2194. this.lexical = new Set();
  2195. this.functions = new Set();
  2196. this.flags = flags;
  2197. }
  2198. }
  2199. class ScopeHandler {
  2200. constructor(raise, inModule) {
  2201. this.scopeStack = [];
  2202. this.undefinedExports = new Map();
  2203. this.undefinedPrivateNames = new Map();
  2204. this.raise = raise;
  2205. this.inModule = inModule;
  2206. }
  2207. get inFunction() {
  2208. return (this.currentVarScopeFlags() & SCOPE_FUNCTION) > 0;
  2209. }
  2210. get allowSuper() {
  2211. return (this.currentThisScopeFlags() & SCOPE_SUPER) > 0;
  2212. }
  2213. get allowDirectSuper() {
  2214. return (this.currentThisScopeFlags() & SCOPE_DIRECT_SUPER) > 0;
  2215. }
  2216. get inClass() {
  2217. return (this.currentThisScopeFlags() & SCOPE_CLASS) > 0;
  2218. }
  2219. get inClassAndNotInNonArrowFunction() {
  2220. const flags = this.currentThisScopeFlags();
  2221. return (flags & SCOPE_CLASS) > 0 && (flags & SCOPE_FUNCTION) === 0;
  2222. }
  2223. get inStaticBlock() {
  2224. for (let i = this.scopeStack.length - 1;; i--) {
  2225. const {
  2226. flags
  2227. } = this.scopeStack[i];
  2228. if (flags & SCOPE_STATIC_BLOCK) {
  2229. return true;
  2230. }
  2231. if (flags & (SCOPE_VAR | SCOPE_CLASS)) {
  2232. return false;
  2233. }
  2234. }
  2235. }
  2236. get inNonArrowFunction() {
  2237. return (this.currentThisScopeFlags() & SCOPE_FUNCTION) > 0;
  2238. }
  2239. get treatFunctionsAsVar() {
  2240. return this.treatFunctionsAsVarInScope(this.currentScope());
  2241. }
  2242. createScope(flags) {
  2243. return new Scope(flags);
  2244. }
  2245. enter(flags) {
  2246. this.scopeStack.push(this.createScope(flags));
  2247. }
  2248. exit() {
  2249. this.scopeStack.pop();
  2250. }
  2251. treatFunctionsAsVarInScope(scope) {
  2252. return !!(scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_PROGRAM);
  2253. }
  2254. declareName(name, bindingType, pos) {
  2255. let scope = this.currentScope();
  2256. if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) {
  2257. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  2258. if (bindingType & BIND_SCOPE_FUNCTION) {
  2259. scope.functions.add(name);
  2260. } else {
  2261. scope.lexical.add(name);
  2262. }
  2263. if (bindingType & BIND_SCOPE_LEXICAL) {
  2264. this.maybeExportDefined(scope, name);
  2265. }
  2266. } else if (bindingType & BIND_SCOPE_VAR) {
  2267. for (let i = this.scopeStack.length - 1; i >= 0; --i) {
  2268. scope = this.scopeStack[i];
  2269. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  2270. scope.var.add(name);
  2271. this.maybeExportDefined(scope, name);
  2272. if (scope.flags & SCOPE_VAR) break;
  2273. }
  2274. }
  2275. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  2276. this.undefinedExports.delete(name);
  2277. }
  2278. }
  2279. maybeExportDefined(scope, name) {
  2280. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  2281. this.undefinedExports.delete(name);
  2282. }
  2283. }
  2284. checkRedeclarationInScope(scope, name, bindingType, pos) {
  2285. if (this.isRedeclaredInScope(scope, name, bindingType)) {
  2286. this.raise(pos, ErrorMessages.VarRedeclaration, name);
  2287. }
  2288. }
  2289. isRedeclaredInScope(scope, name, bindingType) {
  2290. if (!(bindingType & BIND_KIND_VALUE)) return false;
  2291. if (bindingType & BIND_SCOPE_LEXICAL) {
  2292. return scope.lexical.has(name) || scope.functions.has(name) || scope.var.has(name);
  2293. }
  2294. if (bindingType & BIND_SCOPE_FUNCTION) {
  2295. return scope.lexical.has(name) || !this.treatFunctionsAsVarInScope(scope) && scope.var.has(name);
  2296. }
  2297. return scope.lexical.has(name) && !(scope.flags & SCOPE_SIMPLE_CATCH && scope.lexical.values().next().value === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.has(name);
  2298. }
  2299. checkLocalExport(id) {
  2300. const {
  2301. name
  2302. } = id;
  2303. const topLevelScope = this.scopeStack[0];
  2304. if (!topLevelScope.lexical.has(name) && !topLevelScope.var.has(name) && !topLevelScope.functions.has(name)) {
  2305. this.undefinedExports.set(name, id.start);
  2306. }
  2307. }
  2308. currentScope() {
  2309. return this.scopeStack[this.scopeStack.length - 1];
  2310. }
  2311. currentVarScopeFlags() {
  2312. for (let i = this.scopeStack.length - 1;; i--) {
  2313. const {
  2314. flags
  2315. } = this.scopeStack[i];
  2316. if (flags & SCOPE_VAR) {
  2317. return flags;
  2318. }
  2319. }
  2320. }
  2321. currentThisScopeFlags() {
  2322. for (let i = this.scopeStack.length - 1;; i--) {
  2323. const {
  2324. flags
  2325. } = this.scopeStack[i];
  2326. if (flags & (SCOPE_VAR | SCOPE_CLASS) && !(flags & SCOPE_ARROW)) {
  2327. return flags;
  2328. }
  2329. }
  2330. }
  2331. }
  2332. class FlowScope extends Scope {
  2333. constructor(...args) {
  2334. super(...args);
  2335. this.declareFunctions = new Set();
  2336. }
  2337. }
  2338. class FlowScopeHandler extends ScopeHandler {
  2339. createScope(flags) {
  2340. return new FlowScope(flags);
  2341. }
  2342. declareName(name, bindingType, pos) {
  2343. const scope = this.currentScope();
  2344. if (bindingType & BIND_FLAGS_FLOW_DECLARE_FN) {
  2345. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  2346. this.maybeExportDefined(scope, name);
  2347. scope.declareFunctions.add(name);
  2348. return;
  2349. }
  2350. super.declareName(...arguments);
  2351. }
  2352. isRedeclaredInScope(scope, name, bindingType) {
  2353. if (super.isRedeclaredInScope(...arguments)) return true;
  2354. if (bindingType & BIND_FLAGS_FLOW_DECLARE_FN) {
  2355. return !scope.declareFunctions.has(name) && (scope.lexical.has(name) || scope.functions.has(name));
  2356. }
  2357. return false;
  2358. }
  2359. checkLocalExport(id) {
  2360. if (!this.scopeStack[0].declareFunctions.has(id.name)) {
  2361. super.checkLocalExport(id);
  2362. }
  2363. }
  2364. }
  2365. class State {
  2366. constructor() {
  2367. this.strict = void 0;
  2368. this.curLine = void 0;
  2369. this.lineStart = void 0;
  2370. this.startLoc = void 0;
  2371. this.endLoc = void 0;
  2372. this.errors = [];
  2373. this.potentialArrowAt = -1;
  2374. this.noArrowAt = [];
  2375. this.noArrowParamsConversionAt = [];
  2376. this.maybeInArrowParameters = false;
  2377. this.inType = false;
  2378. this.noAnonFunctionType = false;
  2379. this.hasFlowComment = false;
  2380. this.isAmbientContext = false;
  2381. this.inAbstractClass = false;
  2382. this.topicContext = {
  2383. maxNumOfResolvableTopics: 0,
  2384. maxTopicIndex: null
  2385. };
  2386. this.soloAwait = false;
  2387. this.inFSharpPipelineDirectBody = false;
  2388. this.labels = [];
  2389. this.decoratorStack = [[]];
  2390. this.comments = [];
  2391. this.commentStack = [];
  2392. this.pos = 0;
  2393. this.type = 129;
  2394. this.value = null;
  2395. this.start = 0;
  2396. this.end = 0;
  2397. this.lastTokEndLoc = null;
  2398. this.lastTokStartLoc = null;
  2399. this.lastTokStart = 0;
  2400. this.lastTokEnd = 0;
  2401. this.context = [types.brace];
  2402. this.canStartJSXElement = true;
  2403. this.containsEsc = false;
  2404. this.strictErrors = new Map();
  2405. this.tokensLength = 0;
  2406. }
  2407. init({
  2408. strictMode,
  2409. sourceType,
  2410. startLine,
  2411. startColumn
  2412. }) {
  2413. this.strict = strictMode === false ? false : strictMode === true ? true : sourceType === "module";
  2414. this.curLine = startLine;
  2415. this.lineStart = -startColumn;
  2416. this.startLoc = this.endLoc = new Position(startLine, startColumn);
  2417. }
  2418. curPosition() {
  2419. return new Position(this.curLine, this.pos - this.lineStart);
  2420. }
  2421. clone(skipArrays) {
  2422. const state = new State();
  2423. const keys = Object.keys(this);
  2424. for (let i = 0, length = keys.length; i < length; i++) {
  2425. const key = keys[i];
  2426. let val = this[key];
  2427. if (!skipArrays && Array.isArray(val)) {
  2428. val = val.slice();
  2429. }
  2430. state[key] = val;
  2431. }
  2432. return state;
  2433. }
  2434. }
  2435. var _isDigit = function isDigit(code) {
  2436. return code >= 48 && code <= 57;
  2437. };
  2438. const VALID_REGEX_FLAGS = new Set([103, 109, 115, 105, 121, 117, 100]);
  2439. const forbiddenNumericSeparatorSiblings = {
  2440. decBinOct: [46, 66, 69, 79, 95, 98, 101, 111],
  2441. hex: [46, 88, 95, 120]
  2442. };
  2443. const allowedNumericSeparatorSiblings = {};
  2444. allowedNumericSeparatorSiblings.bin = [48, 49];
  2445. allowedNumericSeparatorSiblings.oct = [...allowedNumericSeparatorSiblings.bin, 50, 51, 52, 53, 54, 55];
  2446. allowedNumericSeparatorSiblings.dec = [...allowedNumericSeparatorSiblings.oct, 56, 57];
  2447. allowedNumericSeparatorSiblings.hex = [...allowedNumericSeparatorSiblings.dec, 65, 66, 67, 68, 69, 70, 97, 98, 99, 100, 101, 102];
  2448. class Token {
  2449. constructor(state) {
  2450. this.type = state.type;
  2451. this.value = state.value;
  2452. this.start = state.start;
  2453. this.end = state.end;
  2454. this.loc = new SourceLocation(state.startLoc, state.endLoc);
  2455. }
  2456. }
  2457. class Tokenizer extends ParserError {
  2458. constructor(options, input) {
  2459. super();
  2460. this.isLookahead = void 0;
  2461. this.tokens = [];
  2462. this.state = new State();
  2463. this.state.init(options);
  2464. this.input = input;
  2465. this.length = input.length;
  2466. this.isLookahead = false;
  2467. }
  2468. pushToken(token) {
  2469. this.tokens.length = this.state.tokensLength;
  2470. this.tokens.push(token);
  2471. ++this.state.tokensLength;
  2472. }
  2473. next() {
  2474. this.checkKeywordEscapes();
  2475. if (this.options.tokens) {
  2476. this.pushToken(new Token(this.state));
  2477. }
  2478. this.state.lastTokEnd = this.state.end;
  2479. this.state.lastTokStart = this.state.start;
  2480. this.state.lastTokEndLoc = this.state.endLoc;
  2481. this.state.lastTokStartLoc = this.state.startLoc;
  2482. this.nextToken();
  2483. }
  2484. eat(type) {
  2485. if (this.match(type)) {
  2486. this.next();
  2487. return true;
  2488. } else {
  2489. return false;
  2490. }
  2491. }
  2492. match(type) {
  2493. return this.state.type === type;
  2494. }
  2495. createLookaheadState(state) {
  2496. return {
  2497. pos: state.pos,
  2498. value: null,
  2499. type: state.type,
  2500. start: state.start,
  2501. end: state.end,
  2502. lastTokEnd: state.end,
  2503. context: [this.curContext()],
  2504. inType: state.inType
  2505. };
  2506. }
  2507. lookahead() {
  2508. const old = this.state;
  2509. this.state = this.createLookaheadState(old);
  2510. this.isLookahead = true;
  2511. this.nextToken();
  2512. this.isLookahead = false;
  2513. const curr = this.state;
  2514. this.state = old;
  2515. return curr;
  2516. }
  2517. nextTokenStart() {
  2518. return this.nextTokenStartSince(this.state.pos);
  2519. }
  2520. nextTokenStartSince(pos) {
  2521. skipWhiteSpace.lastIndex = pos;
  2522. return skipWhiteSpace.test(this.input) ? skipWhiteSpace.lastIndex : pos;
  2523. }
  2524. lookaheadCharCode() {
  2525. return this.input.charCodeAt(this.nextTokenStart());
  2526. }
  2527. codePointAtPos(pos) {
  2528. let cp = this.input.charCodeAt(pos);
  2529. if ((cp & 0xfc00) === 0xd800 && ++pos < this.input.length) {
  2530. const trail = this.input.charCodeAt(pos);
  2531. if ((trail & 0xfc00) === 0xdc00) {
  2532. cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);
  2533. }
  2534. }
  2535. return cp;
  2536. }
  2537. setStrict(strict) {
  2538. this.state.strict = strict;
  2539. if (strict) {
  2540. this.state.strictErrors.forEach((message, pos) => this.raise(pos, message));
  2541. this.state.strictErrors.clear();
  2542. }
  2543. }
  2544. curContext() {
  2545. return this.state.context[this.state.context.length - 1];
  2546. }
  2547. nextToken() {
  2548. const curContext = this.curContext();
  2549. if (!curContext.preserveSpace) this.skipSpace();
  2550. this.state.start = this.state.pos;
  2551. if (!this.isLookahead) this.state.startLoc = this.state.curPosition();
  2552. if (this.state.pos >= this.length) {
  2553. this.finishToken(129);
  2554. return;
  2555. }
  2556. if (curContext === types.template) {
  2557. this.readTmplToken();
  2558. } else {
  2559. this.getTokenFromCode(this.codePointAtPos(this.state.pos));
  2560. }
  2561. }
  2562. skipBlockComment() {
  2563. let startLoc;
  2564. if (!this.isLookahead) startLoc = this.state.curPosition();
  2565. const start = this.state.pos;
  2566. const end = this.input.indexOf("*/", start + 2);
  2567. if (end === -1) throw this.raise(start, ErrorMessages.UnterminatedComment);
  2568. this.state.pos = end + 2;
  2569. lineBreakG.lastIndex = start + 2;
  2570. while (lineBreakG.test(this.input) && lineBreakG.lastIndex <= end) {
  2571. ++this.state.curLine;
  2572. this.state.lineStart = lineBreakG.lastIndex;
  2573. }
  2574. if (this.isLookahead) return;
  2575. const comment = {
  2576. type: "CommentBlock",
  2577. value: this.input.slice(start + 2, end),
  2578. start,
  2579. end: end + 2,
  2580. loc: new SourceLocation(startLoc, this.state.curPosition())
  2581. };
  2582. if (this.options.tokens) this.pushToken(comment);
  2583. return comment;
  2584. }
  2585. skipLineComment(startSkip) {
  2586. const start = this.state.pos;
  2587. let startLoc;
  2588. if (!this.isLookahead) startLoc = this.state.curPosition();
  2589. let ch = this.input.charCodeAt(this.state.pos += startSkip);
  2590. if (this.state.pos < this.length) {
  2591. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  2592. ch = this.input.charCodeAt(this.state.pos);
  2593. }
  2594. }
  2595. if (this.isLookahead) return;
  2596. const end = this.state.pos;
  2597. const value = this.input.slice(start + startSkip, end);
  2598. const comment = {
  2599. type: "CommentLine",
  2600. value,
  2601. start,
  2602. end,
  2603. loc: new SourceLocation(startLoc, this.state.curPosition())
  2604. };
  2605. if (this.options.tokens) this.pushToken(comment);
  2606. return comment;
  2607. }
  2608. skipSpace() {
  2609. const spaceStart = this.state.pos;
  2610. const comments = [];
  2611. loop: while (this.state.pos < this.length) {
  2612. const ch = this.input.charCodeAt(this.state.pos);
  2613. switch (ch) {
  2614. case 32:
  2615. case 160:
  2616. case 9:
  2617. ++this.state.pos;
  2618. break;
  2619. case 13:
  2620. if (this.input.charCodeAt(this.state.pos + 1) === 10) {
  2621. ++this.state.pos;
  2622. }
  2623. case 10:
  2624. case 8232:
  2625. case 8233:
  2626. ++this.state.pos;
  2627. ++this.state.curLine;
  2628. this.state.lineStart = this.state.pos;
  2629. break;
  2630. case 47:
  2631. switch (this.input.charCodeAt(this.state.pos + 1)) {
  2632. case 42:
  2633. {
  2634. const comment = this.skipBlockComment();
  2635. if (comment !== undefined) {
  2636. this.addComment(comment);
  2637. if (this.options.attachComment) comments.push(comment);
  2638. }
  2639. break;
  2640. }
  2641. case 47:
  2642. {
  2643. const comment = this.skipLineComment(2);
  2644. if (comment !== undefined) {
  2645. this.addComment(comment);
  2646. if (this.options.attachComment) comments.push(comment);
  2647. }
  2648. break;
  2649. }
  2650. default:
  2651. break loop;
  2652. }
  2653. break;
  2654. default:
  2655. if (isWhitespace(ch)) {
  2656. ++this.state.pos;
  2657. } else if (ch === 45 && !this.inModule) {
  2658. const pos = this.state.pos;
  2659. if (this.input.charCodeAt(pos + 1) === 45 && this.input.charCodeAt(pos + 2) === 62 && (spaceStart === 0 || this.state.lineStart > spaceStart)) {
  2660. const comment = this.skipLineComment(3);
  2661. if (comment !== undefined) {
  2662. this.addComment(comment);
  2663. if (this.options.attachComment) comments.push(comment);
  2664. }
  2665. } else {
  2666. break loop;
  2667. }
  2668. } else if (ch === 60 && !this.inModule) {
  2669. const pos = this.state.pos;
  2670. if (this.input.charCodeAt(pos + 1) === 33 && this.input.charCodeAt(pos + 2) === 45 && this.input.charCodeAt(pos + 3) === 45) {
  2671. const comment = this.skipLineComment(4);
  2672. if (comment !== undefined) {
  2673. this.addComment(comment);
  2674. if (this.options.attachComment) comments.push(comment);
  2675. }
  2676. } else {
  2677. break loop;
  2678. }
  2679. } else {
  2680. break loop;
  2681. }
  2682. }
  2683. }
  2684. if (comments.length > 0) {
  2685. const end = this.state.pos;
  2686. const CommentWhitespace = {
  2687. start: spaceStart,
  2688. end,
  2689. comments,
  2690. leadingNode: null,
  2691. trailingNode: null,
  2692. containingNode: null
  2693. };
  2694. this.state.commentStack.push(CommentWhitespace);
  2695. }
  2696. }
  2697. finishToken(type, val) {
  2698. this.state.end = this.state.pos;
  2699. const prevType = this.state.type;
  2700. this.state.type = type;
  2701. this.state.value = val;
  2702. if (!this.isLookahead) {
  2703. this.state.endLoc = this.state.curPosition();
  2704. this.updateContext(prevType);
  2705. }
  2706. }
  2707. replaceToken(type) {
  2708. this.state.type = type;
  2709. this.updateContext();
  2710. }
  2711. readToken_numberSign() {
  2712. if (this.state.pos === 0 && this.readToken_interpreter()) {
  2713. return;
  2714. }
  2715. const nextPos = this.state.pos + 1;
  2716. const next = this.codePointAtPos(nextPos);
  2717. if (next >= 48 && next <= 57) {
  2718. throw this.raise(this.state.pos, ErrorMessages.UnexpectedDigitAfterHash);
  2719. }
  2720. if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) {
  2721. this.expectPlugin("recordAndTuple");
  2722. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "hash") {
  2723. throw this.raise(this.state.pos, next === 123 ? ErrorMessages.RecordExpressionHashIncorrectStartSyntaxType : ErrorMessages.TupleExpressionHashIncorrectStartSyntaxType);
  2724. }
  2725. this.state.pos += 2;
  2726. if (next === 123) {
  2727. this.finishToken(7);
  2728. } else {
  2729. this.finishToken(1);
  2730. }
  2731. } else if (isIdentifierStart(next)) {
  2732. ++this.state.pos;
  2733. this.finishToken(128, this.readWord1(next));
  2734. } else if (next === 92) {
  2735. ++this.state.pos;
  2736. this.finishToken(128, this.readWord1());
  2737. } else {
  2738. this.finishOp(25, 1);
  2739. }
  2740. }
  2741. readToken_dot() {
  2742. const next = this.input.charCodeAt(this.state.pos + 1);
  2743. if (next >= 48 && next <= 57) {
  2744. this.readNumber(true);
  2745. return;
  2746. }
  2747. if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) {
  2748. this.state.pos += 3;
  2749. this.finishToken(21);
  2750. } else {
  2751. ++this.state.pos;
  2752. this.finishToken(16);
  2753. }
  2754. }
  2755. readToken_slash() {
  2756. const next = this.input.charCodeAt(this.state.pos + 1);
  2757. if (next === 61) {
  2758. this.finishOp(29, 2);
  2759. } else {
  2760. this.finishOp(50, 1);
  2761. }
  2762. }
  2763. readToken_interpreter() {
  2764. if (this.state.pos !== 0 || this.length < 2) return false;
  2765. let ch = this.input.charCodeAt(this.state.pos + 1);
  2766. if (ch !== 33) return false;
  2767. const start = this.state.pos;
  2768. this.state.pos += 1;
  2769. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  2770. ch = this.input.charCodeAt(this.state.pos);
  2771. }
  2772. const value = this.input.slice(start + 2, this.state.pos);
  2773. this.finishToken(26, value);
  2774. return true;
  2775. }
  2776. readToken_mult_modulo(code) {
  2777. let type = code === 42 ? 49 : 48;
  2778. let width = 1;
  2779. let next = this.input.charCodeAt(this.state.pos + 1);
  2780. if (code === 42 && next === 42) {
  2781. width++;
  2782. next = this.input.charCodeAt(this.state.pos + 2);
  2783. type = 51;
  2784. }
  2785. if (next === 61 && !this.state.inType) {
  2786. width++;
  2787. type = code === 37 ? 31 : 28;
  2788. }
  2789. this.finishOp(type, width);
  2790. }
  2791. readToken_pipe_amp(code) {
  2792. const next = this.input.charCodeAt(this.state.pos + 1);
  2793. if (next === code) {
  2794. if (this.input.charCodeAt(this.state.pos + 2) === 61) {
  2795. this.finishOp(28, 3);
  2796. } else {
  2797. this.finishOp(code === 124 ? 37 : 38, 2);
  2798. }
  2799. return;
  2800. }
  2801. if (code === 124) {
  2802. if (next === 62) {
  2803. this.finishOp(35, 2);
  2804. return;
  2805. }
  2806. if (this.hasPlugin("recordAndTuple") && next === 125) {
  2807. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2808. throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectEndSyntaxType);
  2809. }
  2810. this.state.pos += 2;
  2811. this.finishToken(9);
  2812. return;
  2813. }
  2814. if (this.hasPlugin("recordAndTuple") && next === 93) {
  2815. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2816. throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectEndSyntaxType);
  2817. }
  2818. this.state.pos += 2;
  2819. this.finishToken(4);
  2820. return;
  2821. }
  2822. }
  2823. if (next === 61) {
  2824. this.finishOp(28, 2);
  2825. return;
  2826. }
  2827. this.finishOp(code === 124 ? 39 : 41, 1);
  2828. }
  2829. readToken_caret() {
  2830. const next = this.input.charCodeAt(this.state.pos + 1);
  2831. if (next === 61 && !this.state.inType) {
  2832. this.finishOp(30, 2);
  2833. } else {
  2834. this.finishOp(40, 1);
  2835. }
  2836. }
  2837. readToken_plus_min(code) {
  2838. const next = this.input.charCodeAt(this.state.pos + 1);
  2839. if (next === code) {
  2840. this.finishOp(32, 2);
  2841. return;
  2842. }
  2843. if (next === 61) {
  2844. this.finishOp(28, 2);
  2845. } else {
  2846. this.finishOp(47, 1);
  2847. }
  2848. }
  2849. readToken_lt() {
  2850. const {
  2851. pos
  2852. } = this.state;
  2853. const next = this.input.charCodeAt(pos + 1);
  2854. if (next === 60) {
  2855. if (this.input.charCodeAt(pos + 2) === 61) {
  2856. this.finishOp(28, 3);
  2857. return;
  2858. }
  2859. this.finishOp(46, 2);
  2860. return;
  2861. }
  2862. if (next === 61) {
  2863. this.finishOp(45, 2);
  2864. return;
  2865. }
  2866. this.finishOp(43, 1);
  2867. }
  2868. readToken_gt() {
  2869. const {
  2870. pos
  2871. } = this.state;
  2872. const next = this.input.charCodeAt(pos + 1);
  2873. if (next === 62) {
  2874. const size = this.input.charCodeAt(pos + 2) === 62 ? 3 : 2;
  2875. if (this.input.charCodeAt(pos + size) === 61) {
  2876. this.finishOp(28, size + 1);
  2877. return;
  2878. }
  2879. this.finishOp(46, size);
  2880. return;
  2881. }
  2882. if (next === 61) {
  2883. this.finishOp(45, 2);
  2884. return;
  2885. }
  2886. this.finishOp(44, 1);
  2887. }
  2888. readToken_eq_excl(code) {
  2889. const next = this.input.charCodeAt(this.state.pos + 1);
  2890. if (next === 61) {
  2891. this.finishOp(42, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
  2892. return;
  2893. }
  2894. if (code === 61 && next === 62) {
  2895. this.state.pos += 2;
  2896. this.finishToken(19);
  2897. return;
  2898. }
  2899. this.finishOp(code === 61 ? 27 : 33, 1);
  2900. }
  2901. readToken_question() {
  2902. const next = this.input.charCodeAt(this.state.pos + 1);
  2903. const next2 = this.input.charCodeAt(this.state.pos + 2);
  2904. if (next === 63) {
  2905. if (next2 === 61) {
  2906. this.finishOp(28, 3);
  2907. } else {
  2908. this.finishOp(36, 2);
  2909. }
  2910. } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) {
  2911. this.state.pos += 2;
  2912. this.finishToken(18);
  2913. } else {
  2914. ++this.state.pos;
  2915. this.finishToken(17);
  2916. }
  2917. }
  2918. getTokenFromCode(code) {
  2919. switch (code) {
  2920. case 46:
  2921. this.readToken_dot();
  2922. return;
  2923. case 40:
  2924. ++this.state.pos;
  2925. this.finishToken(10);
  2926. return;
  2927. case 41:
  2928. ++this.state.pos;
  2929. this.finishToken(11);
  2930. return;
  2931. case 59:
  2932. ++this.state.pos;
  2933. this.finishToken(13);
  2934. return;
  2935. case 44:
  2936. ++this.state.pos;
  2937. this.finishToken(12);
  2938. return;
  2939. case 91:
  2940. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  2941. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2942. throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectStartSyntaxType);
  2943. }
  2944. this.state.pos += 2;
  2945. this.finishToken(2);
  2946. } else {
  2947. ++this.state.pos;
  2948. this.finishToken(0);
  2949. }
  2950. return;
  2951. case 93:
  2952. ++this.state.pos;
  2953. this.finishToken(3);
  2954. return;
  2955. case 123:
  2956. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  2957. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  2958. throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectStartSyntaxType);
  2959. }
  2960. this.state.pos += 2;
  2961. this.finishToken(6);
  2962. } else {
  2963. ++this.state.pos;
  2964. this.finishToken(5);
  2965. }
  2966. return;
  2967. case 125:
  2968. ++this.state.pos;
  2969. this.finishToken(8);
  2970. return;
  2971. case 58:
  2972. if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
  2973. this.finishOp(15, 2);
  2974. } else {
  2975. ++this.state.pos;
  2976. this.finishToken(14);
  2977. }
  2978. return;
  2979. case 63:
  2980. this.readToken_question();
  2981. return;
  2982. case 96:
  2983. ++this.state.pos;
  2984. this.finishToken(22);
  2985. return;
  2986. case 48:
  2987. {
  2988. const next = this.input.charCodeAt(this.state.pos + 1);
  2989. if (next === 120 || next === 88) {
  2990. this.readRadixNumber(16);
  2991. return;
  2992. }
  2993. if (next === 111 || next === 79) {
  2994. this.readRadixNumber(8);
  2995. return;
  2996. }
  2997. if (next === 98 || next === 66) {
  2998. this.readRadixNumber(2);
  2999. return;
  3000. }
  3001. }
  3002. case 49:
  3003. case 50:
  3004. case 51:
  3005. case 52:
  3006. case 53:
  3007. case 54:
  3008. case 55:
  3009. case 56:
  3010. case 57:
  3011. this.readNumber(false);
  3012. return;
  3013. case 34:
  3014. case 39:
  3015. this.readString(code);
  3016. return;
  3017. case 47:
  3018. this.readToken_slash();
  3019. return;
  3020. case 37:
  3021. case 42:
  3022. this.readToken_mult_modulo(code);
  3023. return;
  3024. case 124:
  3025. case 38:
  3026. this.readToken_pipe_amp(code);
  3027. return;
  3028. case 94:
  3029. this.readToken_caret();
  3030. return;
  3031. case 43:
  3032. case 45:
  3033. this.readToken_plus_min(code);
  3034. return;
  3035. case 60:
  3036. this.readToken_lt();
  3037. return;
  3038. case 62:
  3039. this.readToken_gt();
  3040. return;
  3041. case 61:
  3042. case 33:
  3043. this.readToken_eq_excl(code);
  3044. return;
  3045. case 126:
  3046. this.finishOp(34, 1);
  3047. return;
  3048. case 64:
  3049. ++this.state.pos;
  3050. this.finishToken(24);
  3051. return;
  3052. case 35:
  3053. this.readToken_numberSign();
  3054. return;
  3055. case 92:
  3056. this.readWord();
  3057. return;
  3058. default:
  3059. if (isIdentifierStart(code)) {
  3060. this.readWord(code);
  3061. return;
  3062. }
  3063. }
  3064. throw this.raise(this.state.pos, ErrorMessages.InvalidOrUnexpectedToken, String.fromCodePoint(code));
  3065. }
  3066. finishOp(type, size) {
  3067. const str = this.input.slice(this.state.pos, this.state.pos + size);
  3068. this.state.pos += size;
  3069. this.finishToken(type, str);
  3070. }
  3071. readRegexp() {
  3072. const start = this.state.start + 1;
  3073. let escaped, inClass;
  3074. let {
  3075. pos
  3076. } = this.state;
  3077. for (;; ++pos) {
  3078. if (pos >= this.length) {
  3079. throw this.raise(start, ErrorMessages.UnterminatedRegExp);
  3080. }
  3081. const ch = this.input.charCodeAt(pos);
  3082. if (isNewLine(ch)) {
  3083. throw this.raise(start, ErrorMessages.UnterminatedRegExp);
  3084. }
  3085. if (escaped) {
  3086. escaped = false;
  3087. } else {
  3088. if (ch === 91) {
  3089. inClass = true;
  3090. } else if (ch === 93 && inClass) {
  3091. inClass = false;
  3092. } else if (ch === 47 && !inClass) {
  3093. break;
  3094. }
  3095. escaped = ch === 92;
  3096. }
  3097. }
  3098. const content = this.input.slice(start, pos);
  3099. ++pos;
  3100. let mods = "";
  3101. while (pos < this.length) {
  3102. const cp = this.codePointAtPos(pos);
  3103. const char = String.fromCharCode(cp);
  3104. if (VALID_REGEX_FLAGS.has(cp)) {
  3105. if (mods.includes(char)) {
  3106. this.raise(pos + 1, ErrorMessages.DuplicateRegExpFlags);
  3107. }
  3108. } else if (isIdentifierChar(cp) || cp === 92) {
  3109. this.raise(pos + 1, ErrorMessages.MalformedRegExpFlags);
  3110. } else {
  3111. break;
  3112. }
  3113. ++pos;
  3114. mods += char;
  3115. }
  3116. this.state.pos = pos;
  3117. this.finishToken(127, {
  3118. pattern: content,
  3119. flags: mods
  3120. });
  3121. }
  3122. readInt(radix, len, forceLen, allowNumSeparator = true) {
  3123. const start = this.state.pos;
  3124. const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct;
  3125. const allowedSiblings = radix === 16 ? allowedNumericSeparatorSiblings.hex : radix === 10 ? allowedNumericSeparatorSiblings.dec : radix === 8 ? allowedNumericSeparatorSiblings.oct : allowedNumericSeparatorSiblings.bin;
  3126. let invalid = false;
  3127. let total = 0;
  3128. for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  3129. const code = this.input.charCodeAt(this.state.pos);
  3130. let val;
  3131. if (code === 95) {
  3132. const prev = this.input.charCodeAt(this.state.pos - 1);
  3133. const next = this.input.charCodeAt(this.state.pos + 1);
  3134. if (allowedSiblings.indexOf(next) === -1) {
  3135. this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator);
  3136. } else if (forbiddenSiblings.indexOf(prev) > -1 || forbiddenSiblings.indexOf(next) > -1 || Number.isNaN(next)) {
  3137. this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator);
  3138. }
  3139. if (!allowNumSeparator) {
  3140. this.raise(this.state.pos, ErrorMessages.NumericSeparatorInEscapeSequence);
  3141. }
  3142. ++this.state.pos;
  3143. continue;
  3144. }
  3145. if (code >= 97) {
  3146. val = code - 97 + 10;
  3147. } else if (code >= 65) {
  3148. val = code - 65 + 10;
  3149. } else if (_isDigit(code)) {
  3150. val = code - 48;
  3151. } else {
  3152. val = Infinity;
  3153. }
  3154. if (val >= radix) {
  3155. if (this.options.errorRecovery && val <= 9) {
  3156. val = 0;
  3157. this.raise(this.state.start + i + 2, ErrorMessages.InvalidDigit, radix);
  3158. } else if (forceLen) {
  3159. val = 0;
  3160. invalid = true;
  3161. } else {
  3162. break;
  3163. }
  3164. }
  3165. ++this.state.pos;
  3166. total = total * radix + val;
  3167. }
  3168. if (this.state.pos === start || len != null && this.state.pos - start !== len || invalid) {
  3169. return null;
  3170. }
  3171. return total;
  3172. }
  3173. readRadixNumber(radix) {
  3174. const start = this.state.pos;
  3175. let isBigInt = false;
  3176. this.state.pos += 2;
  3177. const val = this.readInt(radix);
  3178. if (val == null) {
  3179. this.raise(this.state.start + 2, ErrorMessages.InvalidDigit, radix);
  3180. }
  3181. const next = this.input.charCodeAt(this.state.pos);
  3182. if (next === 110) {
  3183. ++this.state.pos;
  3184. isBigInt = true;
  3185. } else if (next === 109) {
  3186. throw this.raise(start, ErrorMessages.InvalidDecimal);
  3187. }
  3188. if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {
  3189. throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier);
  3190. }
  3191. if (isBigInt) {
  3192. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  3193. this.finishToken(125, str);
  3194. return;
  3195. }
  3196. this.finishToken(124, val);
  3197. }
  3198. readNumber(startsWithDot) {
  3199. const start = this.state.pos;
  3200. let isFloat = false;
  3201. let isBigInt = false;
  3202. let isDecimal = false;
  3203. let hasExponent = false;
  3204. let isOctal = false;
  3205. if (!startsWithDot && this.readInt(10) === null) {
  3206. this.raise(start, ErrorMessages.InvalidNumber);
  3207. }
  3208. const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  3209. if (hasLeadingZero) {
  3210. const integer = this.input.slice(start, this.state.pos);
  3211. this.recordStrictModeErrors(start, ErrorMessages.StrictOctalLiteral);
  3212. if (!this.state.strict) {
  3213. const underscorePos = integer.indexOf("_");
  3214. if (underscorePos > 0) {
  3215. this.raise(underscorePos + start, ErrorMessages.ZeroDigitNumericSeparator);
  3216. }
  3217. }
  3218. isOctal = hasLeadingZero && !/[89]/.test(integer);
  3219. }
  3220. let next = this.input.charCodeAt(this.state.pos);
  3221. if (next === 46 && !isOctal) {
  3222. ++this.state.pos;
  3223. this.readInt(10);
  3224. isFloat = true;
  3225. next = this.input.charCodeAt(this.state.pos);
  3226. }
  3227. if ((next === 69 || next === 101) && !isOctal) {
  3228. next = this.input.charCodeAt(++this.state.pos);
  3229. if (next === 43 || next === 45) {
  3230. ++this.state.pos;
  3231. }
  3232. if (this.readInt(10) === null) {
  3233. this.raise(start, ErrorMessages.InvalidOrMissingExponent);
  3234. }
  3235. isFloat = true;
  3236. hasExponent = true;
  3237. next = this.input.charCodeAt(this.state.pos);
  3238. }
  3239. if (next === 110) {
  3240. if (isFloat || hasLeadingZero) {
  3241. this.raise(start, ErrorMessages.InvalidBigIntLiteral);
  3242. }
  3243. ++this.state.pos;
  3244. isBigInt = true;
  3245. }
  3246. if (next === 109) {
  3247. this.expectPlugin("decimal", this.state.pos);
  3248. if (hasExponent || hasLeadingZero) {
  3249. this.raise(start, ErrorMessages.InvalidDecimal);
  3250. }
  3251. ++this.state.pos;
  3252. isDecimal = true;
  3253. }
  3254. if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {
  3255. throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier);
  3256. }
  3257. const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, "");
  3258. if (isBigInt) {
  3259. this.finishToken(125, str);
  3260. return;
  3261. }
  3262. if (isDecimal) {
  3263. this.finishToken(126, str);
  3264. return;
  3265. }
  3266. const val = isOctal ? parseInt(str, 8) : parseFloat(str);
  3267. this.finishToken(124, val);
  3268. }
  3269. readCodePoint(throwOnInvalid) {
  3270. const ch = this.input.charCodeAt(this.state.pos);
  3271. let code;
  3272. if (ch === 123) {
  3273. const codePos = ++this.state.pos;
  3274. code = this.readHexChar(this.input.indexOf("}", this.state.pos) - this.state.pos, true, throwOnInvalid);
  3275. ++this.state.pos;
  3276. if (code !== null && code > 0x10ffff) {
  3277. if (throwOnInvalid) {
  3278. this.raise(codePos, ErrorMessages.InvalidCodePoint);
  3279. } else {
  3280. return null;
  3281. }
  3282. }
  3283. } else {
  3284. code = this.readHexChar(4, false, throwOnInvalid);
  3285. }
  3286. return code;
  3287. }
  3288. readString(quote) {
  3289. let out = "",
  3290. chunkStart = ++this.state.pos;
  3291. for (;;) {
  3292. if (this.state.pos >= this.length) {
  3293. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  3294. }
  3295. const ch = this.input.charCodeAt(this.state.pos);
  3296. if (ch === quote) break;
  3297. if (ch === 92) {
  3298. out += this.input.slice(chunkStart, this.state.pos);
  3299. out += this.readEscapedChar(false);
  3300. chunkStart = this.state.pos;
  3301. } else if (ch === 8232 || ch === 8233) {
  3302. ++this.state.pos;
  3303. ++this.state.curLine;
  3304. this.state.lineStart = this.state.pos;
  3305. } else if (isNewLine(ch)) {
  3306. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  3307. } else {
  3308. ++this.state.pos;
  3309. }
  3310. }
  3311. out += this.input.slice(chunkStart, this.state.pos++);
  3312. this.finishToken(123, out);
  3313. }
  3314. readTmplToken() {
  3315. let out = "",
  3316. chunkStart = this.state.pos,
  3317. containsInvalid = false;
  3318. for (;;) {
  3319. if (this.state.pos >= this.length) {
  3320. throw this.raise(this.state.start, ErrorMessages.UnterminatedTemplate);
  3321. }
  3322. const ch = this.input.charCodeAt(this.state.pos);
  3323. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.state.pos + 1) === 123) {
  3324. if (this.state.pos === this.state.start && this.match(20)) {
  3325. if (ch === 36) {
  3326. this.state.pos += 2;
  3327. this.finishToken(23);
  3328. return;
  3329. } else {
  3330. ++this.state.pos;
  3331. this.finishToken(22);
  3332. return;
  3333. }
  3334. }
  3335. out += this.input.slice(chunkStart, this.state.pos);
  3336. this.finishToken(20, containsInvalid ? null : out);
  3337. return;
  3338. }
  3339. if (ch === 92) {
  3340. out += this.input.slice(chunkStart, this.state.pos);
  3341. const escaped = this.readEscapedChar(true);
  3342. if (escaped === null) {
  3343. containsInvalid = true;
  3344. } else {
  3345. out += escaped;
  3346. }
  3347. chunkStart = this.state.pos;
  3348. } else if (isNewLine(ch)) {
  3349. out += this.input.slice(chunkStart, this.state.pos);
  3350. ++this.state.pos;
  3351. switch (ch) {
  3352. case 13:
  3353. if (this.input.charCodeAt(this.state.pos) === 10) {
  3354. ++this.state.pos;
  3355. }
  3356. case 10:
  3357. out += "\n";
  3358. break;
  3359. default:
  3360. out += String.fromCharCode(ch);
  3361. break;
  3362. }
  3363. ++this.state.curLine;
  3364. this.state.lineStart = this.state.pos;
  3365. chunkStart = this.state.pos;
  3366. } else {
  3367. ++this.state.pos;
  3368. }
  3369. }
  3370. }
  3371. recordStrictModeErrors(pos, message) {
  3372. if (this.state.strict && !this.state.strictErrors.has(pos)) {
  3373. this.raise(pos, message);
  3374. } else {
  3375. this.state.strictErrors.set(pos, message);
  3376. }
  3377. }
  3378. readEscapedChar(inTemplate) {
  3379. const throwOnInvalid = !inTemplate;
  3380. const ch = this.input.charCodeAt(++this.state.pos);
  3381. ++this.state.pos;
  3382. switch (ch) {
  3383. case 110:
  3384. return "\n";
  3385. case 114:
  3386. return "\r";
  3387. case 120:
  3388. {
  3389. const code = this.readHexChar(2, false, throwOnInvalid);
  3390. return code === null ? null : String.fromCharCode(code);
  3391. }
  3392. case 117:
  3393. {
  3394. const code = this.readCodePoint(throwOnInvalid);
  3395. return code === null ? null : String.fromCodePoint(code);
  3396. }
  3397. case 116:
  3398. return "\t";
  3399. case 98:
  3400. return "\b";
  3401. case 118:
  3402. return "\u000b";
  3403. case 102:
  3404. return "\f";
  3405. case 13:
  3406. if (this.input.charCodeAt(this.state.pos) === 10) {
  3407. ++this.state.pos;
  3408. }
  3409. case 10:
  3410. this.state.lineStart = this.state.pos;
  3411. ++this.state.curLine;
  3412. case 8232:
  3413. case 8233:
  3414. return "";
  3415. case 56:
  3416. case 57:
  3417. if (inTemplate) {
  3418. return null;
  3419. } else {
  3420. this.recordStrictModeErrors(this.state.pos - 1, ErrorMessages.StrictNumericEscape);
  3421. }
  3422. default:
  3423. if (ch >= 48 && ch <= 55) {
  3424. const codePos = this.state.pos - 1;
  3425. const match = this.input.substr(this.state.pos - 1, 3).match(/^[0-7]+/);
  3426. let octalStr = match[0];
  3427. let octal = parseInt(octalStr, 8);
  3428. if (octal > 255) {
  3429. octalStr = octalStr.slice(0, -1);
  3430. octal = parseInt(octalStr, 8);
  3431. }
  3432. this.state.pos += octalStr.length - 1;
  3433. const next = this.input.charCodeAt(this.state.pos);
  3434. if (octalStr !== "0" || next === 56 || next === 57) {
  3435. if (inTemplate) {
  3436. return null;
  3437. } else {
  3438. this.recordStrictModeErrors(codePos, ErrorMessages.StrictNumericEscape);
  3439. }
  3440. }
  3441. return String.fromCharCode(octal);
  3442. }
  3443. return String.fromCharCode(ch);
  3444. }
  3445. }
  3446. readHexChar(len, forceLen, throwOnInvalid) {
  3447. const codePos = this.state.pos;
  3448. const n = this.readInt(16, len, forceLen, false);
  3449. if (n === null) {
  3450. if (throwOnInvalid) {
  3451. this.raise(codePos, ErrorMessages.InvalidEscapeSequence);
  3452. } else {
  3453. this.state.pos = codePos - 1;
  3454. }
  3455. }
  3456. return n;
  3457. }
  3458. readWord1(firstCode) {
  3459. this.state.containsEsc = false;
  3460. let word = "";
  3461. const start = this.state.pos;
  3462. let chunkStart = this.state.pos;
  3463. if (firstCode !== undefined) {
  3464. this.state.pos += firstCode <= 0xffff ? 1 : 2;
  3465. }
  3466. while (this.state.pos < this.length) {
  3467. const ch = this.codePointAtPos(this.state.pos);
  3468. if (isIdentifierChar(ch)) {
  3469. this.state.pos += ch <= 0xffff ? 1 : 2;
  3470. } else if (ch === 92) {
  3471. this.state.containsEsc = true;
  3472. word += this.input.slice(chunkStart, this.state.pos);
  3473. const escStart = this.state.pos;
  3474. const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar;
  3475. if (this.input.charCodeAt(++this.state.pos) !== 117) {
  3476. this.raise(this.state.pos, ErrorMessages.MissingUnicodeEscape);
  3477. chunkStart = this.state.pos - 1;
  3478. continue;
  3479. }
  3480. ++this.state.pos;
  3481. const esc = this.readCodePoint(true);
  3482. if (esc !== null) {
  3483. if (!identifierCheck(esc)) {
  3484. this.raise(escStart, ErrorMessages.EscapedCharNotAnIdentifier);
  3485. }
  3486. word += String.fromCodePoint(esc);
  3487. }
  3488. chunkStart = this.state.pos;
  3489. } else {
  3490. break;
  3491. }
  3492. }
  3493. return word + this.input.slice(chunkStart, this.state.pos);
  3494. }
  3495. readWord(firstCode) {
  3496. const word = this.readWord1(firstCode);
  3497. const type = keywords$1.get(word);
  3498. if (type !== undefined) {
  3499. this.finishToken(type, tokenLabelName(type));
  3500. } else {
  3501. this.finishToken(122, word);
  3502. }
  3503. }
  3504. checkKeywordEscapes() {
  3505. const {
  3506. type
  3507. } = this.state;
  3508. if (tokenIsKeyword(type) && this.state.containsEsc) {
  3509. this.raise(this.state.start, ErrorMessages.InvalidEscapedReservedWord, tokenLabelName(type));
  3510. }
  3511. }
  3512. updateContext(prevType) {
  3513. const {
  3514. context,
  3515. type
  3516. } = this.state;
  3517. switch (type) {
  3518. case 8:
  3519. context.pop();
  3520. break;
  3521. case 5:
  3522. case 7:
  3523. case 23:
  3524. context.push(types.brace);
  3525. break;
  3526. case 22:
  3527. if (context[context.length - 1] === types.template) {
  3528. context.pop();
  3529. } else {
  3530. context.push(types.template);
  3531. }
  3532. break;
  3533. }
  3534. }
  3535. }
  3536. class ClassScope {
  3537. constructor() {
  3538. this.privateNames = new Set();
  3539. this.loneAccessors = new Map();
  3540. this.undefinedPrivateNames = new Map();
  3541. }
  3542. }
  3543. class ClassScopeHandler {
  3544. constructor(raise) {
  3545. this.stack = [];
  3546. this.undefinedPrivateNames = new Map();
  3547. this.raise = raise;
  3548. }
  3549. current() {
  3550. return this.stack[this.stack.length - 1];
  3551. }
  3552. enter() {
  3553. this.stack.push(new ClassScope());
  3554. }
  3555. exit() {
  3556. const oldClassScope = this.stack.pop();
  3557. const current = this.current();
  3558. for (const [name, pos] of Array.from(oldClassScope.undefinedPrivateNames)) {
  3559. if (current) {
  3560. if (!current.undefinedPrivateNames.has(name)) {
  3561. current.undefinedPrivateNames.set(name, pos);
  3562. }
  3563. } else {
  3564. this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name);
  3565. }
  3566. }
  3567. }
  3568. declarePrivateName(name, elementType, pos) {
  3569. const classScope = this.current();
  3570. let redefined = classScope.privateNames.has(name);
  3571. if (elementType & CLASS_ELEMENT_KIND_ACCESSOR) {
  3572. const accessor = redefined && classScope.loneAccessors.get(name);
  3573. if (accessor) {
  3574. const oldStatic = accessor & CLASS_ELEMENT_FLAG_STATIC;
  3575. const newStatic = elementType & CLASS_ELEMENT_FLAG_STATIC;
  3576. const oldKind = accessor & CLASS_ELEMENT_KIND_ACCESSOR;
  3577. const newKind = elementType & CLASS_ELEMENT_KIND_ACCESSOR;
  3578. redefined = oldKind === newKind || oldStatic !== newStatic;
  3579. if (!redefined) classScope.loneAccessors.delete(name);
  3580. } else if (!redefined) {
  3581. classScope.loneAccessors.set(name, elementType);
  3582. }
  3583. }
  3584. if (redefined) {
  3585. this.raise(pos, ErrorMessages.PrivateNameRedeclaration, name);
  3586. }
  3587. classScope.privateNames.add(name);
  3588. classScope.undefinedPrivateNames.delete(name);
  3589. }
  3590. usePrivateName(name, pos) {
  3591. let classScope;
  3592. for (classScope of this.stack) {
  3593. if (classScope.privateNames.has(name)) return;
  3594. }
  3595. if (classScope) {
  3596. classScope.undefinedPrivateNames.set(name, pos);
  3597. } else {
  3598. this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name);
  3599. }
  3600. }
  3601. }
  3602. const kExpression = 0,
  3603. kMaybeArrowParameterDeclaration = 1,
  3604. kMaybeAsyncArrowParameterDeclaration = 2,
  3605. kParameterDeclaration = 3;
  3606. class ExpressionScope {
  3607. constructor(type = kExpression) {
  3608. this.type = void 0;
  3609. this.type = type;
  3610. }
  3611. canBeArrowParameterDeclaration() {
  3612. return this.type === kMaybeAsyncArrowParameterDeclaration || this.type === kMaybeArrowParameterDeclaration;
  3613. }
  3614. isCertainlyParameterDeclaration() {
  3615. return this.type === kParameterDeclaration;
  3616. }
  3617. }
  3618. class ArrowHeadParsingScope extends ExpressionScope {
  3619. constructor(type) {
  3620. super(type);
  3621. this.errors = new Map();
  3622. }
  3623. recordDeclarationError(pos, template) {
  3624. this.errors.set(pos, template);
  3625. }
  3626. clearDeclarationError(pos) {
  3627. this.errors.delete(pos);
  3628. }
  3629. iterateErrors(iterator) {
  3630. this.errors.forEach(iterator);
  3631. }
  3632. }
  3633. class ExpressionScopeHandler {
  3634. constructor(raise) {
  3635. this.stack = [new ExpressionScope()];
  3636. this.raise = raise;
  3637. }
  3638. enter(scope) {
  3639. this.stack.push(scope);
  3640. }
  3641. exit() {
  3642. this.stack.pop();
  3643. }
  3644. recordParameterInitializerError(pos, template) {
  3645. const {
  3646. stack
  3647. } = this;
  3648. let i = stack.length - 1;
  3649. let scope = stack[i];
  3650. while (!scope.isCertainlyParameterDeclaration()) {
  3651. if (scope.canBeArrowParameterDeclaration()) {
  3652. scope.recordDeclarationError(pos, template);
  3653. } else {
  3654. return;
  3655. }
  3656. scope = stack[--i];
  3657. }
  3658. this.raise(pos, template);
  3659. }
  3660. recordParenthesizedIdentifierError(pos, template) {
  3661. const {
  3662. stack
  3663. } = this;
  3664. const scope = stack[stack.length - 1];
  3665. if (scope.isCertainlyParameterDeclaration()) {
  3666. this.raise(pos, template);
  3667. } else if (scope.canBeArrowParameterDeclaration()) {
  3668. scope.recordDeclarationError(pos, template);
  3669. } else {
  3670. return;
  3671. }
  3672. }
  3673. recordAsyncArrowParametersError(pos, template) {
  3674. const {
  3675. stack
  3676. } = this;
  3677. let i = stack.length - 1;
  3678. let scope = stack[i];
  3679. while (scope.canBeArrowParameterDeclaration()) {
  3680. if (scope.type === kMaybeAsyncArrowParameterDeclaration) {
  3681. scope.recordDeclarationError(pos, template);
  3682. }
  3683. scope = stack[--i];
  3684. }
  3685. }
  3686. validateAsPattern() {
  3687. const {
  3688. stack
  3689. } = this;
  3690. const currentScope = stack[stack.length - 1];
  3691. if (!currentScope.canBeArrowParameterDeclaration()) return;
  3692. currentScope.iterateErrors((template, pos) => {
  3693. this.raise(pos, template);
  3694. let i = stack.length - 2;
  3695. let scope = stack[i];
  3696. while (scope.canBeArrowParameterDeclaration()) {
  3697. scope.clearDeclarationError(pos);
  3698. scope = stack[--i];
  3699. }
  3700. });
  3701. }
  3702. }
  3703. function newParameterDeclarationScope() {
  3704. return new ExpressionScope(kParameterDeclaration);
  3705. }
  3706. function newArrowHeadScope() {
  3707. return new ArrowHeadParsingScope(kMaybeArrowParameterDeclaration);
  3708. }
  3709. function newAsyncArrowScope() {
  3710. return new ArrowHeadParsingScope(kMaybeAsyncArrowParameterDeclaration);
  3711. }
  3712. function newExpressionScope() {
  3713. return new ExpressionScope();
  3714. }
  3715. const PARAM = 0b0000,
  3716. PARAM_YIELD = 0b0001,
  3717. PARAM_AWAIT = 0b0010,
  3718. PARAM_RETURN = 0b0100,
  3719. PARAM_IN = 0b1000;
  3720. class ProductionParameterHandler {
  3721. constructor() {
  3722. this.stacks = [];
  3723. }
  3724. enter(flags) {
  3725. this.stacks.push(flags);
  3726. }
  3727. exit() {
  3728. this.stacks.pop();
  3729. }
  3730. currentFlags() {
  3731. return this.stacks[this.stacks.length - 1];
  3732. }
  3733. get hasAwait() {
  3734. return (this.currentFlags() & PARAM_AWAIT) > 0;
  3735. }
  3736. get hasYield() {
  3737. return (this.currentFlags() & PARAM_YIELD) > 0;
  3738. }
  3739. get hasReturn() {
  3740. return (this.currentFlags() & PARAM_RETURN) > 0;
  3741. }
  3742. get hasIn() {
  3743. return (this.currentFlags() & PARAM_IN) > 0;
  3744. }
  3745. }
  3746. function functionFlags(isAsync, isGenerator) {
  3747. return (isAsync ? PARAM_AWAIT : 0) | (isGenerator ? PARAM_YIELD : 0);
  3748. }
  3749. class UtilParser extends Tokenizer {
  3750. addExtra(node, key, val) {
  3751. if (!node) return;
  3752. const extra = node.extra = node.extra || {};
  3753. extra[key] = val;
  3754. }
  3755. isContextual(token) {
  3756. return this.state.type === token && !this.state.containsEsc;
  3757. }
  3758. isUnparsedContextual(nameStart, name) {
  3759. const nameEnd = nameStart + name.length;
  3760. if (this.input.slice(nameStart, nameEnd) === name) {
  3761. const nextCh = this.input.charCodeAt(nameEnd);
  3762. return !(isIdentifierChar(nextCh) || (nextCh & 0xfc00) === 0xd800);
  3763. }
  3764. return false;
  3765. }
  3766. isLookaheadContextual(name) {
  3767. const next = this.nextTokenStart();
  3768. return this.isUnparsedContextual(next, name);
  3769. }
  3770. eatContextual(token) {
  3771. if (this.isContextual(token)) {
  3772. this.next();
  3773. return true;
  3774. }
  3775. return false;
  3776. }
  3777. expectContextual(token, template) {
  3778. if (!this.eatContextual(token)) this.unexpected(null, template);
  3779. }
  3780. canInsertSemicolon() {
  3781. return this.match(129) || this.match(8) || this.hasPrecedingLineBreak();
  3782. }
  3783. hasPrecedingLineBreak() {
  3784. return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
  3785. }
  3786. hasFollowingLineBreak() {
  3787. skipWhiteSpaceToLineBreak.lastIndex = this.state.end;
  3788. return skipWhiteSpaceToLineBreak.test(this.input);
  3789. }
  3790. isLineTerminator() {
  3791. return this.eat(13) || this.canInsertSemicolon();
  3792. }
  3793. semicolon(allowAsi = true) {
  3794. if (allowAsi ? this.isLineTerminator() : this.eat(13)) return;
  3795. this.raise(this.state.lastTokEnd, ErrorMessages.MissingSemicolon);
  3796. }
  3797. expect(type, pos) {
  3798. this.eat(type) || this.unexpected(pos, type);
  3799. }
  3800. assertNoSpace(message = "Unexpected space.") {
  3801. if (this.state.start > this.state.lastTokEnd) {
  3802. this.raise(this.state.lastTokEnd, {
  3803. code: ErrorCodes.SyntaxError,
  3804. reasonCode: "UnexpectedSpace",
  3805. template: message
  3806. });
  3807. }
  3808. }
  3809. unexpected(pos, messageOrType = {
  3810. code: ErrorCodes.SyntaxError,
  3811. reasonCode: "UnexpectedToken",
  3812. template: "Unexpected token"
  3813. }) {
  3814. if (isTokenType(messageOrType)) {
  3815. messageOrType = {
  3816. code: ErrorCodes.SyntaxError,
  3817. reasonCode: "UnexpectedToken",
  3818. template: `Unexpected token, expected "${tokenLabelName(messageOrType)}"`
  3819. };
  3820. }
  3821. throw this.raise(pos != null ? pos : this.state.start, messageOrType);
  3822. }
  3823. expectPlugin(name, pos) {
  3824. if (!this.hasPlugin(name)) {
  3825. throw this.raiseWithData(pos != null ? pos : this.state.start, {
  3826. missingPlugin: [name]
  3827. }, `This experimental syntax requires enabling the parser plugin: '${name}'`);
  3828. }
  3829. return true;
  3830. }
  3831. expectOnePlugin(names, pos) {
  3832. if (!names.some(n => this.hasPlugin(n))) {
  3833. throw this.raiseWithData(pos != null ? pos : this.state.start, {
  3834. missingPlugin: names
  3835. }, `This experimental syntax requires enabling one of the following parser plugin(s): '${names.join(", ")}'`);
  3836. }
  3837. }
  3838. tryParse(fn, oldState = this.state.clone()) {
  3839. const abortSignal = {
  3840. node: null
  3841. };
  3842. try {
  3843. const node = fn((node = null) => {
  3844. abortSignal.node = node;
  3845. throw abortSignal;
  3846. });
  3847. if (this.state.errors.length > oldState.errors.length) {
  3848. const failState = this.state;
  3849. this.state = oldState;
  3850. this.state.tokensLength = failState.tokensLength;
  3851. return {
  3852. node,
  3853. error: failState.errors[oldState.errors.length],
  3854. thrown: false,
  3855. aborted: false,
  3856. failState
  3857. };
  3858. }
  3859. return {
  3860. node,
  3861. error: null,
  3862. thrown: false,
  3863. aborted: false,
  3864. failState: null
  3865. };
  3866. } catch (error) {
  3867. const failState = this.state;
  3868. this.state = oldState;
  3869. if (error instanceof SyntaxError) {
  3870. return {
  3871. node: null,
  3872. error,
  3873. thrown: true,
  3874. aborted: false,
  3875. failState
  3876. };
  3877. }
  3878. if (error === abortSignal) {
  3879. return {
  3880. node: abortSignal.node,
  3881. error: null,
  3882. thrown: false,
  3883. aborted: true,
  3884. failState
  3885. };
  3886. }
  3887. throw error;
  3888. }
  3889. }
  3890. checkExpressionErrors(refExpressionErrors, andThrow) {
  3891. if (!refExpressionErrors) return false;
  3892. const {
  3893. shorthandAssign,
  3894. doubleProto,
  3895. optionalParameters
  3896. } = refExpressionErrors;
  3897. const hasErrors = shorthandAssign + doubleProto + optionalParameters > -3;
  3898. if (!andThrow) {
  3899. return hasErrors;
  3900. } else if (hasErrors) {
  3901. if (shorthandAssign >= 0) {
  3902. this.unexpected(shorthandAssign);
  3903. }
  3904. if (doubleProto >= 0) {
  3905. this.raise(doubleProto, ErrorMessages.DuplicateProto);
  3906. }
  3907. if (optionalParameters >= 0) {
  3908. this.unexpected(optionalParameters);
  3909. }
  3910. }
  3911. }
  3912. isLiteralPropertyName() {
  3913. return tokenIsLiteralPropertyName(this.state.type);
  3914. }
  3915. isPrivateName(node) {
  3916. return node.type === "PrivateName";
  3917. }
  3918. getPrivateNameSV(node) {
  3919. return node.id.name;
  3920. }
  3921. hasPropertyAsPrivateName(node) {
  3922. return (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") && this.isPrivateName(node.property);
  3923. }
  3924. isOptionalChain(node) {
  3925. return node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression";
  3926. }
  3927. isObjectProperty(node) {
  3928. return node.type === "ObjectProperty";
  3929. }
  3930. isObjectMethod(node) {
  3931. return node.type === "ObjectMethod";
  3932. }
  3933. initializeScopes(inModule = this.options.sourceType === "module") {
  3934. const oldLabels = this.state.labels;
  3935. this.state.labels = [];
  3936. const oldExportedIdentifiers = this.exportedIdentifiers;
  3937. this.exportedIdentifiers = new Set();
  3938. const oldInModule = this.inModule;
  3939. this.inModule = inModule;
  3940. const oldScope = this.scope;
  3941. const ScopeHandler = this.getScopeHandler();
  3942. this.scope = new ScopeHandler(this.raise.bind(this), this.inModule);
  3943. const oldProdParam = this.prodParam;
  3944. this.prodParam = new ProductionParameterHandler();
  3945. const oldClassScope = this.classScope;
  3946. this.classScope = new ClassScopeHandler(this.raise.bind(this));
  3947. const oldExpressionScope = this.expressionScope;
  3948. this.expressionScope = new ExpressionScopeHandler(this.raise.bind(this));
  3949. return () => {
  3950. this.state.labels = oldLabels;
  3951. this.exportedIdentifiers = oldExportedIdentifiers;
  3952. this.inModule = oldInModule;
  3953. this.scope = oldScope;
  3954. this.prodParam = oldProdParam;
  3955. this.classScope = oldClassScope;
  3956. this.expressionScope = oldExpressionScope;
  3957. };
  3958. }
  3959. enterInitialScopes() {
  3960. let paramFlags = PARAM;
  3961. if (this.inModule) {
  3962. paramFlags |= PARAM_AWAIT;
  3963. }
  3964. this.scope.enter(SCOPE_PROGRAM);
  3965. this.prodParam.enter(paramFlags);
  3966. }
  3967. }
  3968. class ExpressionErrors {
  3969. constructor() {
  3970. this.shorthandAssign = -1;
  3971. this.doubleProto = -1;
  3972. this.optionalParameters = -1;
  3973. }
  3974. }
  3975. class Node {
  3976. constructor(parser, pos, loc) {
  3977. this.type = "";
  3978. this.start = pos;
  3979. this.end = 0;
  3980. this.loc = new SourceLocation(loc);
  3981. if (parser != null && parser.options.ranges) this.range = [pos, 0];
  3982. if (parser != null && parser.filename) this.loc.filename = parser.filename;
  3983. }
  3984. }
  3985. const NodePrototype = Node.prototype;
  3986. {
  3987. NodePrototype.__clone = function () {
  3988. const newNode = new Node();
  3989. const keys = Object.keys(this);
  3990. for (let i = 0, length = keys.length; i < length; i++) {
  3991. const key = keys[i];
  3992. if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") {
  3993. newNode[key] = this[key];
  3994. }
  3995. }
  3996. return newNode;
  3997. };
  3998. }
  3999. function clonePlaceholder(node) {
  4000. return cloneIdentifier(node);
  4001. }
  4002. function cloneIdentifier(node) {
  4003. const {
  4004. type,
  4005. start,
  4006. end,
  4007. loc,
  4008. range,
  4009. extra,
  4010. name
  4011. } = node;
  4012. const cloned = Object.create(NodePrototype);
  4013. cloned.type = type;
  4014. cloned.start = start;
  4015. cloned.end = end;
  4016. cloned.loc = loc;
  4017. cloned.range = range;
  4018. cloned.extra = extra;
  4019. cloned.name = name;
  4020. if (type === "Placeholder") {
  4021. cloned.expectedNode = node.expectedNode;
  4022. }
  4023. return cloned;
  4024. }
  4025. function cloneStringLiteral(node) {
  4026. const {
  4027. type,
  4028. start,
  4029. end,
  4030. loc,
  4031. range,
  4032. extra
  4033. } = node;
  4034. if (type === "Placeholder") {
  4035. return clonePlaceholder(node);
  4036. }
  4037. const cloned = Object.create(NodePrototype);
  4038. cloned.type = "StringLiteral";
  4039. cloned.start = start;
  4040. cloned.end = end;
  4041. cloned.loc = loc;
  4042. cloned.range = range;
  4043. cloned.extra = extra;
  4044. cloned.value = node.value;
  4045. return cloned;
  4046. }
  4047. class NodeUtils extends UtilParser {
  4048. startNode() {
  4049. return new Node(this, this.state.start, this.state.startLoc);
  4050. }
  4051. startNodeAt(pos, loc) {
  4052. return new Node(this, pos, loc);
  4053. }
  4054. startNodeAtNode(type) {
  4055. return this.startNodeAt(type.start, type.loc.start);
  4056. }
  4057. finishNode(node, type) {
  4058. return this.finishNodeAt(node, type, this.state.lastTokEnd, this.state.lastTokEndLoc);
  4059. }
  4060. finishNodeAt(node, type, pos, loc) {
  4061. node.type = type;
  4062. node.end = pos;
  4063. node.loc.end = loc;
  4064. if (this.options.ranges) node.range[1] = pos;
  4065. if (this.options.attachComment) this.processComment(node);
  4066. return node;
  4067. }
  4068. resetStartLocation(node, start, startLoc) {
  4069. node.start = start;
  4070. node.loc.start = startLoc;
  4071. if (this.options.ranges) node.range[0] = start;
  4072. }
  4073. resetEndLocation(node, end = this.state.lastTokEnd, endLoc = this.state.lastTokEndLoc) {
  4074. node.end = end;
  4075. node.loc.end = endLoc;
  4076. if (this.options.ranges) node.range[1] = end;
  4077. }
  4078. resetStartLocationFromNode(node, locationNode) {
  4079. this.resetStartLocation(node, locationNode.start, locationNode.loc.start);
  4080. }
  4081. }
  4082. const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]);
  4083. const FlowErrors = makeErrorTemplates({
  4084. AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",
  4085. 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.",
  4086. AssignReservedType: "Cannot overwrite reserved type %0.",
  4087. DeclareClassElement: "The `declare` modifier can only appear on class fields.",
  4088. DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.",
  4089. DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement.",
  4090. EnumBooleanMemberNotInitialized: "Boolean enum members need to be initialized. Use either `%0 = true,` or `%0 = false,` in enum `%1`.",
  4091. EnumDuplicateMemberName: "Enum member names need to be unique, but the name `%0` has already been used before in enum `%1`.",
  4092. EnumInconsistentMemberValues: "Enum `%0` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.",
  4093. EnumInvalidExplicitType: "Enum type `%1` is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  4094. EnumInvalidExplicitTypeUnknownSupplied: "Supplied enum type is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  4095. EnumInvalidMemberInitializerPrimaryType: "Enum `%0` has type `%2`, so the initializer of `%1` needs to be a %2 literal.",
  4096. EnumInvalidMemberInitializerSymbolType: "Symbol enum members cannot be initialized. Use `%1,` in enum `%0`.",
  4097. EnumInvalidMemberInitializerUnknownType: "The enum member initializer for `%1` needs to be a literal (either a boolean, number, or string) in enum `%0`.",
  4098. EnumInvalidMemberName: "Enum member names cannot start with lowercase 'a' through 'z'. Instead of using `%0`, consider using `%1`, in enum `%2`.",
  4099. EnumNumberMemberNotInitialized: "Number enum members need to be initialized, e.g. `%1 = 1` in enum `%0`.",
  4100. EnumStringMemberInconsistentlyInitailized: "String enum members need to consistently either all use initializers, or use no initializers, in enum `%0`.",
  4101. GetterMayNotHaveThisParam: "A getter cannot have a `this` parameter.",
  4102. 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.",
  4103. InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type.",
  4104. InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions.",
  4105. InexactVariance: "Explicit inexact syntax cannot have variance.",
  4106. InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`.",
  4107. MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",
  4108. NestedDeclareModule: "`declare module` cannot be used inside another `declare module`.",
  4109. NestedFlowComment: "Cannot have a flow comment inside another flow comment.",
  4110. PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.",
  4111. SetterMayNotHaveThisParam: "A setter cannot have a `this` parameter.",
  4112. SpreadVariance: "Spread properties cannot have variance.",
  4113. ThisParamAnnotationRequired: "A type annotation is required for the `this` parameter.",
  4114. ThisParamBannedInConstructor: "Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.",
  4115. ThisParamMayNotBeOptional: "The `this` parameter cannot be optional.",
  4116. ThisParamMustBeFirst: "The `this` parameter must be the first function parameter.",
  4117. ThisParamNoDefault: "The `this` parameter may not have a default value.",
  4118. TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",
  4119. TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis.",
  4120. UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object.",
  4121. UnexpectedReservedType: "Unexpected reserved type %0.",
  4122. UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new.",
  4123. UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.",
  4124. UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions.",
  4125. UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint".',
  4126. UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration.",
  4127. UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`.",
  4128. UnsupportedDeclareExportKind: "`declare export %0` is not supported. Use `%1` instead.",
  4129. UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module.",
  4130. UnterminatedFlowComment: "Unterminated flow-comment."
  4131. }, ErrorCodes.SyntaxError, "flow");
  4132. function isEsModuleType(bodyElement) {
  4133. return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration");
  4134. }
  4135. function hasTypeImportKind(node) {
  4136. return node.importKind === "type" || node.importKind === "typeof";
  4137. }
  4138. function isMaybeDefaultImport(type) {
  4139. return tokenIsKeywordOrIdentifier(type) && type !== 91;
  4140. }
  4141. const exportSuggestions = {
  4142. const: "declare export var",
  4143. let: "declare export var",
  4144. type: "export type",
  4145. interface: "export interface"
  4146. };
  4147. function partition(list, test) {
  4148. const list1 = [];
  4149. const list2 = [];
  4150. for (let i = 0; i < list.length; i++) {
  4151. (test(list[i], i, list) ? list1 : list2).push(list[i]);
  4152. }
  4153. return [list1, list2];
  4154. }
  4155. const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
  4156. var flow = (superClass => class extends superClass {
  4157. constructor(...args) {
  4158. super(...args);
  4159. this.flowPragma = undefined;
  4160. }
  4161. getScopeHandler() {
  4162. return FlowScopeHandler;
  4163. }
  4164. shouldParseTypes() {
  4165. return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
  4166. }
  4167. shouldParseEnums() {
  4168. return !!this.getPluginOption("flow", "enums");
  4169. }
  4170. finishToken(type, val) {
  4171. if (type !== 123 && type !== 13 && type !== 26) {
  4172. if (this.flowPragma === undefined) {
  4173. this.flowPragma = null;
  4174. }
  4175. }
  4176. return super.finishToken(type, val);
  4177. }
  4178. addComment(comment) {
  4179. if (this.flowPragma === undefined) {
  4180. const matches = FLOW_PRAGMA_REGEX.exec(comment.value);
  4181. if (!matches) ; else if (matches[1] === "flow") {
  4182. this.flowPragma = "flow";
  4183. } else if (matches[1] === "noflow") {
  4184. this.flowPragma = "noflow";
  4185. } else {
  4186. throw new Error("Unexpected flow pragma");
  4187. }
  4188. }
  4189. return super.addComment(comment);
  4190. }
  4191. flowParseTypeInitialiser(tok) {
  4192. const oldInType = this.state.inType;
  4193. this.state.inType = true;
  4194. this.expect(tok || 14);
  4195. const type = this.flowParseType();
  4196. this.state.inType = oldInType;
  4197. return type;
  4198. }
  4199. flowParsePredicate() {
  4200. const node = this.startNode();
  4201. const moduloPos = this.state.start;
  4202. this.next();
  4203. this.expectContextual(101);
  4204. if (this.state.lastTokStart > moduloPos + 1) {
  4205. this.raise(moduloPos, FlowErrors.UnexpectedSpaceBetweenModuloChecks);
  4206. }
  4207. if (this.eat(10)) {
  4208. node.value = this.parseExpression();
  4209. this.expect(11);
  4210. return this.finishNode(node, "DeclaredPredicate");
  4211. } else {
  4212. return this.finishNode(node, "InferredPredicate");
  4213. }
  4214. }
  4215. flowParseTypeAndPredicateInitialiser() {
  4216. const oldInType = this.state.inType;
  4217. this.state.inType = true;
  4218. this.expect(14);
  4219. let type = null;
  4220. let predicate = null;
  4221. if (this.match(48)) {
  4222. this.state.inType = oldInType;
  4223. predicate = this.flowParsePredicate();
  4224. } else {
  4225. type = this.flowParseType();
  4226. this.state.inType = oldInType;
  4227. if (this.match(48)) {
  4228. predicate = this.flowParsePredicate();
  4229. }
  4230. }
  4231. return [type, predicate];
  4232. }
  4233. flowParseDeclareClass(node) {
  4234. this.next();
  4235. this.flowParseInterfaceish(node, true);
  4236. return this.finishNode(node, "DeclareClass");
  4237. }
  4238. flowParseDeclareFunction(node) {
  4239. this.next();
  4240. const id = node.id = this.parseIdentifier();
  4241. const typeNode = this.startNode();
  4242. const typeContainer = this.startNode();
  4243. if (this.match(43)) {
  4244. typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
  4245. } else {
  4246. typeNode.typeParameters = null;
  4247. }
  4248. this.expect(10);
  4249. const tmp = this.flowParseFunctionTypeParams();
  4250. typeNode.params = tmp.params;
  4251. typeNode.rest = tmp.rest;
  4252. typeNode.this = tmp._this;
  4253. this.expect(11);
  4254. [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  4255. typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
  4256. id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
  4257. this.resetEndLocation(id);
  4258. this.semicolon();
  4259. this.scope.declareName(node.id.name, BIND_FLOW_DECLARE_FN, node.id.start);
  4260. return this.finishNode(node, "DeclareFunction");
  4261. }
  4262. flowParseDeclare(node, insideModule) {
  4263. if (this.match(74)) {
  4264. return this.flowParseDeclareClass(node);
  4265. } else if (this.match(62)) {
  4266. return this.flowParseDeclareFunction(node);
  4267. } else if (this.match(68)) {
  4268. return this.flowParseDeclareVariable(node);
  4269. } else if (this.eatContextual(117)) {
  4270. if (this.match(16)) {
  4271. return this.flowParseDeclareModuleExports(node);
  4272. } else {
  4273. if (insideModule) {
  4274. this.raise(this.state.lastTokStart, FlowErrors.NestedDeclareModule);
  4275. }
  4276. return this.flowParseDeclareModule(node);
  4277. }
  4278. } else if (this.isContextual(120)) {
  4279. return this.flowParseDeclareTypeAlias(node);
  4280. } else if (this.isContextual(121)) {
  4281. return this.flowParseDeclareOpaqueType(node);
  4282. } else if (this.isContextual(119)) {
  4283. return this.flowParseDeclareInterface(node);
  4284. } else if (this.match(76)) {
  4285. return this.flowParseDeclareExportDeclaration(node, insideModule);
  4286. } else {
  4287. throw this.unexpected();
  4288. }
  4289. }
  4290. flowParseDeclareVariable(node) {
  4291. this.next();
  4292. node.id = this.flowParseTypeAnnotatableIdentifier(true);
  4293. this.scope.declareName(node.id.name, BIND_VAR, node.id.start);
  4294. this.semicolon();
  4295. return this.finishNode(node, "DeclareVariable");
  4296. }
  4297. flowParseDeclareModule(node) {
  4298. this.scope.enter(SCOPE_OTHER);
  4299. if (this.match(123)) {
  4300. node.id = this.parseExprAtom();
  4301. } else {
  4302. node.id = this.parseIdentifier();
  4303. }
  4304. const bodyNode = node.body = this.startNode();
  4305. const body = bodyNode.body = [];
  4306. this.expect(5);
  4307. while (!this.match(8)) {
  4308. let bodyNode = this.startNode();
  4309. if (this.match(77)) {
  4310. this.next();
  4311. if (!this.isContextual(120) && !this.match(81)) {
  4312. this.raise(this.state.lastTokStart, FlowErrors.InvalidNonTypeImportInDeclareModule);
  4313. }
  4314. this.parseImport(bodyNode);
  4315. } else {
  4316. this.expectContextual(115, FlowErrors.UnsupportedStatementInDeclareModule);
  4317. bodyNode = this.flowParseDeclare(bodyNode, true);
  4318. }
  4319. body.push(bodyNode);
  4320. }
  4321. this.scope.exit();
  4322. this.expect(8);
  4323. this.finishNode(bodyNode, "BlockStatement");
  4324. let kind = null;
  4325. let hasModuleExport = false;
  4326. body.forEach(bodyElement => {
  4327. if (isEsModuleType(bodyElement)) {
  4328. if (kind === "CommonJS") {
  4329. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  4330. }
  4331. kind = "ES";
  4332. } else if (bodyElement.type === "DeclareModuleExports") {
  4333. if (hasModuleExport) {
  4334. this.raise(bodyElement.start, FlowErrors.DuplicateDeclareModuleExports);
  4335. }
  4336. if (kind === "ES") {
  4337. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  4338. }
  4339. kind = "CommonJS";
  4340. hasModuleExport = true;
  4341. }
  4342. });
  4343. node.kind = kind || "CommonJS";
  4344. return this.finishNode(node, "DeclareModule");
  4345. }
  4346. flowParseDeclareExportDeclaration(node, insideModule) {
  4347. this.expect(76);
  4348. if (this.eat(59)) {
  4349. if (this.match(62) || this.match(74)) {
  4350. node.declaration = this.flowParseDeclare(this.startNode());
  4351. } else {
  4352. node.declaration = this.flowParseType();
  4353. this.semicolon();
  4354. }
  4355. node.default = true;
  4356. return this.finishNode(node, "DeclareExportDeclaration");
  4357. } else {
  4358. if (this.match(69) || this.isLet() || (this.isContextual(120) || this.isContextual(119)) && !insideModule) {
  4359. const label = this.state.value;
  4360. const suggestion = exportSuggestions[label];
  4361. throw this.raise(this.state.start, FlowErrors.UnsupportedDeclareExportKind, label, suggestion);
  4362. }
  4363. if (this.match(68) || this.match(62) || this.match(74) || this.isContextual(121)) {
  4364. node.declaration = this.flowParseDeclare(this.startNode());
  4365. node.default = false;
  4366. return this.finishNode(node, "DeclareExportDeclaration");
  4367. } else if (this.match(49) || this.match(5) || this.isContextual(119) || this.isContextual(120) || this.isContextual(121)) {
  4368. node = this.parseExport(node);
  4369. if (node.type === "ExportNamedDeclaration") {
  4370. node.type = "ExportDeclaration";
  4371. node.default = false;
  4372. delete node.exportKind;
  4373. }
  4374. node.type = "Declare" + node.type;
  4375. return node;
  4376. }
  4377. }
  4378. throw this.unexpected();
  4379. }
  4380. flowParseDeclareModuleExports(node) {
  4381. this.next();
  4382. this.expectContextual(102);
  4383. node.typeAnnotation = this.flowParseTypeAnnotation();
  4384. this.semicolon();
  4385. return this.finishNode(node, "DeclareModuleExports");
  4386. }
  4387. flowParseDeclareTypeAlias(node) {
  4388. this.next();
  4389. this.flowParseTypeAlias(node);
  4390. node.type = "DeclareTypeAlias";
  4391. return node;
  4392. }
  4393. flowParseDeclareOpaqueType(node) {
  4394. this.next();
  4395. this.flowParseOpaqueType(node, true);
  4396. node.type = "DeclareOpaqueType";
  4397. return node;
  4398. }
  4399. flowParseDeclareInterface(node) {
  4400. this.next();
  4401. this.flowParseInterfaceish(node);
  4402. return this.finishNode(node, "DeclareInterface");
  4403. }
  4404. flowParseInterfaceish(node, isClass = false) {
  4405. node.id = this.flowParseRestrictedIdentifier(!isClass, true);
  4406. this.scope.declareName(node.id.name, isClass ? BIND_FUNCTION : BIND_LEXICAL, node.id.start);
  4407. if (this.match(43)) {
  4408. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4409. } else {
  4410. node.typeParameters = null;
  4411. }
  4412. node.extends = [];
  4413. node.implements = [];
  4414. node.mixins = [];
  4415. if (this.eat(75)) {
  4416. do {
  4417. node.extends.push(this.flowParseInterfaceExtends());
  4418. } while (!isClass && this.eat(12));
  4419. }
  4420. if (this.isContextual(108)) {
  4421. this.next();
  4422. do {
  4423. node.mixins.push(this.flowParseInterfaceExtends());
  4424. } while (this.eat(12));
  4425. }
  4426. if (this.isContextual(104)) {
  4427. this.next();
  4428. do {
  4429. node.implements.push(this.flowParseInterfaceExtends());
  4430. } while (this.eat(12));
  4431. }
  4432. node.body = this.flowParseObjectType({
  4433. allowStatic: isClass,
  4434. allowExact: false,
  4435. allowSpread: false,
  4436. allowProto: isClass,
  4437. allowInexact: false
  4438. });
  4439. }
  4440. flowParseInterfaceExtends() {
  4441. const node = this.startNode();
  4442. node.id = this.flowParseQualifiedTypeIdentifier();
  4443. if (this.match(43)) {
  4444. node.typeParameters = this.flowParseTypeParameterInstantiation();
  4445. } else {
  4446. node.typeParameters = null;
  4447. }
  4448. return this.finishNode(node, "InterfaceExtends");
  4449. }
  4450. flowParseInterface(node) {
  4451. this.flowParseInterfaceish(node);
  4452. return this.finishNode(node, "InterfaceDeclaration");
  4453. }
  4454. checkNotUnderscore(word) {
  4455. if (word === "_") {
  4456. this.raise(this.state.start, FlowErrors.UnexpectedReservedUnderscore);
  4457. }
  4458. }
  4459. checkReservedType(word, startLoc, declaration) {
  4460. if (!reservedTypes.has(word)) return;
  4461. this.raise(startLoc, declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, word);
  4462. }
  4463. flowParseRestrictedIdentifier(liberal, declaration) {
  4464. this.checkReservedType(this.state.value, this.state.start, declaration);
  4465. return this.parseIdentifier(liberal);
  4466. }
  4467. flowParseTypeAlias(node) {
  4468. node.id = this.flowParseRestrictedIdentifier(false, true);
  4469. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  4470. if (this.match(43)) {
  4471. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4472. } else {
  4473. node.typeParameters = null;
  4474. }
  4475. node.right = this.flowParseTypeInitialiser(27);
  4476. this.semicolon();
  4477. return this.finishNode(node, "TypeAlias");
  4478. }
  4479. flowParseOpaqueType(node, declare) {
  4480. this.expectContextual(120);
  4481. node.id = this.flowParseRestrictedIdentifier(true, true);
  4482. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  4483. if (this.match(43)) {
  4484. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4485. } else {
  4486. node.typeParameters = null;
  4487. }
  4488. node.supertype = null;
  4489. if (this.match(14)) {
  4490. node.supertype = this.flowParseTypeInitialiser(14);
  4491. }
  4492. node.impltype = null;
  4493. if (!declare) {
  4494. node.impltype = this.flowParseTypeInitialiser(27);
  4495. }
  4496. this.semicolon();
  4497. return this.finishNode(node, "OpaqueType");
  4498. }
  4499. flowParseTypeParameter(requireDefault = false) {
  4500. const nodeStart = this.state.start;
  4501. const node = this.startNode();
  4502. const variance = this.flowParseVariance();
  4503. const ident = this.flowParseTypeAnnotatableIdentifier();
  4504. node.name = ident.name;
  4505. node.variance = variance;
  4506. node.bound = ident.typeAnnotation;
  4507. if (this.match(27)) {
  4508. this.eat(27);
  4509. node.default = this.flowParseType();
  4510. } else {
  4511. if (requireDefault) {
  4512. this.raise(nodeStart, FlowErrors.MissingTypeParamDefault);
  4513. }
  4514. }
  4515. return this.finishNode(node, "TypeParameter");
  4516. }
  4517. flowParseTypeParameterDeclaration() {
  4518. const oldInType = this.state.inType;
  4519. const node = this.startNode();
  4520. node.params = [];
  4521. this.state.inType = true;
  4522. if (this.match(43) || this.match(132)) {
  4523. this.next();
  4524. } else {
  4525. this.unexpected();
  4526. }
  4527. let defaultRequired = false;
  4528. do {
  4529. const typeParameter = this.flowParseTypeParameter(defaultRequired);
  4530. node.params.push(typeParameter);
  4531. if (typeParameter.default) {
  4532. defaultRequired = true;
  4533. }
  4534. if (!this.match(44)) {
  4535. this.expect(12);
  4536. }
  4537. } while (!this.match(44));
  4538. this.expect(44);
  4539. this.state.inType = oldInType;
  4540. return this.finishNode(node, "TypeParameterDeclaration");
  4541. }
  4542. flowParseTypeParameterInstantiation() {
  4543. const node = this.startNode();
  4544. const oldInType = this.state.inType;
  4545. node.params = [];
  4546. this.state.inType = true;
  4547. this.expect(43);
  4548. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  4549. this.state.noAnonFunctionType = false;
  4550. while (!this.match(44)) {
  4551. node.params.push(this.flowParseType());
  4552. if (!this.match(44)) {
  4553. this.expect(12);
  4554. }
  4555. }
  4556. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  4557. this.expect(44);
  4558. this.state.inType = oldInType;
  4559. return this.finishNode(node, "TypeParameterInstantiation");
  4560. }
  4561. flowParseTypeParameterInstantiationCallOrNew() {
  4562. const node = this.startNode();
  4563. const oldInType = this.state.inType;
  4564. node.params = [];
  4565. this.state.inType = true;
  4566. this.expect(43);
  4567. while (!this.match(44)) {
  4568. node.params.push(this.flowParseTypeOrImplicitInstantiation());
  4569. if (!this.match(44)) {
  4570. this.expect(12);
  4571. }
  4572. }
  4573. this.expect(44);
  4574. this.state.inType = oldInType;
  4575. return this.finishNode(node, "TypeParameterInstantiation");
  4576. }
  4577. flowParseInterfaceType() {
  4578. const node = this.startNode();
  4579. this.expectContextual(119);
  4580. node.extends = [];
  4581. if (this.eat(75)) {
  4582. do {
  4583. node.extends.push(this.flowParseInterfaceExtends());
  4584. } while (this.eat(12));
  4585. }
  4586. node.body = this.flowParseObjectType({
  4587. allowStatic: false,
  4588. allowExact: false,
  4589. allowSpread: false,
  4590. allowProto: false,
  4591. allowInexact: false
  4592. });
  4593. return this.finishNode(node, "InterfaceTypeAnnotation");
  4594. }
  4595. flowParseObjectPropertyKey() {
  4596. return this.match(124) || this.match(123) ? this.parseExprAtom() : this.parseIdentifier(true);
  4597. }
  4598. flowParseObjectTypeIndexer(node, isStatic, variance) {
  4599. node.static = isStatic;
  4600. if (this.lookahead().type === 14) {
  4601. node.id = this.flowParseObjectPropertyKey();
  4602. node.key = this.flowParseTypeInitialiser();
  4603. } else {
  4604. node.id = null;
  4605. node.key = this.flowParseType();
  4606. }
  4607. this.expect(3);
  4608. node.value = this.flowParseTypeInitialiser();
  4609. node.variance = variance;
  4610. return this.finishNode(node, "ObjectTypeIndexer");
  4611. }
  4612. flowParseObjectTypeInternalSlot(node, isStatic) {
  4613. node.static = isStatic;
  4614. node.id = this.flowParseObjectPropertyKey();
  4615. this.expect(3);
  4616. this.expect(3);
  4617. if (this.match(43) || this.match(10)) {
  4618. node.method = true;
  4619. node.optional = false;
  4620. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  4621. } else {
  4622. node.method = false;
  4623. if (this.eat(17)) {
  4624. node.optional = true;
  4625. }
  4626. node.value = this.flowParseTypeInitialiser();
  4627. }
  4628. return this.finishNode(node, "ObjectTypeInternalSlot");
  4629. }
  4630. flowParseObjectTypeMethodish(node) {
  4631. node.params = [];
  4632. node.rest = null;
  4633. node.typeParameters = null;
  4634. node.this = null;
  4635. if (this.match(43)) {
  4636. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4637. }
  4638. this.expect(10);
  4639. if (this.match(72)) {
  4640. node.this = this.flowParseFunctionTypeParam(true);
  4641. node.this.name = null;
  4642. if (!this.match(11)) {
  4643. this.expect(12);
  4644. }
  4645. }
  4646. while (!this.match(11) && !this.match(21)) {
  4647. node.params.push(this.flowParseFunctionTypeParam(false));
  4648. if (!this.match(11)) {
  4649. this.expect(12);
  4650. }
  4651. }
  4652. if (this.eat(21)) {
  4653. node.rest = this.flowParseFunctionTypeParam(false);
  4654. }
  4655. this.expect(11);
  4656. node.returnType = this.flowParseTypeInitialiser();
  4657. return this.finishNode(node, "FunctionTypeAnnotation");
  4658. }
  4659. flowParseObjectTypeCallProperty(node, isStatic) {
  4660. const valueNode = this.startNode();
  4661. node.static = isStatic;
  4662. node.value = this.flowParseObjectTypeMethodish(valueNode);
  4663. return this.finishNode(node, "ObjectTypeCallProperty");
  4664. }
  4665. flowParseObjectType({
  4666. allowStatic,
  4667. allowExact,
  4668. allowSpread,
  4669. allowProto,
  4670. allowInexact
  4671. }) {
  4672. const oldInType = this.state.inType;
  4673. this.state.inType = true;
  4674. const nodeStart = this.startNode();
  4675. nodeStart.callProperties = [];
  4676. nodeStart.properties = [];
  4677. nodeStart.indexers = [];
  4678. nodeStart.internalSlots = [];
  4679. let endDelim;
  4680. let exact;
  4681. let inexact = false;
  4682. if (allowExact && this.match(6)) {
  4683. this.expect(6);
  4684. endDelim = 9;
  4685. exact = true;
  4686. } else {
  4687. this.expect(5);
  4688. endDelim = 8;
  4689. exact = false;
  4690. }
  4691. nodeStart.exact = exact;
  4692. while (!this.match(endDelim)) {
  4693. let isStatic = false;
  4694. let protoStart = null;
  4695. let inexactStart = null;
  4696. const node = this.startNode();
  4697. if (allowProto && this.isContextual(109)) {
  4698. const lookahead = this.lookahead();
  4699. if (lookahead.type !== 14 && lookahead.type !== 17) {
  4700. this.next();
  4701. protoStart = this.state.start;
  4702. allowStatic = false;
  4703. }
  4704. }
  4705. if (allowStatic && this.isContextual(98)) {
  4706. const lookahead = this.lookahead();
  4707. if (lookahead.type !== 14 && lookahead.type !== 17) {
  4708. this.next();
  4709. isStatic = true;
  4710. }
  4711. }
  4712. const variance = this.flowParseVariance();
  4713. if (this.eat(0)) {
  4714. if (protoStart != null) {
  4715. this.unexpected(protoStart);
  4716. }
  4717. if (this.eat(0)) {
  4718. if (variance) {
  4719. this.unexpected(variance.start);
  4720. }
  4721. nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic));
  4722. } else {
  4723. nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance));
  4724. }
  4725. } else if (this.match(10) || this.match(43)) {
  4726. if (protoStart != null) {
  4727. this.unexpected(protoStart);
  4728. }
  4729. if (variance) {
  4730. this.unexpected(variance.start);
  4731. }
  4732. nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic));
  4733. } else {
  4734. let kind = "init";
  4735. if (this.isContextual(92) || this.isContextual(97)) {
  4736. const lookahead = this.lookahead();
  4737. if (tokenIsLiteralPropertyName(lookahead.type)) {
  4738. kind = this.state.value;
  4739. this.next();
  4740. }
  4741. }
  4742. const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact);
  4743. if (propOrInexact === null) {
  4744. inexact = true;
  4745. inexactStart = this.state.lastTokStart;
  4746. } else {
  4747. nodeStart.properties.push(propOrInexact);
  4748. }
  4749. }
  4750. this.flowObjectTypeSemicolon();
  4751. if (inexactStart && !this.match(8) && !this.match(9)) {
  4752. this.raise(inexactStart, FlowErrors.UnexpectedExplicitInexactInObject);
  4753. }
  4754. }
  4755. this.expect(endDelim);
  4756. if (allowSpread) {
  4757. nodeStart.inexact = inexact;
  4758. }
  4759. const out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
  4760. this.state.inType = oldInType;
  4761. return out;
  4762. }
  4763. flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact) {
  4764. if (this.eat(21)) {
  4765. const isInexactToken = this.match(12) || this.match(13) || this.match(8) || this.match(9);
  4766. if (isInexactToken) {
  4767. if (!allowSpread) {
  4768. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideNonObject);
  4769. } else if (!allowInexact) {
  4770. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideExact);
  4771. }
  4772. if (variance) {
  4773. this.raise(variance.start, FlowErrors.InexactVariance);
  4774. }
  4775. return null;
  4776. }
  4777. if (!allowSpread) {
  4778. this.raise(this.state.lastTokStart, FlowErrors.UnexpectedSpreadType);
  4779. }
  4780. if (protoStart != null) {
  4781. this.unexpected(protoStart);
  4782. }
  4783. if (variance) {
  4784. this.raise(variance.start, FlowErrors.SpreadVariance);
  4785. }
  4786. node.argument = this.flowParseType();
  4787. return this.finishNode(node, "ObjectTypeSpreadProperty");
  4788. } else {
  4789. node.key = this.flowParseObjectPropertyKey();
  4790. node.static = isStatic;
  4791. node.proto = protoStart != null;
  4792. node.kind = kind;
  4793. let optional = false;
  4794. if (this.match(43) || this.match(10)) {
  4795. node.method = true;
  4796. if (protoStart != null) {
  4797. this.unexpected(protoStart);
  4798. }
  4799. if (variance) {
  4800. this.unexpected(variance.start);
  4801. }
  4802. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  4803. if (kind === "get" || kind === "set") {
  4804. this.flowCheckGetterSetterParams(node);
  4805. }
  4806. if (!allowSpread && node.key.name === "constructor" && node.value.this) {
  4807. this.raise(node.value.this.start, FlowErrors.ThisParamBannedInConstructor);
  4808. }
  4809. } else {
  4810. if (kind !== "init") this.unexpected();
  4811. node.method = false;
  4812. if (this.eat(17)) {
  4813. optional = true;
  4814. }
  4815. node.value = this.flowParseTypeInitialiser();
  4816. node.variance = variance;
  4817. }
  4818. node.optional = optional;
  4819. return this.finishNode(node, "ObjectTypeProperty");
  4820. }
  4821. }
  4822. flowCheckGetterSetterParams(property) {
  4823. const paramCount = property.kind === "get" ? 0 : 1;
  4824. const start = property.start;
  4825. const length = property.value.params.length + (property.value.rest ? 1 : 0);
  4826. if (property.value.this) {
  4827. this.raise(property.value.this.start, property.kind === "get" ? FlowErrors.GetterMayNotHaveThisParam : FlowErrors.SetterMayNotHaveThisParam);
  4828. }
  4829. if (length !== paramCount) {
  4830. if (property.kind === "get") {
  4831. this.raise(start, ErrorMessages.BadGetterArity);
  4832. } else {
  4833. this.raise(start, ErrorMessages.BadSetterArity);
  4834. }
  4835. }
  4836. if (property.kind === "set" && property.value.rest) {
  4837. this.raise(start, ErrorMessages.BadSetterRestParameter);
  4838. }
  4839. }
  4840. flowObjectTypeSemicolon() {
  4841. if (!this.eat(13) && !this.eat(12) && !this.match(8) && !this.match(9)) {
  4842. this.unexpected();
  4843. }
  4844. }
  4845. flowParseQualifiedTypeIdentifier(startPos, startLoc, id) {
  4846. startPos = startPos || this.state.start;
  4847. startLoc = startLoc || this.state.startLoc;
  4848. let node = id || this.flowParseRestrictedIdentifier(true);
  4849. while (this.eat(16)) {
  4850. const node2 = this.startNodeAt(startPos, startLoc);
  4851. node2.qualification = node;
  4852. node2.id = this.flowParseRestrictedIdentifier(true);
  4853. node = this.finishNode(node2, "QualifiedTypeIdentifier");
  4854. }
  4855. return node;
  4856. }
  4857. flowParseGenericType(startPos, startLoc, id) {
  4858. const node = this.startNodeAt(startPos, startLoc);
  4859. node.typeParameters = null;
  4860. node.id = this.flowParseQualifiedTypeIdentifier(startPos, startLoc, id);
  4861. if (this.match(43)) {
  4862. node.typeParameters = this.flowParseTypeParameterInstantiation();
  4863. }
  4864. return this.finishNode(node, "GenericTypeAnnotation");
  4865. }
  4866. flowParseTypeofType() {
  4867. const node = this.startNode();
  4868. this.expect(81);
  4869. node.argument = this.flowParsePrimaryType();
  4870. return this.finishNode(node, "TypeofTypeAnnotation");
  4871. }
  4872. flowParseTupleType() {
  4873. const node = this.startNode();
  4874. node.types = [];
  4875. this.expect(0);
  4876. while (this.state.pos < this.length && !this.match(3)) {
  4877. node.types.push(this.flowParseType());
  4878. if (this.match(3)) break;
  4879. this.expect(12);
  4880. }
  4881. this.expect(3);
  4882. return this.finishNode(node, "TupleTypeAnnotation");
  4883. }
  4884. flowParseFunctionTypeParam(first) {
  4885. let name = null;
  4886. let optional = false;
  4887. let typeAnnotation = null;
  4888. const node = this.startNode();
  4889. const lh = this.lookahead();
  4890. const isThis = this.state.type === 72;
  4891. if (lh.type === 14 || lh.type === 17) {
  4892. if (isThis && !first) {
  4893. this.raise(node.start, FlowErrors.ThisParamMustBeFirst);
  4894. }
  4895. name = this.parseIdentifier(isThis);
  4896. if (this.eat(17)) {
  4897. optional = true;
  4898. if (isThis) {
  4899. this.raise(node.start, FlowErrors.ThisParamMayNotBeOptional);
  4900. }
  4901. }
  4902. typeAnnotation = this.flowParseTypeInitialiser();
  4903. } else {
  4904. typeAnnotation = this.flowParseType();
  4905. }
  4906. node.name = name;
  4907. node.optional = optional;
  4908. node.typeAnnotation = typeAnnotation;
  4909. return this.finishNode(node, "FunctionTypeParam");
  4910. }
  4911. reinterpretTypeAsFunctionTypeParam(type) {
  4912. const node = this.startNodeAt(type.start, type.loc.start);
  4913. node.name = null;
  4914. node.optional = false;
  4915. node.typeAnnotation = type;
  4916. return this.finishNode(node, "FunctionTypeParam");
  4917. }
  4918. flowParseFunctionTypeParams(params = []) {
  4919. let rest = null;
  4920. let _this = null;
  4921. if (this.match(72)) {
  4922. _this = this.flowParseFunctionTypeParam(true);
  4923. _this.name = null;
  4924. if (!this.match(11)) {
  4925. this.expect(12);
  4926. }
  4927. }
  4928. while (!this.match(11) && !this.match(21)) {
  4929. params.push(this.flowParseFunctionTypeParam(false));
  4930. if (!this.match(11)) {
  4931. this.expect(12);
  4932. }
  4933. }
  4934. if (this.eat(21)) {
  4935. rest = this.flowParseFunctionTypeParam(false);
  4936. }
  4937. return {
  4938. params,
  4939. rest,
  4940. _this
  4941. };
  4942. }
  4943. flowIdentToTypeAnnotation(startPos, startLoc, node, id) {
  4944. switch (id.name) {
  4945. case "any":
  4946. return this.finishNode(node, "AnyTypeAnnotation");
  4947. case "bool":
  4948. case "boolean":
  4949. return this.finishNode(node, "BooleanTypeAnnotation");
  4950. case "mixed":
  4951. return this.finishNode(node, "MixedTypeAnnotation");
  4952. case "empty":
  4953. return this.finishNode(node, "EmptyTypeAnnotation");
  4954. case "number":
  4955. return this.finishNode(node, "NumberTypeAnnotation");
  4956. case "string":
  4957. return this.finishNode(node, "StringTypeAnnotation");
  4958. case "symbol":
  4959. return this.finishNode(node, "SymbolTypeAnnotation");
  4960. default:
  4961. this.checkNotUnderscore(id.name);
  4962. return this.flowParseGenericType(startPos, startLoc, id);
  4963. }
  4964. }
  4965. flowParsePrimaryType() {
  4966. const startPos = this.state.start;
  4967. const startLoc = this.state.startLoc;
  4968. const node = this.startNode();
  4969. let tmp;
  4970. let type;
  4971. let isGroupedType = false;
  4972. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  4973. switch (this.state.type) {
  4974. case 5:
  4975. return this.flowParseObjectType({
  4976. allowStatic: false,
  4977. allowExact: false,
  4978. allowSpread: true,
  4979. allowProto: false,
  4980. allowInexact: true
  4981. });
  4982. case 6:
  4983. return this.flowParseObjectType({
  4984. allowStatic: false,
  4985. allowExact: true,
  4986. allowSpread: true,
  4987. allowProto: false,
  4988. allowInexact: false
  4989. });
  4990. case 0:
  4991. this.state.noAnonFunctionType = false;
  4992. type = this.flowParseTupleType();
  4993. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  4994. return type;
  4995. case 43:
  4996. node.typeParameters = this.flowParseTypeParameterDeclaration();
  4997. this.expect(10);
  4998. tmp = this.flowParseFunctionTypeParams();
  4999. node.params = tmp.params;
  5000. node.rest = tmp.rest;
  5001. node.this = tmp._this;
  5002. this.expect(11);
  5003. this.expect(19);
  5004. node.returnType = this.flowParseType();
  5005. return this.finishNode(node, "FunctionTypeAnnotation");
  5006. case 10:
  5007. this.next();
  5008. if (!this.match(11) && !this.match(21)) {
  5009. if (tokenIsIdentifier(this.state.type) || this.match(72)) {
  5010. const token = this.lookahead().type;
  5011. isGroupedType = token !== 17 && token !== 14;
  5012. } else {
  5013. isGroupedType = true;
  5014. }
  5015. }
  5016. if (isGroupedType) {
  5017. this.state.noAnonFunctionType = false;
  5018. type = this.flowParseType();
  5019. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  5020. if (this.state.noAnonFunctionType || !(this.match(12) || this.match(11) && this.lookahead().type === 19)) {
  5021. this.expect(11);
  5022. return type;
  5023. } else {
  5024. this.eat(12);
  5025. }
  5026. }
  5027. if (type) {
  5028. tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
  5029. } else {
  5030. tmp = this.flowParseFunctionTypeParams();
  5031. }
  5032. node.params = tmp.params;
  5033. node.rest = tmp.rest;
  5034. node.this = tmp._this;
  5035. this.expect(11);
  5036. this.expect(19);
  5037. node.returnType = this.flowParseType();
  5038. node.typeParameters = null;
  5039. return this.finishNode(node, "FunctionTypeAnnotation");
  5040. case 123:
  5041. return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
  5042. case 79:
  5043. case 80:
  5044. node.value = this.match(79);
  5045. this.next();
  5046. return this.finishNode(node, "BooleanLiteralTypeAnnotation");
  5047. case 47:
  5048. if (this.state.value === "-") {
  5049. this.next();
  5050. if (this.match(124)) {
  5051. return this.parseLiteralAtNode(-this.state.value, "NumberLiteralTypeAnnotation", node);
  5052. }
  5053. if (this.match(125)) {
  5054. return this.parseLiteralAtNode(-this.state.value, "BigIntLiteralTypeAnnotation", node);
  5055. }
  5056. throw this.raise(this.state.start, FlowErrors.UnexpectedSubtractionOperand);
  5057. }
  5058. throw this.unexpected();
  5059. case 124:
  5060. return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
  5061. case 125:
  5062. return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation");
  5063. case 82:
  5064. this.next();
  5065. return this.finishNode(node, "VoidTypeAnnotation");
  5066. case 78:
  5067. this.next();
  5068. return this.finishNode(node, "NullLiteralTypeAnnotation");
  5069. case 72:
  5070. this.next();
  5071. return this.finishNode(node, "ThisTypeAnnotation");
  5072. case 49:
  5073. this.next();
  5074. return this.finishNode(node, "ExistsTypeAnnotation");
  5075. case 81:
  5076. return this.flowParseTypeofType();
  5077. default:
  5078. if (tokenIsKeyword(this.state.type)) {
  5079. const label = tokenLabelName(this.state.type);
  5080. this.next();
  5081. return super.createIdentifier(node, label);
  5082. } else if (tokenIsIdentifier(this.state.type)) {
  5083. if (this.isContextual(119)) {
  5084. return this.flowParseInterfaceType();
  5085. }
  5086. return this.flowIdentToTypeAnnotation(startPos, startLoc, node, this.parseIdentifier());
  5087. }
  5088. }
  5089. throw this.unexpected();
  5090. }
  5091. flowParsePostfixType() {
  5092. const startPos = this.state.start;
  5093. const startLoc = this.state.startLoc;
  5094. let type = this.flowParsePrimaryType();
  5095. let seenOptionalIndexedAccess = false;
  5096. while ((this.match(0) || this.match(18)) && !this.canInsertSemicolon()) {
  5097. const node = this.startNodeAt(startPos, startLoc);
  5098. const optional = this.eat(18);
  5099. seenOptionalIndexedAccess = seenOptionalIndexedAccess || optional;
  5100. this.expect(0);
  5101. if (!optional && this.match(3)) {
  5102. node.elementType = type;
  5103. this.next();
  5104. type = this.finishNode(node, "ArrayTypeAnnotation");
  5105. } else {
  5106. node.objectType = type;
  5107. node.indexType = this.flowParseType();
  5108. this.expect(3);
  5109. if (seenOptionalIndexedAccess) {
  5110. node.optional = optional;
  5111. type = this.finishNode(node, "OptionalIndexedAccessType");
  5112. } else {
  5113. type = this.finishNode(node, "IndexedAccessType");
  5114. }
  5115. }
  5116. }
  5117. return type;
  5118. }
  5119. flowParsePrefixType() {
  5120. const node = this.startNode();
  5121. if (this.eat(17)) {
  5122. node.typeAnnotation = this.flowParsePrefixType();
  5123. return this.finishNode(node, "NullableTypeAnnotation");
  5124. } else {
  5125. return this.flowParsePostfixType();
  5126. }
  5127. }
  5128. flowParseAnonFunctionWithoutParens() {
  5129. const param = this.flowParsePrefixType();
  5130. if (!this.state.noAnonFunctionType && this.eat(19)) {
  5131. const node = this.startNodeAt(param.start, param.loc.start);
  5132. node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
  5133. node.rest = null;
  5134. node.this = null;
  5135. node.returnType = this.flowParseType();
  5136. node.typeParameters = null;
  5137. return this.finishNode(node, "FunctionTypeAnnotation");
  5138. }
  5139. return param;
  5140. }
  5141. flowParseIntersectionType() {
  5142. const node = this.startNode();
  5143. this.eat(41);
  5144. const type = this.flowParseAnonFunctionWithoutParens();
  5145. node.types = [type];
  5146. while (this.eat(41)) {
  5147. node.types.push(this.flowParseAnonFunctionWithoutParens());
  5148. }
  5149. return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
  5150. }
  5151. flowParseUnionType() {
  5152. const node = this.startNode();
  5153. this.eat(39);
  5154. const type = this.flowParseIntersectionType();
  5155. node.types = [type];
  5156. while (this.eat(39)) {
  5157. node.types.push(this.flowParseIntersectionType());
  5158. }
  5159. return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
  5160. }
  5161. flowParseType() {
  5162. const oldInType = this.state.inType;
  5163. this.state.inType = true;
  5164. const type = this.flowParseUnionType();
  5165. this.state.inType = oldInType;
  5166. return type;
  5167. }
  5168. flowParseTypeOrImplicitInstantiation() {
  5169. if (this.state.type === 122 && this.state.value === "_") {
  5170. const startPos = this.state.start;
  5171. const startLoc = this.state.startLoc;
  5172. const node = this.parseIdentifier();
  5173. return this.flowParseGenericType(startPos, startLoc, node);
  5174. } else {
  5175. return this.flowParseType();
  5176. }
  5177. }
  5178. flowParseTypeAnnotation() {
  5179. const node = this.startNode();
  5180. node.typeAnnotation = this.flowParseTypeInitialiser();
  5181. return this.finishNode(node, "TypeAnnotation");
  5182. }
  5183. flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) {
  5184. const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier();
  5185. if (this.match(14)) {
  5186. ident.typeAnnotation = this.flowParseTypeAnnotation();
  5187. this.resetEndLocation(ident);
  5188. }
  5189. return ident;
  5190. }
  5191. typeCastToParameter(node) {
  5192. node.expression.typeAnnotation = node.typeAnnotation;
  5193. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  5194. return node.expression;
  5195. }
  5196. flowParseVariance() {
  5197. let variance = null;
  5198. if (this.match(47)) {
  5199. variance = this.startNode();
  5200. if (this.state.value === "+") {
  5201. variance.kind = "plus";
  5202. } else {
  5203. variance.kind = "minus";
  5204. }
  5205. this.next();
  5206. this.finishNode(variance, "Variance");
  5207. }
  5208. return variance;
  5209. }
  5210. parseFunctionBody(node, allowExpressionBody, isMethod = false) {
  5211. if (allowExpressionBody) {
  5212. return this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod));
  5213. }
  5214. return super.parseFunctionBody(node, false, isMethod);
  5215. }
  5216. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  5217. if (this.match(14)) {
  5218. const typeNode = this.startNode();
  5219. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  5220. node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
  5221. }
  5222. super.parseFunctionBodyAndFinish(node, type, isMethod);
  5223. }
  5224. parseStatement(context, topLevel) {
  5225. if (this.state.strict && this.isContextual(119)) {
  5226. const lookahead = this.lookahead();
  5227. if (tokenIsKeywordOrIdentifier(lookahead.type)) {
  5228. const node = this.startNode();
  5229. this.next();
  5230. return this.flowParseInterface(node);
  5231. }
  5232. } else if (this.shouldParseEnums() && this.isContextual(116)) {
  5233. const node = this.startNode();
  5234. this.next();
  5235. return this.flowParseEnumDeclaration(node);
  5236. }
  5237. const stmt = super.parseStatement(context, topLevel);
  5238. if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {
  5239. this.flowPragma = null;
  5240. }
  5241. return stmt;
  5242. }
  5243. parseExpressionStatement(node, expr) {
  5244. if (expr.type === "Identifier") {
  5245. if (expr.name === "declare") {
  5246. if (this.match(74) || tokenIsIdentifier(this.state.type) || this.match(62) || this.match(68) || this.match(76)) {
  5247. return this.flowParseDeclare(node);
  5248. }
  5249. } else if (tokenIsIdentifier(this.state.type)) {
  5250. if (expr.name === "interface") {
  5251. return this.flowParseInterface(node);
  5252. } else if (expr.name === "type") {
  5253. return this.flowParseTypeAlias(node);
  5254. } else if (expr.name === "opaque") {
  5255. return this.flowParseOpaqueType(node, false);
  5256. }
  5257. }
  5258. }
  5259. return super.parseExpressionStatement(node, expr);
  5260. }
  5261. shouldParseExportDeclaration() {
  5262. const {
  5263. type
  5264. } = this.state;
  5265. if (tokenIsFlowInterfaceOrTypeOrOpaque(type) || this.shouldParseEnums() && type === 116) {
  5266. return !this.state.containsEsc;
  5267. }
  5268. return super.shouldParseExportDeclaration();
  5269. }
  5270. isExportDefaultSpecifier() {
  5271. const {
  5272. type
  5273. } = this.state;
  5274. if (tokenIsFlowInterfaceOrTypeOrOpaque(type) || this.shouldParseEnums() && type === 116) {
  5275. return this.state.containsEsc;
  5276. }
  5277. return super.isExportDefaultSpecifier();
  5278. }
  5279. parseExportDefaultExpression() {
  5280. if (this.shouldParseEnums() && this.isContextual(116)) {
  5281. const node = this.startNode();
  5282. this.next();
  5283. return this.flowParseEnumDeclaration(node);
  5284. }
  5285. return super.parseExportDefaultExpression();
  5286. }
  5287. parseConditional(expr, startPos, startLoc, refExpressionErrors) {
  5288. if (!this.match(17)) return expr;
  5289. if (this.state.maybeInArrowParameters) {
  5290. const nextCh = this.lookaheadCharCode();
  5291. if (nextCh === 44 || nextCh === 61 || nextCh === 58 || nextCh === 41) {
  5292. this.setOptionalParametersError(refExpressionErrors);
  5293. return expr;
  5294. }
  5295. }
  5296. this.expect(17);
  5297. const state = this.state.clone();
  5298. const originalNoArrowAt = this.state.noArrowAt;
  5299. const node = this.startNodeAt(startPos, startLoc);
  5300. let {
  5301. consequent,
  5302. failed
  5303. } = this.tryParseConditionalConsequent();
  5304. let [valid, invalid] = this.getArrowLikeExpressions(consequent);
  5305. if (failed || invalid.length > 0) {
  5306. const noArrowAt = [...originalNoArrowAt];
  5307. if (invalid.length > 0) {
  5308. this.state = state;
  5309. this.state.noArrowAt = noArrowAt;
  5310. for (let i = 0; i < invalid.length; i++) {
  5311. noArrowAt.push(invalid[i].start);
  5312. }
  5313. ({
  5314. consequent,
  5315. failed
  5316. } = this.tryParseConditionalConsequent());
  5317. [valid, invalid] = this.getArrowLikeExpressions(consequent);
  5318. }
  5319. if (failed && valid.length > 1) {
  5320. this.raise(state.start, FlowErrors.AmbiguousConditionalArrow);
  5321. }
  5322. if (failed && valid.length === 1) {
  5323. this.state = state;
  5324. noArrowAt.push(valid[0].start);
  5325. this.state.noArrowAt = noArrowAt;
  5326. ({
  5327. consequent,
  5328. failed
  5329. } = this.tryParseConditionalConsequent());
  5330. }
  5331. }
  5332. this.getArrowLikeExpressions(consequent, true);
  5333. this.state.noArrowAt = originalNoArrowAt;
  5334. this.expect(14);
  5335. node.test = expr;
  5336. node.consequent = consequent;
  5337. node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(undefined, undefined));
  5338. return this.finishNode(node, "ConditionalExpression");
  5339. }
  5340. tryParseConditionalConsequent() {
  5341. this.state.noArrowParamsConversionAt.push(this.state.start);
  5342. const consequent = this.parseMaybeAssignAllowIn();
  5343. const failed = !this.match(14);
  5344. this.state.noArrowParamsConversionAt.pop();
  5345. return {
  5346. consequent,
  5347. failed
  5348. };
  5349. }
  5350. getArrowLikeExpressions(node, disallowInvalid) {
  5351. const stack = [node];
  5352. const arrows = [];
  5353. while (stack.length !== 0) {
  5354. const node = stack.pop();
  5355. if (node.type === "ArrowFunctionExpression") {
  5356. if (node.typeParameters || !node.returnType) {
  5357. this.finishArrowValidation(node);
  5358. } else {
  5359. arrows.push(node);
  5360. }
  5361. stack.push(node.body);
  5362. } else if (node.type === "ConditionalExpression") {
  5363. stack.push(node.consequent);
  5364. stack.push(node.alternate);
  5365. }
  5366. }
  5367. if (disallowInvalid) {
  5368. arrows.forEach(node => this.finishArrowValidation(node));
  5369. return [arrows, []];
  5370. }
  5371. return partition(arrows, node => node.params.every(param => this.isAssignable(param, true)));
  5372. }
  5373. finishArrowValidation(node) {
  5374. var _node$extra;
  5375. this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingComma, false);
  5376. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  5377. super.checkParams(node, false, true);
  5378. this.scope.exit();
  5379. }
  5380. forwardNoArrowParamsConversionAt(node, parse) {
  5381. let result;
  5382. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  5383. this.state.noArrowParamsConversionAt.push(this.state.start);
  5384. result = parse();
  5385. this.state.noArrowParamsConversionAt.pop();
  5386. } else {
  5387. result = parse();
  5388. }
  5389. return result;
  5390. }
  5391. parseParenItem(node, startPos, startLoc) {
  5392. node = super.parseParenItem(node, startPos, startLoc);
  5393. if (this.eat(17)) {
  5394. node.optional = true;
  5395. this.resetEndLocation(node);
  5396. }
  5397. if (this.match(14)) {
  5398. const typeCastNode = this.startNodeAt(startPos, startLoc);
  5399. typeCastNode.expression = node;
  5400. typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
  5401. return this.finishNode(typeCastNode, "TypeCastExpression");
  5402. }
  5403. return node;
  5404. }
  5405. assertModuleNodeAllowed(node) {
  5406. if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") {
  5407. return;
  5408. }
  5409. super.assertModuleNodeAllowed(node);
  5410. }
  5411. parseExport(node) {
  5412. const decl = super.parseExport(node);
  5413. if (decl.type === "ExportNamedDeclaration" || decl.type === "ExportAllDeclaration") {
  5414. decl.exportKind = decl.exportKind || "value";
  5415. }
  5416. return decl;
  5417. }
  5418. parseExportDeclaration(node) {
  5419. if (this.isContextual(120)) {
  5420. node.exportKind = "type";
  5421. const declarationNode = this.startNode();
  5422. this.next();
  5423. if (this.match(5)) {
  5424. node.specifiers = this.parseExportSpecifiers(true);
  5425. this.parseExportFrom(node);
  5426. return null;
  5427. } else {
  5428. return this.flowParseTypeAlias(declarationNode);
  5429. }
  5430. } else if (this.isContextual(121)) {
  5431. node.exportKind = "type";
  5432. const declarationNode = this.startNode();
  5433. this.next();
  5434. return this.flowParseOpaqueType(declarationNode, false);
  5435. } else if (this.isContextual(119)) {
  5436. node.exportKind = "type";
  5437. const declarationNode = this.startNode();
  5438. this.next();
  5439. return this.flowParseInterface(declarationNode);
  5440. } else if (this.shouldParseEnums() && this.isContextual(116)) {
  5441. node.exportKind = "value";
  5442. const declarationNode = this.startNode();
  5443. this.next();
  5444. return this.flowParseEnumDeclaration(declarationNode);
  5445. } else {
  5446. return super.parseExportDeclaration(node);
  5447. }
  5448. }
  5449. eatExportStar(node) {
  5450. if (super.eatExportStar(...arguments)) return true;
  5451. if (this.isContextual(120) && this.lookahead().type === 49) {
  5452. node.exportKind = "type";
  5453. this.next();
  5454. this.next();
  5455. return true;
  5456. }
  5457. return false;
  5458. }
  5459. maybeParseExportNamespaceSpecifier(node) {
  5460. const pos = this.state.start;
  5461. const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);
  5462. if (hasNamespace && node.exportKind === "type") {
  5463. this.unexpected(pos);
  5464. }
  5465. return hasNamespace;
  5466. }
  5467. parseClassId(node, isStatement, optionalId) {
  5468. super.parseClassId(node, isStatement, optionalId);
  5469. if (this.match(43)) {
  5470. node.typeParameters = this.flowParseTypeParameterDeclaration();
  5471. }
  5472. }
  5473. parseClassMember(classBody, member, state) {
  5474. const pos = this.state.start;
  5475. if (this.isContextual(115)) {
  5476. if (this.parseClassMemberFromModifier(classBody, member)) {
  5477. return;
  5478. }
  5479. member.declare = true;
  5480. }
  5481. super.parseClassMember(classBody, member, state);
  5482. if (member.declare) {
  5483. if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty" && member.type !== "PropertyDefinition") {
  5484. this.raise(pos, FlowErrors.DeclareClassElement);
  5485. } else if (member.value) {
  5486. this.raise(member.value.start, FlowErrors.DeclareClassFieldInitializer);
  5487. }
  5488. }
  5489. }
  5490. isIterator(word) {
  5491. return word === "iterator" || word === "asyncIterator";
  5492. }
  5493. readIterator() {
  5494. const word = super.readWord1();
  5495. const fullWord = "@@" + word;
  5496. if (!this.isIterator(word) || !this.state.inType) {
  5497. this.raise(this.state.pos, ErrorMessages.InvalidIdentifier, fullWord);
  5498. }
  5499. this.finishToken(122, fullWord);
  5500. }
  5501. getTokenFromCode(code) {
  5502. const next = this.input.charCodeAt(this.state.pos + 1);
  5503. if (code === 123 && next === 124) {
  5504. return this.finishOp(6, 2);
  5505. } else if (this.state.inType && (code === 62 || code === 60)) {
  5506. return this.finishOp(code === 62 ? 44 : 43, 1);
  5507. } else if (this.state.inType && code === 63) {
  5508. if (next === 46) {
  5509. return this.finishOp(18, 2);
  5510. }
  5511. return this.finishOp(17, 1);
  5512. } else if (isIteratorStart(code, next)) {
  5513. this.state.pos += 2;
  5514. return this.readIterator();
  5515. } else {
  5516. return super.getTokenFromCode(code);
  5517. }
  5518. }
  5519. isAssignable(node, isBinding) {
  5520. if (node.type === "TypeCastExpression") {
  5521. return this.isAssignable(node.expression, isBinding);
  5522. } else {
  5523. return super.isAssignable(node, isBinding);
  5524. }
  5525. }
  5526. toAssignable(node, isLHS = false) {
  5527. if (node.type === "TypeCastExpression") {
  5528. return super.toAssignable(this.typeCastToParameter(node), isLHS);
  5529. } else {
  5530. return super.toAssignable(node, isLHS);
  5531. }
  5532. }
  5533. toAssignableList(exprList, trailingCommaPos, isLHS) {
  5534. for (let i = 0; i < exprList.length; i++) {
  5535. const expr = exprList[i];
  5536. if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") {
  5537. exprList[i] = this.typeCastToParameter(expr);
  5538. }
  5539. }
  5540. return super.toAssignableList(exprList, trailingCommaPos, isLHS);
  5541. }
  5542. toReferencedList(exprList, isParenthesizedExpr) {
  5543. for (let i = 0; i < exprList.length; i++) {
  5544. var _expr$extra;
  5545. const expr = exprList[i];
  5546. if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) != null && _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) {
  5547. this.raise(expr.typeAnnotation.start, FlowErrors.TypeCastInPattern);
  5548. }
  5549. }
  5550. return exprList;
  5551. }
  5552. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  5553. const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors);
  5554. if (canBePattern && !this.state.maybeInArrowParameters) {
  5555. this.toReferencedList(node.elements);
  5556. }
  5557. return node;
  5558. }
  5559. checkLVal(expr, ...args) {
  5560. if (expr.type !== "TypeCastExpression") {
  5561. return super.checkLVal(expr, ...args);
  5562. }
  5563. }
  5564. parseClassProperty(node) {
  5565. if (this.match(14)) {
  5566. node.typeAnnotation = this.flowParseTypeAnnotation();
  5567. }
  5568. return super.parseClassProperty(node);
  5569. }
  5570. parseClassPrivateProperty(node) {
  5571. if (this.match(14)) {
  5572. node.typeAnnotation = this.flowParseTypeAnnotation();
  5573. }
  5574. return super.parseClassPrivateProperty(node);
  5575. }
  5576. isClassMethod() {
  5577. return this.match(43) || super.isClassMethod();
  5578. }
  5579. isClassProperty() {
  5580. return this.match(14) || super.isClassProperty();
  5581. }
  5582. isNonstaticConstructor(method) {
  5583. return !this.match(14) && super.isNonstaticConstructor(method);
  5584. }
  5585. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  5586. if (method.variance) {
  5587. this.unexpected(method.variance.start);
  5588. }
  5589. delete method.variance;
  5590. if (this.match(43)) {
  5591. method.typeParameters = this.flowParseTypeParameterDeclaration();
  5592. }
  5593. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  5594. if (method.params && isConstructor) {
  5595. const params = method.params;
  5596. if (params.length > 0 && this.isThisParam(params[0])) {
  5597. this.raise(method.start, FlowErrors.ThisParamBannedInConstructor);
  5598. }
  5599. } else if (method.type === "MethodDefinition" && isConstructor && method.value.params) {
  5600. const params = method.value.params;
  5601. if (params.length > 0 && this.isThisParam(params[0])) {
  5602. this.raise(method.start, FlowErrors.ThisParamBannedInConstructor);
  5603. }
  5604. }
  5605. }
  5606. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  5607. if (method.variance) {
  5608. this.unexpected(method.variance.start);
  5609. }
  5610. delete method.variance;
  5611. if (this.match(43)) {
  5612. method.typeParameters = this.flowParseTypeParameterDeclaration();
  5613. }
  5614. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  5615. }
  5616. parseClassSuper(node) {
  5617. super.parseClassSuper(node);
  5618. if (node.superClass && this.match(43)) {
  5619. node.superTypeParameters = this.flowParseTypeParameterInstantiation();
  5620. }
  5621. if (this.isContextual(104)) {
  5622. this.next();
  5623. const implemented = node.implements = [];
  5624. do {
  5625. const node = this.startNode();
  5626. node.id = this.flowParseRestrictedIdentifier(true);
  5627. if (this.match(43)) {
  5628. node.typeParameters = this.flowParseTypeParameterInstantiation();
  5629. } else {
  5630. node.typeParameters = null;
  5631. }
  5632. implemented.push(this.finishNode(node, "ClassImplements"));
  5633. } while (this.eat(12));
  5634. }
  5635. }
  5636. checkGetterSetterParams(method) {
  5637. super.checkGetterSetterParams(method);
  5638. const params = this.getObjectOrClassMethodParams(method);
  5639. if (params.length > 0) {
  5640. const param = params[0];
  5641. if (this.isThisParam(param) && method.kind === "get") {
  5642. this.raise(param.start, FlowErrors.GetterMayNotHaveThisParam);
  5643. } else if (this.isThisParam(param)) {
  5644. this.raise(param.start, FlowErrors.SetterMayNotHaveThisParam);
  5645. }
  5646. }
  5647. }
  5648. parsePropertyNamePrefixOperator(node) {
  5649. node.variance = this.flowParseVariance();
  5650. }
  5651. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  5652. if (prop.variance) {
  5653. this.unexpected(prop.variance.start);
  5654. }
  5655. delete prop.variance;
  5656. let typeParameters;
  5657. if (this.match(43) && !isAccessor) {
  5658. typeParameters = this.flowParseTypeParameterDeclaration();
  5659. if (!this.match(10)) this.unexpected();
  5660. }
  5661. super.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  5662. if (typeParameters) {
  5663. (prop.value || prop).typeParameters = typeParameters;
  5664. }
  5665. }
  5666. parseAssignableListItemTypes(param) {
  5667. if (this.eat(17)) {
  5668. if (param.type !== "Identifier") {
  5669. this.raise(param.start, FlowErrors.PatternIsOptional);
  5670. }
  5671. if (this.isThisParam(param)) {
  5672. this.raise(param.start, FlowErrors.ThisParamMayNotBeOptional);
  5673. }
  5674. param.optional = true;
  5675. }
  5676. if (this.match(14)) {
  5677. param.typeAnnotation = this.flowParseTypeAnnotation();
  5678. } else if (this.isThisParam(param)) {
  5679. this.raise(param.start, FlowErrors.ThisParamAnnotationRequired);
  5680. }
  5681. if (this.match(27) && this.isThisParam(param)) {
  5682. this.raise(param.start, FlowErrors.ThisParamNoDefault);
  5683. }
  5684. this.resetEndLocation(param);
  5685. return param;
  5686. }
  5687. parseMaybeDefault(startPos, startLoc, left) {
  5688. const node = super.parseMaybeDefault(startPos, startLoc, left);
  5689. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  5690. this.raise(node.typeAnnotation.start, FlowErrors.TypeBeforeInitializer);
  5691. }
  5692. return node;
  5693. }
  5694. shouldParseDefaultImport(node) {
  5695. if (!hasTypeImportKind(node)) {
  5696. return super.shouldParseDefaultImport(node);
  5697. }
  5698. return isMaybeDefaultImport(this.state.type);
  5699. }
  5700. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  5701. specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier();
  5702. this.checkLVal(specifier.local, contextDescription, BIND_LEXICAL);
  5703. node.specifiers.push(this.finishNode(specifier, type));
  5704. }
  5705. maybeParseDefaultImportSpecifier(node) {
  5706. node.importKind = "value";
  5707. let kind = null;
  5708. if (this.match(81)) {
  5709. kind = "typeof";
  5710. } else if (this.isContextual(120)) {
  5711. kind = "type";
  5712. }
  5713. if (kind) {
  5714. const lh = this.lookahead();
  5715. const {
  5716. type
  5717. } = lh;
  5718. if (kind === "type" && type === 49) {
  5719. this.unexpected(lh.start);
  5720. }
  5721. if (isMaybeDefaultImport(type) || type === 5 || type === 49) {
  5722. this.next();
  5723. node.importKind = kind;
  5724. }
  5725. }
  5726. return super.maybeParseDefaultImportSpecifier(node);
  5727. }
  5728. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly) {
  5729. const firstIdent = specifier.imported;
  5730. let specifierTypeKind = null;
  5731. if (firstIdent.type === "Identifier") {
  5732. if (firstIdent.name === "type") {
  5733. specifierTypeKind = "type";
  5734. } else if (firstIdent.name === "typeof") {
  5735. specifierTypeKind = "typeof";
  5736. }
  5737. }
  5738. let isBinding = false;
  5739. if (this.isContextual(87) && !this.isLookaheadContextual("as")) {
  5740. const as_ident = this.parseIdentifier(true);
  5741. if (specifierTypeKind !== null && !tokenIsKeywordOrIdentifier(this.state.type)) {
  5742. specifier.imported = as_ident;
  5743. specifier.importKind = specifierTypeKind;
  5744. specifier.local = cloneIdentifier(as_ident);
  5745. } else {
  5746. specifier.imported = firstIdent;
  5747. specifier.importKind = null;
  5748. specifier.local = this.parseIdentifier();
  5749. }
  5750. } else {
  5751. if (specifierTypeKind !== null && tokenIsKeywordOrIdentifier(this.state.type)) {
  5752. specifier.imported = this.parseIdentifier(true);
  5753. specifier.importKind = specifierTypeKind;
  5754. } else {
  5755. if (importedIsString) {
  5756. throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, firstIdent.value);
  5757. }
  5758. specifier.imported = firstIdent;
  5759. specifier.importKind = null;
  5760. }
  5761. if (this.eatContextual(87)) {
  5762. specifier.local = this.parseIdentifier();
  5763. } else {
  5764. isBinding = true;
  5765. specifier.local = cloneIdentifier(specifier.imported);
  5766. }
  5767. }
  5768. const specifierIsTypeImport = hasTypeImportKind(specifier);
  5769. if (isInTypeOnlyImport && specifierIsTypeImport) {
  5770. this.raise(specifier.start, FlowErrors.ImportTypeShorthandOnlyInPureImport);
  5771. }
  5772. if (isInTypeOnlyImport || specifierIsTypeImport) {
  5773. this.checkReservedType(specifier.local.name, specifier.local.start, true);
  5774. }
  5775. if (isBinding && !isInTypeOnlyImport && !specifierIsTypeImport) {
  5776. this.checkReservedWord(specifier.local.name, specifier.start, true, true);
  5777. }
  5778. this.checkLVal(specifier.local, "import specifier", BIND_LEXICAL);
  5779. return this.finishNode(specifier, "ImportSpecifier");
  5780. }
  5781. parseBindingAtom() {
  5782. switch (this.state.type) {
  5783. case 72:
  5784. return this.parseIdentifier(true);
  5785. default:
  5786. return super.parseBindingAtom();
  5787. }
  5788. }
  5789. parseFunctionParams(node, allowModifiers) {
  5790. const kind = node.kind;
  5791. if (kind !== "get" && kind !== "set" && this.match(43)) {
  5792. node.typeParameters = this.flowParseTypeParameterDeclaration();
  5793. }
  5794. super.parseFunctionParams(node, allowModifiers);
  5795. }
  5796. parseVarId(decl, kind) {
  5797. super.parseVarId(decl, kind);
  5798. if (this.match(14)) {
  5799. decl.id.typeAnnotation = this.flowParseTypeAnnotation();
  5800. this.resetEndLocation(decl.id);
  5801. }
  5802. }
  5803. parseAsyncArrowFromCallExpression(node, call) {
  5804. if (this.match(14)) {
  5805. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  5806. this.state.noAnonFunctionType = true;
  5807. node.returnType = this.flowParseTypeAnnotation();
  5808. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  5809. }
  5810. return super.parseAsyncArrowFromCallExpression(node, call);
  5811. }
  5812. shouldParseAsyncArrow() {
  5813. return this.match(14) || super.shouldParseAsyncArrow();
  5814. }
  5815. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  5816. var _jsx;
  5817. let state = null;
  5818. let jsx;
  5819. if (this.hasPlugin("jsx") && (this.match(132) || this.match(43))) {
  5820. state = this.state.clone();
  5821. jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
  5822. if (!jsx.error) return jsx.node;
  5823. const {
  5824. context
  5825. } = this.state;
  5826. const curContext = context[context.length - 1];
  5827. if (curContext === types.j_oTag) {
  5828. context.length -= 2;
  5829. } else if (curContext === types.j_expr) {
  5830. context.length -= 1;
  5831. }
  5832. }
  5833. if ((_jsx = jsx) != null && _jsx.error || this.match(43)) {
  5834. var _jsx2, _jsx3;
  5835. state = state || this.state.clone();
  5836. let typeParameters;
  5837. const arrow = this.tryParse(abort => {
  5838. var _arrowExpression$extr;
  5839. typeParameters = this.flowParseTypeParameterDeclaration();
  5840. const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => {
  5841. const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  5842. this.resetStartLocationFromNode(result, typeParameters);
  5843. return result;
  5844. });
  5845. if ((_arrowExpression$extr = arrowExpression.extra) != null && _arrowExpression$extr.parenthesized) abort();
  5846. const expr = this.maybeUnwrapTypeCastExpression(arrowExpression);
  5847. if (expr.type !== "ArrowFunctionExpression") abort();
  5848. expr.typeParameters = typeParameters;
  5849. this.resetStartLocationFromNode(expr, typeParameters);
  5850. return arrowExpression;
  5851. }, state);
  5852. let arrowExpression = null;
  5853. if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") {
  5854. if (!arrow.error && !arrow.aborted) {
  5855. if (arrow.node.async) {
  5856. this.raise(typeParameters.start, FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction);
  5857. }
  5858. return arrow.node;
  5859. }
  5860. arrowExpression = arrow.node;
  5861. }
  5862. if ((_jsx2 = jsx) != null && _jsx2.node) {
  5863. this.state = jsx.failState;
  5864. return jsx.node;
  5865. }
  5866. if (arrowExpression) {
  5867. this.state = arrow.failState;
  5868. return arrowExpression;
  5869. }
  5870. if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error;
  5871. if (arrow.thrown) throw arrow.error;
  5872. throw this.raise(typeParameters.start, FlowErrors.UnexpectedTokenAfterTypeParameter);
  5873. }
  5874. return super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  5875. }
  5876. parseArrow(node) {
  5877. if (this.match(14)) {
  5878. const result = this.tryParse(() => {
  5879. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  5880. this.state.noAnonFunctionType = true;
  5881. const typeNode = this.startNode();
  5882. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  5883. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  5884. if (this.canInsertSemicolon()) this.unexpected();
  5885. if (!this.match(19)) this.unexpected();
  5886. return typeNode;
  5887. });
  5888. if (result.thrown) return null;
  5889. if (result.error) this.state = result.failState;
  5890. node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null;
  5891. }
  5892. return super.parseArrow(node);
  5893. }
  5894. shouldParseArrow(params) {
  5895. return this.match(14) || super.shouldParseArrow(params);
  5896. }
  5897. setArrowFunctionParameters(node, params) {
  5898. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  5899. node.params = params;
  5900. } else {
  5901. super.setArrowFunctionParameters(node, params);
  5902. }
  5903. }
  5904. checkParams(node, allowDuplicates, isArrowFunction) {
  5905. if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  5906. return;
  5907. }
  5908. for (let i = 0; i < node.params.length; i++) {
  5909. if (this.isThisParam(node.params[i]) && i > 0) {
  5910. this.raise(node.params[i].start, FlowErrors.ThisParamMustBeFirst);
  5911. }
  5912. }
  5913. return super.checkParams(...arguments);
  5914. }
  5915. parseParenAndDistinguishExpression(canBeArrow) {
  5916. return super.parseParenAndDistinguishExpression(canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1);
  5917. }
  5918. parseSubscripts(base, startPos, startLoc, noCalls) {
  5919. if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.indexOf(startPos) !== -1) {
  5920. this.next();
  5921. const node = this.startNodeAt(startPos, startLoc);
  5922. node.callee = base;
  5923. node.arguments = this.parseCallExpressionArguments(11, false);
  5924. base = this.finishNode(node, "CallExpression");
  5925. } else if (base.type === "Identifier" && base.name === "async" && this.match(43)) {
  5926. const state = this.state.clone();
  5927. const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startPos, startLoc) || abort(), state);
  5928. if (!arrow.error && !arrow.aborted) return arrow.node;
  5929. const result = this.tryParse(() => super.parseSubscripts(base, startPos, startLoc, noCalls), state);
  5930. if (result.node && !result.error) return result.node;
  5931. if (arrow.node) {
  5932. this.state = arrow.failState;
  5933. return arrow.node;
  5934. }
  5935. if (result.node) {
  5936. this.state = result.failState;
  5937. return result.node;
  5938. }
  5939. throw arrow.error || result.error;
  5940. }
  5941. return super.parseSubscripts(base, startPos, startLoc, noCalls);
  5942. }
  5943. parseSubscript(base, startPos, startLoc, noCalls, subscriptState) {
  5944. if (this.match(18) && this.isLookaheadToken_lt()) {
  5945. subscriptState.optionalChainMember = true;
  5946. if (noCalls) {
  5947. subscriptState.stop = true;
  5948. return base;
  5949. }
  5950. this.next();
  5951. const node = this.startNodeAt(startPos, startLoc);
  5952. node.callee = base;
  5953. node.typeArguments = this.flowParseTypeParameterInstantiation();
  5954. this.expect(10);
  5955. node.arguments = this.parseCallExpressionArguments(11, false);
  5956. node.optional = true;
  5957. return this.finishCallExpression(node, true);
  5958. } else if (!noCalls && this.shouldParseTypes() && this.match(43)) {
  5959. const node = this.startNodeAt(startPos, startLoc);
  5960. node.callee = base;
  5961. const result = this.tryParse(() => {
  5962. node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew();
  5963. this.expect(10);
  5964. node.arguments = this.parseCallExpressionArguments(11, false);
  5965. if (subscriptState.optionalChainMember) node.optional = false;
  5966. return this.finishCallExpression(node, subscriptState.optionalChainMember);
  5967. });
  5968. if (result.node) {
  5969. if (result.error) this.state = result.failState;
  5970. return result.node;
  5971. }
  5972. }
  5973. return super.parseSubscript(base, startPos, startLoc, noCalls, subscriptState);
  5974. }
  5975. parseNewArguments(node) {
  5976. let targs = null;
  5977. if (this.shouldParseTypes() && this.match(43)) {
  5978. targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node;
  5979. }
  5980. node.typeArguments = targs;
  5981. super.parseNewArguments(node);
  5982. }
  5983. parseAsyncArrowWithTypeParameters(startPos, startLoc) {
  5984. const node = this.startNodeAt(startPos, startLoc);
  5985. this.parseFunctionParams(node);
  5986. if (!this.parseArrow(node)) return;
  5987. return this.parseArrowExpression(node, undefined, true);
  5988. }
  5989. readToken_mult_modulo(code) {
  5990. const next = this.input.charCodeAt(this.state.pos + 1);
  5991. if (code === 42 && next === 47 && this.state.hasFlowComment) {
  5992. this.state.hasFlowComment = false;
  5993. this.state.pos += 2;
  5994. this.nextToken();
  5995. return;
  5996. }
  5997. super.readToken_mult_modulo(code);
  5998. }
  5999. readToken_pipe_amp(code) {
  6000. const next = this.input.charCodeAt(this.state.pos + 1);
  6001. if (code === 124 && next === 125) {
  6002. this.finishOp(9, 2);
  6003. return;
  6004. }
  6005. super.readToken_pipe_amp(code);
  6006. }
  6007. parseTopLevel(file, program) {
  6008. const fileNode = super.parseTopLevel(file, program);
  6009. if (this.state.hasFlowComment) {
  6010. this.raise(this.state.pos, FlowErrors.UnterminatedFlowComment);
  6011. }
  6012. return fileNode;
  6013. }
  6014. skipBlockComment() {
  6015. if (this.hasPlugin("flowComments") && this.skipFlowComment()) {
  6016. if (this.state.hasFlowComment) {
  6017. this.unexpected(null, FlowErrors.NestedFlowComment);
  6018. }
  6019. this.hasFlowCommentCompletion();
  6020. this.state.pos += this.skipFlowComment();
  6021. this.state.hasFlowComment = true;
  6022. return;
  6023. }
  6024. if (this.state.hasFlowComment) {
  6025. const end = this.input.indexOf("*-/", this.state.pos += 2);
  6026. if (end === -1) {
  6027. throw this.raise(this.state.pos - 2, ErrorMessages.UnterminatedComment);
  6028. }
  6029. this.state.pos = end + 3;
  6030. return;
  6031. }
  6032. return super.skipBlockComment();
  6033. }
  6034. skipFlowComment() {
  6035. const {
  6036. pos
  6037. } = this.state;
  6038. let shiftToFirstNonWhiteSpace = 2;
  6039. while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) {
  6040. shiftToFirstNonWhiteSpace++;
  6041. }
  6042. const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);
  6043. const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);
  6044. if (ch2 === 58 && ch3 === 58) {
  6045. return shiftToFirstNonWhiteSpace + 2;
  6046. }
  6047. if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") {
  6048. return shiftToFirstNonWhiteSpace + 12;
  6049. }
  6050. if (ch2 === 58 && ch3 !== 58) {
  6051. return shiftToFirstNonWhiteSpace;
  6052. }
  6053. return false;
  6054. }
  6055. hasFlowCommentCompletion() {
  6056. const end = this.input.indexOf("*/", this.state.pos);
  6057. if (end === -1) {
  6058. throw this.raise(this.state.pos, ErrorMessages.UnterminatedComment);
  6059. }
  6060. }
  6061. flowEnumErrorBooleanMemberNotInitialized(pos, {
  6062. enumName,
  6063. memberName
  6064. }) {
  6065. this.raise(pos, FlowErrors.EnumBooleanMemberNotInitialized, memberName, enumName);
  6066. }
  6067. flowEnumErrorInvalidMemberName(pos, {
  6068. enumName,
  6069. memberName
  6070. }) {
  6071. const suggestion = memberName[0].toUpperCase() + memberName.slice(1);
  6072. this.raise(pos, FlowErrors.EnumInvalidMemberName, memberName, suggestion, enumName);
  6073. }
  6074. flowEnumErrorDuplicateMemberName(pos, {
  6075. enumName,
  6076. memberName
  6077. }) {
  6078. this.raise(pos, FlowErrors.EnumDuplicateMemberName, memberName, enumName);
  6079. }
  6080. flowEnumErrorInconsistentMemberValues(pos, {
  6081. enumName
  6082. }) {
  6083. this.raise(pos, FlowErrors.EnumInconsistentMemberValues, enumName);
  6084. }
  6085. flowEnumErrorInvalidExplicitType(pos, {
  6086. enumName,
  6087. suppliedType
  6088. }) {
  6089. return this.raise(pos, suppliedType === null ? FlowErrors.EnumInvalidExplicitTypeUnknownSupplied : FlowErrors.EnumInvalidExplicitType, enumName, suppliedType);
  6090. }
  6091. flowEnumErrorInvalidMemberInitializer(pos, {
  6092. enumName,
  6093. explicitType,
  6094. memberName
  6095. }) {
  6096. let message = null;
  6097. switch (explicitType) {
  6098. case "boolean":
  6099. case "number":
  6100. case "string":
  6101. message = FlowErrors.EnumInvalidMemberInitializerPrimaryType;
  6102. break;
  6103. case "symbol":
  6104. message = FlowErrors.EnumInvalidMemberInitializerSymbolType;
  6105. break;
  6106. default:
  6107. message = FlowErrors.EnumInvalidMemberInitializerUnknownType;
  6108. }
  6109. return this.raise(pos, message, enumName, memberName, explicitType);
  6110. }
  6111. flowEnumErrorNumberMemberNotInitialized(pos, {
  6112. enumName,
  6113. memberName
  6114. }) {
  6115. this.raise(pos, FlowErrors.EnumNumberMemberNotInitialized, enumName, memberName);
  6116. }
  6117. flowEnumErrorStringMemberInconsistentlyInitailized(pos, {
  6118. enumName
  6119. }) {
  6120. this.raise(pos, FlowErrors.EnumStringMemberInconsistentlyInitailized, enumName);
  6121. }
  6122. flowEnumMemberInit() {
  6123. const startPos = this.state.start;
  6124. const endOfInit = () => this.match(12) || this.match(8);
  6125. switch (this.state.type) {
  6126. case 124:
  6127. {
  6128. const literal = this.parseNumericLiteral(this.state.value);
  6129. if (endOfInit()) {
  6130. return {
  6131. type: "number",
  6132. pos: literal.start,
  6133. value: literal
  6134. };
  6135. }
  6136. return {
  6137. type: "invalid",
  6138. pos: startPos
  6139. };
  6140. }
  6141. case 123:
  6142. {
  6143. const literal = this.parseStringLiteral(this.state.value);
  6144. if (endOfInit()) {
  6145. return {
  6146. type: "string",
  6147. pos: literal.start,
  6148. value: literal
  6149. };
  6150. }
  6151. return {
  6152. type: "invalid",
  6153. pos: startPos
  6154. };
  6155. }
  6156. case 79:
  6157. case 80:
  6158. {
  6159. const literal = this.parseBooleanLiteral(this.match(79));
  6160. if (endOfInit()) {
  6161. return {
  6162. type: "boolean",
  6163. pos: literal.start,
  6164. value: literal
  6165. };
  6166. }
  6167. return {
  6168. type: "invalid",
  6169. pos: startPos
  6170. };
  6171. }
  6172. default:
  6173. return {
  6174. type: "invalid",
  6175. pos: startPos
  6176. };
  6177. }
  6178. }
  6179. flowEnumMemberRaw() {
  6180. const pos = this.state.start;
  6181. const id = this.parseIdentifier(true);
  6182. const init = this.eat(27) ? this.flowEnumMemberInit() : {
  6183. type: "none",
  6184. pos
  6185. };
  6186. return {
  6187. id,
  6188. init
  6189. };
  6190. }
  6191. flowEnumCheckExplicitTypeMismatch(pos, context, expectedType) {
  6192. const {
  6193. explicitType
  6194. } = context;
  6195. if (explicitType === null) {
  6196. return;
  6197. }
  6198. if (explicitType !== expectedType) {
  6199. this.flowEnumErrorInvalidMemberInitializer(pos, context);
  6200. }
  6201. }
  6202. flowEnumMembers({
  6203. enumName,
  6204. explicitType
  6205. }) {
  6206. const seenNames = new Set();
  6207. const members = {
  6208. booleanMembers: [],
  6209. numberMembers: [],
  6210. stringMembers: [],
  6211. defaultedMembers: []
  6212. };
  6213. let hasUnknownMembers = false;
  6214. while (!this.match(8)) {
  6215. if (this.eat(21)) {
  6216. hasUnknownMembers = true;
  6217. break;
  6218. }
  6219. const memberNode = this.startNode();
  6220. const {
  6221. id,
  6222. init
  6223. } = this.flowEnumMemberRaw();
  6224. const memberName = id.name;
  6225. if (memberName === "") {
  6226. continue;
  6227. }
  6228. if (/^[a-z]/.test(memberName)) {
  6229. this.flowEnumErrorInvalidMemberName(id.start, {
  6230. enumName,
  6231. memberName
  6232. });
  6233. }
  6234. if (seenNames.has(memberName)) {
  6235. this.flowEnumErrorDuplicateMemberName(id.start, {
  6236. enumName,
  6237. memberName
  6238. });
  6239. }
  6240. seenNames.add(memberName);
  6241. const context = {
  6242. enumName,
  6243. explicitType,
  6244. memberName
  6245. };
  6246. memberNode.id = id;
  6247. switch (init.type) {
  6248. case "boolean":
  6249. {
  6250. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "boolean");
  6251. memberNode.init = init.value;
  6252. members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember"));
  6253. break;
  6254. }
  6255. case "number":
  6256. {
  6257. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "number");
  6258. memberNode.init = init.value;
  6259. members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember"));
  6260. break;
  6261. }
  6262. case "string":
  6263. {
  6264. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "string");
  6265. memberNode.init = init.value;
  6266. members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember"));
  6267. break;
  6268. }
  6269. case "invalid":
  6270. {
  6271. throw this.flowEnumErrorInvalidMemberInitializer(init.pos, context);
  6272. }
  6273. case "none":
  6274. {
  6275. switch (explicitType) {
  6276. case "boolean":
  6277. this.flowEnumErrorBooleanMemberNotInitialized(init.pos, context);
  6278. break;
  6279. case "number":
  6280. this.flowEnumErrorNumberMemberNotInitialized(init.pos, context);
  6281. break;
  6282. default:
  6283. members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember"));
  6284. }
  6285. }
  6286. }
  6287. if (!this.match(8)) {
  6288. this.expect(12);
  6289. }
  6290. }
  6291. return {
  6292. members,
  6293. hasUnknownMembers
  6294. };
  6295. }
  6296. flowEnumStringMembers(initializedMembers, defaultedMembers, {
  6297. enumName
  6298. }) {
  6299. if (initializedMembers.length === 0) {
  6300. return defaultedMembers;
  6301. } else if (defaultedMembers.length === 0) {
  6302. return initializedMembers;
  6303. } else if (defaultedMembers.length > initializedMembers.length) {
  6304. for (const member of initializedMembers) {
  6305. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  6306. enumName
  6307. });
  6308. }
  6309. return defaultedMembers;
  6310. } else {
  6311. for (const member of defaultedMembers) {
  6312. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  6313. enumName
  6314. });
  6315. }
  6316. return initializedMembers;
  6317. }
  6318. }
  6319. flowEnumParseExplicitType({
  6320. enumName
  6321. }) {
  6322. if (this.eatContextual(95)) {
  6323. if (!tokenIsIdentifier(this.state.type)) {
  6324. throw this.flowEnumErrorInvalidExplicitType(this.state.start, {
  6325. enumName,
  6326. suppliedType: null
  6327. });
  6328. }
  6329. const {
  6330. value
  6331. } = this.state;
  6332. this.next();
  6333. if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") {
  6334. this.flowEnumErrorInvalidExplicitType(this.state.start, {
  6335. enumName,
  6336. suppliedType: value
  6337. });
  6338. }
  6339. return value;
  6340. }
  6341. return null;
  6342. }
  6343. flowEnumBody(node, {
  6344. enumName,
  6345. nameLoc
  6346. }) {
  6347. const explicitType = this.flowEnumParseExplicitType({
  6348. enumName
  6349. });
  6350. this.expect(5);
  6351. const {
  6352. members,
  6353. hasUnknownMembers
  6354. } = this.flowEnumMembers({
  6355. enumName,
  6356. explicitType
  6357. });
  6358. node.hasUnknownMembers = hasUnknownMembers;
  6359. switch (explicitType) {
  6360. case "boolean":
  6361. node.explicitType = true;
  6362. node.members = members.booleanMembers;
  6363. this.expect(8);
  6364. return this.finishNode(node, "EnumBooleanBody");
  6365. case "number":
  6366. node.explicitType = true;
  6367. node.members = members.numberMembers;
  6368. this.expect(8);
  6369. return this.finishNode(node, "EnumNumberBody");
  6370. case "string":
  6371. node.explicitType = true;
  6372. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  6373. enumName
  6374. });
  6375. this.expect(8);
  6376. return this.finishNode(node, "EnumStringBody");
  6377. case "symbol":
  6378. node.members = members.defaultedMembers;
  6379. this.expect(8);
  6380. return this.finishNode(node, "EnumSymbolBody");
  6381. default:
  6382. {
  6383. const empty = () => {
  6384. node.members = [];
  6385. this.expect(8);
  6386. return this.finishNode(node, "EnumStringBody");
  6387. };
  6388. node.explicitType = false;
  6389. const boolsLen = members.booleanMembers.length;
  6390. const numsLen = members.numberMembers.length;
  6391. const strsLen = members.stringMembers.length;
  6392. const defaultedLen = members.defaultedMembers.length;
  6393. if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {
  6394. return empty();
  6395. } else if (!boolsLen && !numsLen) {
  6396. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  6397. enumName
  6398. });
  6399. this.expect(8);
  6400. return this.finishNode(node, "EnumStringBody");
  6401. } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {
  6402. for (const member of members.defaultedMembers) {
  6403. this.flowEnumErrorBooleanMemberNotInitialized(member.start, {
  6404. enumName,
  6405. memberName: member.id.name
  6406. });
  6407. }
  6408. node.members = members.booleanMembers;
  6409. this.expect(8);
  6410. return this.finishNode(node, "EnumBooleanBody");
  6411. } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {
  6412. for (const member of members.defaultedMembers) {
  6413. this.flowEnumErrorNumberMemberNotInitialized(member.start, {
  6414. enumName,
  6415. memberName: member.id.name
  6416. });
  6417. }
  6418. node.members = members.numberMembers;
  6419. this.expect(8);
  6420. return this.finishNode(node, "EnumNumberBody");
  6421. } else {
  6422. this.flowEnumErrorInconsistentMemberValues(nameLoc, {
  6423. enumName
  6424. });
  6425. return empty();
  6426. }
  6427. }
  6428. }
  6429. }
  6430. flowParseEnumDeclaration(node) {
  6431. const id = this.parseIdentifier();
  6432. node.id = id;
  6433. node.body = this.flowEnumBody(this.startNode(), {
  6434. enumName: id.name,
  6435. nameLoc: id.start
  6436. });
  6437. return this.finishNode(node, "EnumDeclaration");
  6438. }
  6439. isLookaheadToken_lt() {
  6440. const next = this.nextTokenStart();
  6441. if (this.input.charCodeAt(next) === 60) {
  6442. const afterNext = this.input.charCodeAt(next + 1);
  6443. return afterNext !== 60 && afterNext !== 61;
  6444. }
  6445. return false;
  6446. }
  6447. maybeUnwrapTypeCastExpression(node) {
  6448. return node.type === "TypeCastExpression" ? node.expression : node;
  6449. }
  6450. });
  6451. const entities = {
  6452. quot: "\u0022",
  6453. amp: "&",
  6454. apos: "\u0027",
  6455. lt: "<",
  6456. gt: ">",
  6457. nbsp: "\u00A0",
  6458. iexcl: "\u00A1",
  6459. cent: "\u00A2",
  6460. pound: "\u00A3",
  6461. curren: "\u00A4",
  6462. yen: "\u00A5",
  6463. brvbar: "\u00A6",
  6464. sect: "\u00A7",
  6465. uml: "\u00A8",
  6466. copy: "\u00A9",
  6467. ordf: "\u00AA",
  6468. laquo: "\u00AB",
  6469. not: "\u00AC",
  6470. shy: "\u00AD",
  6471. reg: "\u00AE",
  6472. macr: "\u00AF",
  6473. deg: "\u00B0",
  6474. plusmn: "\u00B1",
  6475. sup2: "\u00B2",
  6476. sup3: "\u00B3",
  6477. acute: "\u00B4",
  6478. micro: "\u00B5",
  6479. para: "\u00B6",
  6480. middot: "\u00B7",
  6481. cedil: "\u00B8",
  6482. sup1: "\u00B9",
  6483. ordm: "\u00BA",
  6484. raquo: "\u00BB",
  6485. frac14: "\u00BC",
  6486. frac12: "\u00BD",
  6487. frac34: "\u00BE",
  6488. iquest: "\u00BF",
  6489. Agrave: "\u00C0",
  6490. Aacute: "\u00C1",
  6491. Acirc: "\u00C2",
  6492. Atilde: "\u00C3",
  6493. Auml: "\u00C4",
  6494. Aring: "\u00C5",
  6495. AElig: "\u00C6",
  6496. Ccedil: "\u00C7",
  6497. Egrave: "\u00C8",
  6498. Eacute: "\u00C9",
  6499. Ecirc: "\u00CA",
  6500. Euml: "\u00CB",
  6501. Igrave: "\u00CC",
  6502. Iacute: "\u00CD",
  6503. Icirc: "\u00CE",
  6504. Iuml: "\u00CF",
  6505. ETH: "\u00D0",
  6506. Ntilde: "\u00D1",
  6507. Ograve: "\u00D2",
  6508. Oacute: "\u00D3",
  6509. Ocirc: "\u00D4",
  6510. Otilde: "\u00D5",
  6511. Ouml: "\u00D6",
  6512. times: "\u00D7",
  6513. Oslash: "\u00D8",
  6514. Ugrave: "\u00D9",
  6515. Uacute: "\u00DA",
  6516. Ucirc: "\u00DB",
  6517. Uuml: "\u00DC",
  6518. Yacute: "\u00DD",
  6519. THORN: "\u00DE",
  6520. szlig: "\u00DF",
  6521. agrave: "\u00E0",
  6522. aacute: "\u00E1",
  6523. acirc: "\u00E2",
  6524. atilde: "\u00E3",
  6525. auml: "\u00E4",
  6526. aring: "\u00E5",
  6527. aelig: "\u00E6",
  6528. ccedil: "\u00E7",
  6529. egrave: "\u00E8",
  6530. eacute: "\u00E9",
  6531. ecirc: "\u00EA",
  6532. euml: "\u00EB",
  6533. igrave: "\u00EC",
  6534. iacute: "\u00ED",
  6535. icirc: "\u00EE",
  6536. iuml: "\u00EF",
  6537. eth: "\u00F0",
  6538. ntilde: "\u00F1",
  6539. ograve: "\u00F2",
  6540. oacute: "\u00F3",
  6541. ocirc: "\u00F4",
  6542. otilde: "\u00F5",
  6543. ouml: "\u00F6",
  6544. divide: "\u00F7",
  6545. oslash: "\u00F8",
  6546. ugrave: "\u00F9",
  6547. uacute: "\u00FA",
  6548. ucirc: "\u00FB",
  6549. uuml: "\u00FC",
  6550. yacute: "\u00FD",
  6551. thorn: "\u00FE",
  6552. yuml: "\u00FF",
  6553. OElig: "\u0152",
  6554. oelig: "\u0153",
  6555. Scaron: "\u0160",
  6556. scaron: "\u0161",
  6557. Yuml: "\u0178",
  6558. fnof: "\u0192",
  6559. circ: "\u02C6",
  6560. tilde: "\u02DC",
  6561. Alpha: "\u0391",
  6562. Beta: "\u0392",
  6563. Gamma: "\u0393",
  6564. Delta: "\u0394",
  6565. Epsilon: "\u0395",
  6566. Zeta: "\u0396",
  6567. Eta: "\u0397",
  6568. Theta: "\u0398",
  6569. Iota: "\u0399",
  6570. Kappa: "\u039A",
  6571. Lambda: "\u039B",
  6572. Mu: "\u039C",
  6573. Nu: "\u039D",
  6574. Xi: "\u039E",
  6575. Omicron: "\u039F",
  6576. Pi: "\u03A0",
  6577. Rho: "\u03A1",
  6578. Sigma: "\u03A3",
  6579. Tau: "\u03A4",
  6580. Upsilon: "\u03A5",
  6581. Phi: "\u03A6",
  6582. Chi: "\u03A7",
  6583. Psi: "\u03A8",
  6584. Omega: "\u03A9",
  6585. alpha: "\u03B1",
  6586. beta: "\u03B2",
  6587. gamma: "\u03B3",
  6588. delta: "\u03B4",
  6589. epsilon: "\u03B5",
  6590. zeta: "\u03B6",
  6591. eta: "\u03B7",
  6592. theta: "\u03B8",
  6593. iota: "\u03B9",
  6594. kappa: "\u03BA",
  6595. lambda: "\u03BB",
  6596. mu: "\u03BC",
  6597. nu: "\u03BD",
  6598. xi: "\u03BE",
  6599. omicron: "\u03BF",
  6600. pi: "\u03C0",
  6601. rho: "\u03C1",
  6602. sigmaf: "\u03C2",
  6603. sigma: "\u03C3",
  6604. tau: "\u03C4",
  6605. upsilon: "\u03C5",
  6606. phi: "\u03C6",
  6607. chi: "\u03C7",
  6608. psi: "\u03C8",
  6609. omega: "\u03C9",
  6610. thetasym: "\u03D1",
  6611. upsih: "\u03D2",
  6612. piv: "\u03D6",
  6613. ensp: "\u2002",
  6614. emsp: "\u2003",
  6615. thinsp: "\u2009",
  6616. zwnj: "\u200C",
  6617. zwj: "\u200D",
  6618. lrm: "\u200E",
  6619. rlm: "\u200F",
  6620. ndash: "\u2013",
  6621. mdash: "\u2014",
  6622. lsquo: "\u2018",
  6623. rsquo: "\u2019",
  6624. sbquo: "\u201A",
  6625. ldquo: "\u201C",
  6626. rdquo: "\u201D",
  6627. bdquo: "\u201E",
  6628. dagger: "\u2020",
  6629. Dagger: "\u2021",
  6630. bull: "\u2022",
  6631. hellip: "\u2026",
  6632. permil: "\u2030",
  6633. prime: "\u2032",
  6634. Prime: "\u2033",
  6635. lsaquo: "\u2039",
  6636. rsaquo: "\u203A",
  6637. oline: "\u203E",
  6638. frasl: "\u2044",
  6639. euro: "\u20AC",
  6640. image: "\u2111",
  6641. weierp: "\u2118",
  6642. real: "\u211C",
  6643. trade: "\u2122",
  6644. alefsym: "\u2135",
  6645. larr: "\u2190",
  6646. uarr: "\u2191",
  6647. rarr: "\u2192",
  6648. darr: "\u2193",
  6649. harr: "\u2194",
  6650. crarr: "\u21B5",
  6651. lArr: "\u21D0",
  6652. uArr: "\u21D1",
  6653. rArr: "\u21D2",
  6654. dArr: "\u21D3",
  6655. hArr: "\u21D4",
  6656. forall: "\u2200",
  6657. part: "\u2202",
  6658. exist: "\u2203",
  6659. empty: "\u2205",
  6660. nabla: "\u2207",
  6661. isin: "\u2208",
  6662. notin: "\u2209",
  6663. ni: "\u220B",
  6664. prod: "\u220F",
  6665. sum: "\u2211",
  6666. minus: "\u2212",
  6667. lowast: "\u2217",
  6668. radic: "\u221A",
  6669. prop: "\u221D",
  6670. infin: "\u221E",
  6671. ang: "\u2220",
  6672. and: "\u2227",
  6673. or: "\u2228",
  6674. cap: "\u2229",
  6675. cup: "\u222A",
  6676. int: "\u222B",
  6677. there4: "\u2234",
  6678. sim: "\u223C",
  6679. cong: "\u2245",
  6680. asymp: "\u2248",
  6681. ne: "\u2260",
  6682. equiv: "\u2261",
  6683. le: "\u2264",
  6684. ge: "\u2265",
  6685. sub: "\u2282",
  6686. sup: "\u2283",
  6687. nsub: "\u2284",
  6688. sube: "\u2286",
  6689. supe: "\u2287",
  6690. oplus: "\u2295",
  6691. otimes: "\u2297",
  6692. perp: "\u22A5",
  6693. sdot: "\u22C5",
  6694. lceil: "\u2308",
  6695. rceil: "\u2309",
  6696. lfloor: "\u230A",
  6697. rfloor: "\u230B",
  6698. lang: "\u2329",
  6699. rang: "\u232A",
  6700. loz: "\u25CA",
  6701. spades: "\u2660",
  6702. clubs: "\u2663",
  6703. hearts: "\u2665",
  6704. diams: "\u2666"
  6705. };
  6706. const HEX_NUMBER = /^[\da-fA-F]+$/;
  6707. const DECIMAL_NUMBER = /^\d+$/;
  6708. const JsxErrors = makeErrorTemplates({
  6709. AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression.",
  6710. MissingClosingTagElement: "Expected corresponding JSX closing tag for <%0>.",
  6711. MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>.",
  6712. UnexpectedSequenceExpression: "Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?",
  6713. UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text.",
  6714. UnterminatedJsxContent: "Unterminated JSX contents.",
  6715. UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"
  6716. }, ErrorCodes.SyntaxError, "jsx");
  6717. types.j_oTag = new TokContext("<tag");
  6718. types.j_cTag = new TokContext("</tag");
  6719. types.j_expr = new TokContext("<tag>...</tag>", true);
  6720. function isFragment(object) {
  6721. return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false;
  6722. }
  6723. function getQualifiedJSXName(object) {
  6724. if (object.type === "JSXIdentifier") {
  6725. return object.name;
  6726. }
  6727. if (object.type === "JSXNamespacedName") {
  6728. return object.namespace.name + ":" + object.name.name;
  6729. }
  6730. if (object.type === "JSXMemberExpression") {
  6731. return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property);
  6732. }
  6733. throw new Error("Node had unexpected type: " + object.type);
  6734. }
  6735. var jsx = (superClass => class extends superClass {
  6736. jsxReadToken() {
  6737. let out = "";
  6738. let chunkStart = this.state.pos;
  6739. for (;;) {
  6740. if (this.state.pos >= this.length) {
  6741. throw this.raise(this.state.start, JsxErrors.UnterminatedJsxContent);
  6742. }
  6743. const ch = this.input.charCodeAt(this.state.pos);
  6744. switch (ch) {
  6745. case 60:
  6746. case 123:
  6747. if (this.state.pos === this.state.start) {
  6748. if (ch === 60 && this.state.canStartJSXElement) {
  6749. ++this.state.pos;
  6750. return this.finishToken(132);
  6751. }
  6752. return super.getTokenFromCode(ch);
  6753. }
  6754. out += this.input.slice(chunkStart, this.state.pos);
  6755. return this.finishToken(131, out);
  6756. case 38:
  6757. out += this.input.slice(chunkStart, this.state.pos);
  6758. out += this.jsxReadEntity();
  6759. chunkStart = this.state.pos;
  6760. break;
  6761. case 62:
  6762. case 125:
  6763. default:
  6764. if (isNewLine(ch)) {
  6765. out += this.input.slice(chunkStart, this.state.pos);
  6766. out += this.jsxReadNewLine(true);
  6767. chunkStart = this.state.pos;
  6768. } else {
  6769. ++this.state.pos;
  6770. }
  6771. }
  6772. }
  6773. }
  6774. jsxReadNewLine(normalizeCRLF) {
  6775. const ch = this.input.charCodeAt(this.state.pos);
  6776. let out;
  6777. ++this.state.pos;
  6778. if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) {
  6779. ++this.state.pos;
  6780. out = normalizeCRLF ? "\n" : "\r\n";
  6781. } else {
  6782. out = String.fromCharCode(ch);
  6783. }
  6784. ++this.state.curLine;
  6785. this.state.lineStart = this.state.pos;
  6786. return out;
  6787. }
  6788. jsxReadString(quote) {
  6789. let out = "";
  6790. let chunkStart = ++this.state.pos;
  6791. for (;;) {
  6792. if (this.state.pos >= this.length) {
  6793. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  6794. }
  6795. const ch = this.input.charCodeAt(this.state.pos);
  6796. if (ch === quote) break;
  6797. if (ch === 38) {
  6798. out += this.input.slice(chunkStart, this.state.pos);
  6799. out += this.jsxReadEntity();
  6800. chunkStart = this.state.pos;
  6801. } else if (isNewLine(ch)) {
  6802. out += this.input.slice(chunkStart, this.state.pos);
  6803. out += this.jsxReadNewLine(false);
  6804. chunkStart = this.state.pos;
  6805. } else {
  6806. ++this.state.pos;
  6807. }
  6808. }
  6809. out += this.input.slice(chunkStart, this.state.pos++);
  6810. return this.finishToken(123, out);
  6811. }
  6812. jsxReadEntity() {
  6813. let str = "";
  6814. let count = 0;
  6815. let entity;
  6816. let ch = this.input[this.state.pos];
  6817. const startPos = ++this.state.pos;
  6818. while (this.state.pos < this.length && count++ < 10) {
  6819. ch = this.input[this.state.pos++];
  6820. if (ch === ";") {
  6821. if (str[0] === "#") {
  6822. if (str[1] === "x") {
  6823. str = str.substr(2);
  6824. if (HEX_NUMBER.test(str)) {
  6825. entity = String.fromCodePoint(parseInt(str, 16));
  6826. }
  6827. } else {
  6828. str = str.substr(1);
  6829. if (DECIMAL_NUMBER.test(str)) {
  6830. entity = String.fromCodePoint(parseInt(str, 10));
  6831. }
  6832. }
  6833. } else {
  6834. entity = entities[str];
  6835. }
  6836. break;
  6837. }
  6838. str += ch;
  6839. }
  6840. if (!entity) {
  6841. this.state.pos = startPos;
  6842. return "&";
  6843. }
  6844. return entity;
  6845. }
  6846. jsxReadWord() {
  6847. let ch;
  6848. const start = this.state.pos;
  6849. do {
  6850. ch = this.input.charCodeAt(++this.state.pos);
  6851. } while (isIdentifierChar(ch) || ch === 45);
  6852. return this.finishToken(130, this.input.slice(start, this.state.pos));
  6853. }
  6854. jsxParseIdentifier() {
  6855. const node = this.startNode();
  6856. if (this.match(130)) {
  6857. node.name = this.state.value;
  6858. } else if (tokenIsKeyword(this.state.type)) {
  6859. node.name = tokenLabelName(this.state.type);
  6860. } else {
  6861. this.unexpected();
  6862. }
  6863. this.next();
  6864. return this.finishNode(node, "JSXIdentifier");
  6865. }
  6866. jsxParseNamespacedName() {
  6867. const startPos = this.state.start;
  6868. const startLoc = this.state.startLoc;
  6869. const name = this.jsxParseIdentifier();
  6870. if (!this.eat(14)) return name;
  6871. const node = this.startNodeAt(startPos, startLoc);
  6872. node.namespace = name;
  6873. node.name = this.jsxParseIdentifier();
  6874. return this.finishNode(node, "JSXNamespacedName");
  6875. }
  6876. jsxParseElementName() {
  6877. const startPos = this.state.start;
  6878. const startLoc = this.state.startLoc;
  6879. let node = this.jsxParseNamespacedName();
  6880. if (node.type === "JSXNamespacedName") {
  6881. return node;
  6882. }
  6883. while (this.eat(16)) {
  6884. const newNode = this.startNodeAt(startPos, startLoc);
  6885. newNode.object = node;
  6886. newNode.property = this.jsxParseIdentifier();
  6887. node = this.finishNode(newNode, "JSXMemberExpression");
  6888. }
  6889. return node;
  6890. }
  6891. jsxParseAttributeValue() {
  6892. let node;
  6893. switch (this.state.type) {
  6894. case 5:
  6895. node = this.startNode();
  6896. this.next();
  6897. node = this.jsxParseExpressionContainer(node);
  6898. if (node.expression.type === "JSXEmptyExpression") {
  6899. this.raise(node.start, JsxErrors.AttributeIsEmpty);
  6900. }
  6901. return node;
  6902. case 132:
  6903. case 123:
  6904. return this.parseExprAtom();
  6905. default:
  6906. throw this.raise(this.state.start, JsxErrors.UnsupportedJsxValue);
  6907. }
  6908. }
  6909. jsxParseEmptyExpression() {
  6910. const node = this.startNodeAt(this.state.lastTokEnd, this.state.lastTokEndLoc);
  6911. return this.finishNodeAt(node, "JSXEmptyExpression", this.state.start, this.state.startLoc);
  6912. }
  6913. jsxParseSpreadChild(node) {
  6914. this.next();
  6915. node.expression = this.parseExpression();
  6916. this.expect(8);
  6917. return this.finishNode(node, "JSXSpreadChild");
  6918. }
  6919. jsxParseExpressionContainer(node) {
  6920. if (this.match(8)) {
  6921. node.expression = this.jsxParseEmptyExpression();
  6922. } else {
  6923. const expression = this.parseExpression();
  6924. node.expression = expression;
  6925. }
  6926. this.expect(8);
  6927. return this.finishNode(node, "JSXExpressionContainer");
  6928. }
  6929. jsxParseAttribute() {
  6930. const node = this.startNode();
  6931. if (this.eat(5)) {
  6932. this.expect(21);
  6933. node.argument = this.parseMaybeAssignAllowIn();
  6934. this.expect(8);
  6935. return this.finishNode(node, "JSXSpreadAttribute");
  6936. }
  6937. node.name = this.jsxParseNamespacedName();
  6938. node.value = this.eat(27) ? this.jsxParseAttributeValue() : null;
  6939. return this.finishNode(node, "JSXAttribute");
  6940. }
  6941. jsxParseOpeningElementAt(startPos, startLoc) {
  6942. const node = this.startNodeAt(startPos, startLoc);
  6943. if (this.match(133)) {
  6944. this.expect(133);
  6945. return this.finishNode(node, "JSXOpeningFragment");
  6946. }
  6947. node.name = this.jsxParseElementName();
  6948. return this.jsxParseOpeningElementAfterName(node);
  6949. }
  6950. jsxParseOpeningElementAfterName(node) {
  6951. const attributes = [];
  6952. while (!this.match(50) && !this.match(133)) {
  6953. attributes.push(this.jsxParseAttribute());
  6954. }
  6955. node.attributes = attributes;
  6956. node.selfClosing = this.eat(50);
  6957. this.expect(133);
  6958. return this.finishNode(node, "JSXOpeningElement");
  6959. }
  6960. jsxParseClosingElementAt(startPos, startLoc) {
  6961. const node = this.startNodeAt(startPos, startLoc);
  6962. if (this.match(133)) {
  6963. this.expect(133);
  6964. return this.finishNode(node, "JSXClosingFragment");
  6965. }
  6966. node.name = this.jsxParseElementName();
  6967. this.expect(133);
  6968. return this.finishNode(node, "JSXClosingElement");
  6969. }
  6970. jsxParseElementAt(startPos, startLoc) {
  6971. const node = this.startNodeAt(startPos, startLoc);
  6972. const children = [];
  6973. const openingElement = this.jsxParseOpeningElementAt(startPos, startLoc);
  6974. let closingElement = null;
  6975. if (!openingElement.selfClosing) {
  6976. contents: for (;;) {
  6977. switch (this.state.type) {
  6978. case 132:
  6979. startPos = this.state.start;
  6980. startLoc = this.state.startLoc;
  6981. this.next();
  6982. if (this.eat(50)) {
  6983. closingElement = this.jsxParseClosingElementAt(startPos, startLoc);
  6984. break contents;
  6985. }
  6986. children.push(this.jsxParseElementAt(startPos, startLoc));
  6987. break;
  6988. case 131:
  6989. children.push(this.parseExprAtom());
  6990. break;
  6991. case 5:
  6992. {
  6993. const node = this.startNode();
  6994. this.next();
  6995. if (this.match(21)) {
  6996. children.push(this.jsxParseSpreadChild(node));
  6997. } else {
  6998. children.push(this.jsxParseExpressionContainer(node));
  6999. }
  7000. break;
  7001. }
  7002. default:
  7003. throw this.unexpected();
  7004. }
  7005. }
  7006. if (isFragment(openingElement) && !isFragment(closingElement)) {
  7007. this.raise(closingElement.start, JsxErrors.MissingClosingTagFragment);
  7008. } else if (!isFragment(openingElement) && isFragment(closingElement)) {
  7009. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  7010. } else if (!isFragment(openingElement) && !isFragment(closingElement)) {
  7011. if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
  7012. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  7013. }
  7014. }
  7015. }
  7016. if (isFragment(openingElement)) {
  7017. node.openingFragment = openingElement;
  7018. node.closingFragment = closingElement;
  7019. } else {
  7020. node.openingElement = openingElement;
  7021. node.closingElement = closingElement;
  7022. }
  7023. node.children = children;
  7024. if (this.match(43)) {
  7025. throw this.raise(this.state.start, JsxErrors.UnwrappedAdjacentJSXElements);
  7026. }
  7027. return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement");
  7028. }
  7029. jsxParseElement() {
  7030. const startPos = this.state.start;
  7031. const startLoc = this.state.startLoc;
  7032. this.next();
  7033. return this.jsxParseElementAt(startPos, startLoc);
  7034. }
  7035. parseExprAtom(refExpressionErrors) {
  7036. if (this.match(131)) {
  7037. return this.parseLiteral(this.state.value, "JSXText");
  7038. } else if (this.match(132)) {
  7039. return this.jsxParseElement();
  7040. } else if (this.match(43) && this.input.charCodeAt(this.state.pos) !== 33) {
  7041. this.replaceToken(132);
  7042. return this.jsxParseElement();
  7043. } else {
  7044. return super.parseExprAtom(refExpressionErrors);
  7045. }
  7046. }
  7047. getTokenFromCode(code) {
  7048. const context = this.curContext();
  7049. if (context === types.j_expr) {
  7050. return this.jsxReadToken();
  7051. }
  7052. if (context === types.j_oTag || context === types.j_cTag) {
  7053. if (isIdentifierStart(code)) {
  7054. return this.jsxReadWord();
  7055. }
  7056. if (code === 62) {
  7057. ++this.state.pos;
  7058. return this.finishToken(133);
  7059. }
  7060. if ((code === 34 || code === 39) && context === types.j_oTag) {
  7061. return this.jsxReadString(code);
  7062. }
  7063. }
  7064. if (code === 60 && this.state.canStartJSXElement && this.input.charCodeAt(this.state.pos + 1) !== 33) {
  7065. ++this.state.pos;
  7066. return this.finishToken(132);
  7067. }
  7068. return super.getTokenFromCode(code);
  7069. }
  7070. updateContext(prevType) {
  7071. super.updateContext(prevType);
  7072. const {
  7073. context,
  7074. type
  7075. } = this.state;
  7076. if (type === 50 && prevType === 132) {
  7077. context.splice(-2, 2, types.j_cTag);
  7078. this.state.canStartJSXElement = false;
  7079. } else if (type === 132) {
  7080. context.push(types.j_expr, types.j_oTag);
  7081. } else if (type === 133) {
  7082. const out = context.pop();
  7083. if (out === types.j_oTag && prevType === 50 || out === types.j_cTag) {
  7084. context.pop();
  7085. this.state.canStartJSXElement = context[context.length - 1] === types.j_expr;
  7086. } else {
  7087. this.state.canStartJSXElement = true;
  7088. }
  7089. } else {
  7090. this.state.canStartJSXElement = tokenComesBeforeExpression(type);
  7091. }
  7092. }
  7093. });
  7094. class TypeScriptScope extends Scope {
  7095. constructor(...args) {
  7096. super(...args);
  7097. this.types = new Set();
  7098. this.enums = new Set();
  7099. this.constEnums = new Set();
  7100. this.classes = new Set();
  7101. this.exportOnlyBindings = new Set();
  7102. }
  7103. }
  7104. class TypeScriptScopeHandler extends ScopeHandler {
  7105. createScope(flags) {
  7106. return new TypeScriptScope(flags);
  7107. }
  7108. declareName(name, bindingType, pos) {
  7109. const scope = this.currentScope();
  7110. if (bindingType & BIND_FLAGS_TS_EXPORT_ONLY) {
  7111. this.maybeExportDefined(scope, name);
  7112. scope.exportOnlyBindings.add(name);
  7113. return;
  7114. }
  7115. super.declareName(...arguments);
  7116. if (bindingType & BIND_KIND_TYPE) {
  7117. if (!(bindingType & BIND_KIND_VALUE)) {
  7118. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  7119. this.maybeExportDefined(scope, name);
  7120. }
  7121. scope.types.add(name);
  7122. }
  7123. if (bindingType & BIND_FLAGS_TS_ENUM) scope.enums.add(name);
  7124. if (bindingType & BIND_FLAGS_TS_CONST_ENUM) scope.constEnums.add(name);
  7125. if (bindingType & BIND_FLAGS_CLASS) scope.classes.add(name);
  7126. }
  7127. isRedeclaredInScope(scope, name, bindingType) {
  7128. if (scope.enums.has(name)) {
  7129. if (bindingType & BIND_FLAGS_TS_ENUM) {
  7130. const isConst = !!(bindingType & BIND_FLAGS_TS_CONST_ENUM);
  7131. const wasConst = scope.constEnums.has(name);
  7132. return isConst !== wasConst;
  7133. }
  7134. return true;
  7135. }
  7136. if (bindingType & BIND_FLAGS_CLASS && scope.classes.has(name)) {
  7137. if (scope.lexical.has(name)) {
  7138. return !!(bindingType & BIND_KIND_VALUE);
  7139. } else {
  7140. return false;
  7141. }
  7142. }
  7143. if (bindingType & BIND_KIND_TYPE && scope.types.has(name)) {
  7144. return true;
  7145. }
  7146. return super.isRedeclaredInScope(...arguments);
  7147. }
  7148. checkLocalExport(id) {
  7149. const topLevelScope = this.scopeStack[0];
  7150. const {
  7151. name
  7152. } = id;
  7153. if (!topLevelScope.types.has(name) && !topLevelScope.exportOnlyBindings.has(name)) {
  7154. super.checkLocalExport(id);
  7155. }
  7156. }
  7157. }
  7158. function nonNull(x) {
  7159. if (x == null) {
  7160. throw new Error(`Unexpected ${x} value.`);
  7161. }
  7162. return x;
  7163. }
  7164. function assert(x) {
  7165. if (!x) {
  7166. throw new Error("Assert fail");
  7167. }
  7168. }
  7169. const TSErrors = makeErrorTemplates({
  7170. AbstractMethodHasImplementation: "Method '%0' cannot have an implementation because it is marked abstract.",
  7171. AbstractPropertyHasInitializer: "Property '%0' cannot have an initializer because it is marked abstract.",
  7172. AccesorCannotDeclareThisParameter: "'get' and 'set' accessors cannot declare 'this' parameters.",
  7173. AccesorCannotHaveTypeParameters: "An accessor cannot have type parameters.",
  7174. ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier.",
  7175. ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier.",
  7176. ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.",
  7177. DeclareAccessor: "'declare' is not allowed in %0ters.",
  7178. DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.",
  7179. DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.",
  7180. DuplicateAccessibilityModifier: "Accessibility modifier already seen.",
  7181. DuplicateModifier: "Duplicate modifier: '%0'.",
  7182. EmptyHeritageClauseType: "'%0' list cannot be empty.",
  7183. EmptyTypeArguments: "Type argument list cannot be empty.",
  7184. EmptyTypeParameters: "Type parameter list cannot be empty.",
  7185. ExpectedAmbientAfterExportDeclare: "'export declare' must be followed by an ambient declaration.",
  7186. ImportAliasHasImportType: "An import alias can not use 'import type'.",
  7187. IncompatibleModifiers: "'%0' modifier cannot be used with '%1' modifier.",
  7188. IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier.",
  7189. IndexSignatureHasAccessibility: "Index signatures cannot have an accessibility modifier ('%0').",
  7190. IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier.",
  7191. IndexSignatureHasOverride: "'override' modifier cannot appear on an index signature.",
  7192. IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier.",
  7193. InvalidModifierOnTypeMember: "'%0' modifier cannot appear on a type member.",
  7194. InvalidModifiersOrder: "'%0' modifier must precede '%1' modifier.",
  7195. InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.",
  7196. MissingInterfaceName: "'interface' declarations must be followed by an identifier.",
  7197. MixedLabeledAndUnlabeledElements: "Tuple members must all have names or all not have names.",
  7198. NonAbstractClassHasAbstractMethod: "Abstract methods can only appear within an abstract class.",
  7199. NonClassMethodPropertyHasAbstractModifer: "'abstract' modifier can only appear on a class, method, or property declaration.",
  7200. OptionalTypeBeforeRequired: "A required element cannot follow an optional element.",
  7201. OverrideNotInSubClass: "This member cannot have an 'override' modifier because its containing class does not extend another class.",
  7202. PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.",
  7203. PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.",
  7204. PrivateElementHasAccessibility: "Private elements cannot have an accessibility modifier ('%0').",
  7205. ReadonlyForMethodSignature: "'readonly' modifier can only appear on a property declaration or index signature.",
  7206. ReservedArrowTypeParam: "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma, as in `<T,>() => ...`.",
  7207. ReservedTypeAssertion: "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.",
  7208. SetAccesorCannotHaveOptionalParameter: "A 'set' accessor cannot have an optional parameter.",
  7209. SetAccesorCannotHaveRestParameter: "A 'set' accessor cannot have rest parameter.",
  7210. SetAccesorCannotHaveReturnType: "A 'set' accessor cannot have a return type annotation.",
  7211. StaticBlockCannotHaveModifier: "Static class blocks cannot have any modifier.",
  7212. TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",
  7213. TypeImportCannotSpecifyDefaultAndNamed: "A type-only import can specify a default import or named bindings, but not both.",
  7214. TypeModifierIsUsedInTypeExports: "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.",
  7215. TypeModifierIsUsedInTypeImports: "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.",
  7216. UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.",
  7217. UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.",
  7218. UnexpectedTypeAnnotation: "Did not expect a type annotation here.",
  7219. UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.",
  7220. UnsupportedImportTypeArgument: "Argument in a type import must be a string literal.",
  7221. UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.",
  7222. UnsupportedSignatureParameterKind: "Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got %0."
  7223. }, ErrorCodes.SyntaxError, "typescript");
  7224. function keywordTypeFromName(value) {
  7225. switch (value) {
  7226. case "any":
  7227. return "TSAnyKeyword";
  7228. case "boolean":
  7229. return "TSBooleanKeyword";
  7230. case "bigint":
  7231. return "TSBigIntKeyword";
  7232. case "never":
  7233. return "TSNeverKeyword";
  7234. case "number":
  7235. return "TSNumberKeyword";
  7236. case "object":
  7237. return "TSObjectKeyword";
  7238. case "string":
  7239. return "TSStringKeyword";
  7240. case "symbol":
  7241. return "TSSymbolKeyword";
  7242. case "undefined":
  7243. return "TSUndefinedKeyword";
  7244. case "unknown":
  7245. return "TSUnknownKeyword";
  7246. default:
  7247. return undefined;
  7248. }
  7249. }
  7250. function tsIsAccessModifier(modifier) {
  7251. return modifier === "private" || modifier === "public" || modifier === "protected";
  7252. }
  7253. var typescript = (superClass => class extends superClass {
  7254. getScopeHandler() {
  7255. return TypeScriptScopeHandler;
  7256. }
  7257. tsIsIdentifier() {
  7258. return tokenIsIdentifier(this.state.type);
  7259. }
  7260. tsTokenCanFollowModifier() {
  7261. return (this.match(0) || this.match(5) || this.match(49) || this.match(21) || this.match(128) || this.isLiteralPropertyName()) && !this.hasPrecedingLineBreak();
  7262. }
  7263. tsNextTokenCanFollowModifier() {
  7264. this.next();
  7265. return this.tsTokenCanFollowModifier();
  7266. }
  7267. tsParseModifier(allowedModifiers, stopOnStartOfClassStaticBlock) {
  7268. if (!tokenIsIdentifier(this.state.type)) {
  7269. return undefined;
  7270. }
  7271. const modifier = this.state.value;
  7272. if (allowedModifiers.indexOf(modifier) !== -1) {
  7273. if (stopOnStartOfClassStaticBlock && this.tsIsStartOfStaticBlocks()) {
  7274. return undefined;
  7275. }
  7276. if (this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {
  7277. return modifier;
  7278. }
  7279. }
  7280. return undefined;
  7281. }
  7282. tsParseModifiers(modified, allowedModifiers, disallowedModifiers, errorTemplate, stopOnStartOfClassStaticBlock) {
  7283. const enforceOrder = (pos, modifier, before, after) => {
  7284. if (modifier === before && modified[after]) {
  7285. this.raise(pos, TSErrors.InvalidModifiersOrder, before, after);
  7286. }
  7287. };
  7288. const incompatible = (pos, modifier, mod1, mod2) => {
  7289. if (modified[mod1] && modifier === mod2 || modified[mod2] && modifier === mod1) {
  7290. this.raise(pos, TSErrors.IncompatibleModifiers, mod1, mod2);
  7291. }
  7292. };
  7293. for (;;) {
  7294. const startPos = this.state.start;
  7295. const modifier = this.tsParseModifier(allowedModifiers.concat(disallowedModifiers != null ? disallowedModifiers : []), stopOnStartOfClassStaticBlock);
  7296. if (!modifier) break;
  7297. if (tsIsAccessModifier(modifier)) {
  7298. if (modified.accessibility) {
  7299. this.raise(startPos, TSErrors.DuplicateAccessibilityModifier);
  7300. } else {
  7301. enforceOrder(startPos, modifier, modifier, "override");
  7302. enforceOrder(startPos, modifier, modifier, "static");
  7303. enforceOrder(startPos, modifier, modifier, "readonly");
  7304. modified.accessibility = modifier;
  7305. }
  7306. } else {
  7307. if (Object.hasOwnProperty.call(modified, modifier)) {
  7308. this.raise(startPos, TSErrors.DuplicateModifier, modifier);
  7309. } else {
  7310. enforceOrder(startPos, modifier, "static", "readonly");
  7311. enforceOrder(startPos, modifier, "static", "override");
  7312. enforceOrder(startPos, modifier, "override", "readonly");
  7313. enforceOrder(startPos, modifier, "abstract", "override");
  7314. incompatible(startPos, modifier, "declare", "override");
  7315. incompatible(startPos, modifier, "static", "abstract");
  7316. }
  7317. modified[modifier] = true;
  7318. }
  7319. if (disallowedModifiers != null && disallowedModifiers.includes(modifier)) {
  7320. this.raise(startPos, errorTemplate, modifier);
  7321. }
  7322. }
  7323. }
  7324. tsIsListTerminator(kind) {
  7325. switch (kind) {
  7326. case "EnumMembers":
  7327. case "TypeMembers":
  7328. return this.match(8);
  7329. case "HeritageClauseElement":
  7330. return this.match(5);
  7331. case "TupleElementTypes":
  7332. return this.match(3);
  7333. case "TypeParametersOrArguments":
  7334. return this.match(44);
  7335. }
  7336. throw new Error("Unreachable");
  7337. }
  7338. tsParseList(kind, parseElement) {
  7339. const result = [];
  7340. while (!this.tsIsListTerminator(kind)) {
  7341. result.push(parseElement());
  7342. }
  7343. return result;
  7344. }
  7345. tsParseDelimitedList(kind, parseElement, refTrailingCommaPos) {
  7346. return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true, refTrailingCommaPos));
  7347. }
  7348. tsParseDelimitedListWorker(kind, parseElement, expectSuccess, refTrailingCommaPos) {
  7349. const result = [];
  7350. let trailingCommaPos = -1;
  7351. for (;;) {
  7352. if (this.tsIsListTerminator(kind)) {
  7353. break;
  7354. }
  7355. trailingCommaPos = -1;
  7356. const element = parseElement();
  7357. if (element == null) {
  7358. return undefined;
  7359. }
  7360. result.push(element);
  7361. if (this.eat(12)) {
  7362. trailingCommaPos = this.state.lastTokStart;
  7363. continue;
  7364. }
  7365. if (this.tsIsListTerminator(kind)) {
  7366. break;
  7367. }
  7368. if (expectSuccess) {
  7369. this.expect(12);
  7370. }
  7371. return undefined;
  7372. }
  7373. if (refTrailingCommaPos) {
  7374. refTrailingCommaPos.value = trailingCommaPos;
  7375. }
  7376. return result;
  7377. }
  7378. tsParseBracketedList(kind, parseElement, bracket, skipFirstToken, refTrailingCommaPos) {
  7379. if (!skipFirstToken) {
  7380. if (bracket) {
  7381. this.expect(0);
  7382. } else {
  7383. this.expect(43);
  7384. }
  7385. }
  7386. const result = this.tsParseDelimitedList(kind, parseElement, refTrailingCommaPos);
  7387. if (bracket) {
  7388. this.expect(3);
  7389. } else {
  7390. this.expect(44);
  7391. }
  7392. return result;
  7393. }
  7394. tsParseImportType() {
  7395. const node = this.startNode();
  7396. this.expect(77);
  7397. this.expect(10);
  7398. if (!this.match(123)) {
  7399. this.raise(this.state.start, TSErrors.UnsupportedImportTypeArgument);
  7400. }
  7401. node.argument = this.parseExprAtom();
  7402. this.expect(11);
  7403. if (this.eat(16)) {
  7404. node.qualifier = this.tsParseEntityName(true);
  7405. }
  7406. if (this.match(43)) {
  7407. node.typeParameters = this.tsParseTypeArguments();
  7408. }
  7409. return this.finishNode(node, "TSImportType");
  7410. }
  7411. tsParseEntityName(allowReservedWords) {
  7412. let entity = this.parseIdentifier();
  7413. while (this.eat(16)) {
  7414. const node = this.startNodeAtNode(entity);
  7415. node.left = entity;
  7416. node.right = this.parseIdentifier(allowReservedWords);
  7417. entity = this.finishNode(node, "TSQualifiedName");
  7418. }
  7419. return entity;
  7420. }
  7421. tsParseTypeReference() {
  7422. const node = this.startNode();
  7423. node.typeName = this.tsParseEntityName(false);
  7424. if (!this.hasPrecedingLineBreak() && this.match(43)) {
  7425. node.typeParameters = this.tsParseTypeArguments();
  7426. }
  7427. return this.finishNode(node, "TSTypeReference");
  7428. }
  7429. tsParseThisTypePredicate(lhs) {
  7430. this.next();
  7431. const node = this.startNodeAtNode(lhs);
  7432. node.parameterName = lhs;
  7433. node.typeAnnotation = this.tsParseTypeAnnotation(false);
  7434. node.asserts = false;
  7435. return this.finishNode(node, "TSTypePredicate");
  7436. }
  7437. tsParseThisTypeNode() {
  7438. const node = this.startNode();
  7439. this.next();
  7440. return this.finishNode(node, "TSThisType");
  7441. }
  7442. tsParseTypeQuery() {
  7443. const node = this.startNode();
  7444. this.expect(81);
  7445. if (this.match(77)) {
  7446. node.exprName = this.tsParseImportType();
  7447. } else {
  7448. node.exprName = this.tsParseEntityName(true);
  7449. }
  7450. return this.finishNode(node, "TSTypeQuery");
  7451. }
  7452. tsParseTypeParameter() {
  7453. const node = this.startNode();
  7454. node.name = this.tsParseTypeParameterName();
  7455. node.constraint = this.tsEatThenParseType(75);
  7456. node.default = this.tsEatThenParseType(27);
  7457. return this.finishNode(node, "TSTypeParameter");
  7458. }
  7459. tsTryParseTypeParameters() {
  7460. if (this.match(43)) {
  7461. return this.tsParseTypeParameters();
  7462. }
  7463. }
  7464. tsParseTypeParameters() {
  7465. const node = this.startNode();
  7466. if (this.match(43) || this.match(132)) {
  7467. this.next();
  7468. } else {
  7469. this.unexpected();
  7470. }
  7471. const refTrailingCommaPos = {
  7472. value: -1
  7473. };
  7474. node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this), false, true, refTrailingCommaPos);
  7475. if (node.params.length === 0) {
  7476. this.raise(node.start, TSErrors.EmptyTypeParameters);
  7477. }
  7478. if (refTrailingCommaPos.value !== -1) {
  7479. this.addExtra(node, "trailingComma", refTrailingCommaPos.value);
  7480. }
  7481. return this.finishNode(node, "TSTypeParameterDeclaration");
  7482. }
  7483. tsTryNextParseConstantContext() {
  7484. if (this.lookahead().type === 69) {
  7485. this.next();
  7486. return this.tsParseTypeReference();
  7487. }
  7488. return null;
  7489. }
  7490. tsFillSignature(returnToken, signature) {
  7491. const returnTokenRequired = returnToken === 19;
  7492. signature.typeParameters = this.tsTryParseTypeParameters();
  7493. this.expect(10);
  7494. signature.parameters = this.tsParseBindingListForSignature();
  7495. if (returnTokenRequired) {
  7496. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  7497. } else if (this.match(returnToken)) {
  7498. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  7499. }
  7500. }
  7501. tsParseBindingListForSignature() {
  7502. return this.parseBindingList(11, 41).map(pattern => {
  7503. if (pattern.type !== "Identifier" && pattern.type !== "RestElement" && pattern.type !== "ObjectPattern" && pattern.type !== "ArrayPattern") {
  7504. this.raise(pattern.start, TSErrors.UnsupportedSignatureParameterKind, pattern.type);
  7505. }
  7506. return pattern;
  7507. });
  7508. }
  7509. tsParseTypeMemberSemicolon() {
  7510. if (!this.eat(12) && !this.isLineTerminator()) {
  7511. this.expect(13);
  7512. }
  7513. }
  7514. tsParseSignatureMember(kind, node) {
  7515. this.tsFillSignature(14, node);
  7516. this.tsParseTypeMemberSemicolon();
  7517. return this.finishNode(node, kind);
  7518. }
  7519. tsIsUnambiguouslyIndexSignature() {
  7520. this.next();
  7521. if (tokenIsIdentifier(this.state.type)) {
  7522. this.next();
  7523. return this.match(14);
  7524. }
  7525. return false;
  7526. }
  7527. tsTryParseIndexSignature(node) {
  7528. if (!(this.match(0) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) {
  7529. return undefined;
  7530. }
  7531. this.expect(0);
  7532. const id = this.parseIdentifier();
  7533. id.typeAnnotation = this.tsParseTypeAnnotation();
  7534. this.resetEndLocation(id);
  7535. this.expect(3);
  7536. node.parameters = [id];
  7537. const type = this.tsTryParseTypeAnnotation();
  7538. if (type) node.typeAnnotation = type;
  7539. this.tsParseTypeMemberSemicolon();
  7540. return this.finishNode(node, "TSIndexSignature");
  7541. }
  7542. tsParsePropertyOrMethodSignature(node, readonly) {
  7543. if (this.eat(17)) node.optional = true;
  7544. const nodeAny = node;
  7545. if (this.match(10) || this.match(43)) {
  7546. if (readonly) {
  7547. this.raise(node.start, TSErrors.ReadonlyForMethodSignature);
  7548. }
  7549. const method = nodeAny;
  7550. if (method.kind && this.match(43)) {
  7551. this.raise(this.state.pos, TSErrors.AccesorCannotHaveTypeParameters);
  7552. }
  7553. this.tsFillSignature(14, method);
  7554. this.tsParseTypeMemberSemicolon();
  7555. if (method.kind === "get") {
  7556. if (method.parameters.length > 0) {
  7557. this.raise(this.state.pos, ErrorMessages.BadGetterArity);
  7558. if (this.isThisParam(method.parameters[0])) {
  7559. this.raise(this.state.pos, TSErrors.AccesorCannotDeclareThisParameter);
  7560. }
  7561. }
  7562. } else if (method.kind === "set") {
  7563. if (method.parameters.length !== 1) {
  7564. this.raise(this.state.pos, ErrorMessages.BadSetterArity);
  7565. } else {
  7566. const firstParameter = method.parameters[0];
  7567. if (this.isThisParam(firstParameter)) {
  7568. this.raise(this.state.pos, TSErrors.AccesorCannotDeclareThisParameter);
  7569. }
  7570. if (firstParameter.type === "Identifier" && firstParameter.optional) {
  7571. this.raise(this.state.pos, TSErrors.SetAccesorCannotHaveOptionalParameter);
  7572. }
  7573. if (firstParameter.type === "RestElement") {
  7574. this.raise(this.state.pos, TSErrors.SetAccesorCannotHaveRestParameter);
  7575. }
  7576. }
  7577. if (method.typeAnnotation) {
  7578. this.raise(method.typeAnnotation.start, TSErrors.SetAccesorCannotHaveReturnType);
  7579. }
  7580. } else {
  7581. method.kind = "method";
  7582. }
  7583. return this.finishNode(method, "TSMethodSignature");
  7584. } else {
  7585. const property = nodeAny;
  7586. if (readonly) property.readonly = true;
  7587. const type = this.tsTryParseTypeAnnotation();
  7588. if (type) property.typeAnnotation = type;
  7589. this.tsParseTypeMemberSemicolon();
  7590. return this.finishNode(property, "TSPropertySignature");
  7591. }
  7592. }
  7593. tsParseTypeMember() {
  7594. const node = this.startNode();
  7595. if (this.match(10) || this.match(43)) {
  7596. return this.tsParseSignatureMember("TSCallSignatureDeclaration", node);
  7597. }
  7598. if (this.match(71)) {
  7599. const id = this.startNode();
  7600. this.next();
  7601. if (this.match(10) || this.match(43)) {
  7602. return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node);
  7603. } else {
  7604. node.key = this.createIdentifier(id, "new");
  7605. return this.tsParsePropertyOrMethodSignature(node, false);
  7606. }
  7607. }
  7608. this.tsParseModifiers(node, ["readonly"], ["declare", "abstract", "private", "protected", "public", "static", "override"], TSErrors.InvalidModifierOnTypeMember);
  7609. const idx = this.tsTryParseIndexSignature(node);
  7610. if (idx) {
  7611. return idx;
  7612. }
  7613. this.parsePropertyName(node);
  7614. if (!node.computed && node.key.type === "Identifier" && (node.key.name === "get" || node.key.name === "set") && this.tsTokenCanFollowModifier()) {
  7615. node.kind = node.key.name;
  7616. this.parsePropertyName(node);
  7617. }
  7618. return this.tsParsePropertyOrMethodSignature(node, !!node.readonly);
  7619. }
  7620. tsParseTypeLiteral() {
  7621. const node = this.startNode();
  7622. node.members = this.tsParseObjectTypeMembers();
  7623. return this.finishNode(node, "TSTypeLiteral");
  7624. }
  7625. tsParseObjectTypeMembers() {
  7626. this.expect(5);
  7627. const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this));
  7628. this.expect(8);
  7629. return members;
  7630. }
  7631. tsIsStartOfMappedType() {
  7632. this.next();
  7633. if (this.eat(47)) {
  7634. return this.isContextual(112);
  7635. }
  7636. if (this.isContextual(112)) {
  7637. this.next();
  7638. }
  7639. if (!this.match(0)) {
  7640. return false;
  7641. }
  7642. this.next();
  7643. if (!this.tsIsIdentifier()) {
  7644. return false;
  7645. }
  7646. this.next();
  7647. return this.match(52);
  7648. }
  7649. tsParseMappedTypeParameter() {
  7650. const node = this.startNode();
  7651. node.name = this.tsParseTypeParameterName();
  7652. node.constraint = this.tsExpectThenParseType(52);
  7653. return this.finishNode(node, "TSTypeParameter");
  7654. }
  7655. tsParseMappedType() {
  7656. const node = this.startNode();
  7657. this.expect(5);
  7658. if (this.match(47)) {
  7659. node.readonly = this.state.value;
  7660. this.next();
  7661. this.expectContextual(112);
  7662. } else if (this.eatContextual(112)) {
  7663. node.readonly = true;
  7664. }
  7665. this.expect(0);
  7666. node.typeParameter = this.tsParseMappedTypeParameter();
  7667. node.nameType = this.eatContextual(87) ? this.tsParseType() : null;
  7668. this.expect(3);
  7669. if (this.match(47)) {
  7670. node.optional = this.state.value;
  7671. this.next();
  7672. this.expect(17);
  7673. } else if (this.eat(17)) {
  7674. node.optional = true;
  7675. }
  7676. node.typeAnnotation = this.tsTryParseType();
  7677. this.semicolon();
  7678. this.expect(8);
  7679. return this.finishNode(node, "TSMappedType");
  7680. }
  7681. tsParseTupleType() {
  7682. const node = this.startNode();
  7683. node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false);
  7684. let seenOptionalElement = false;
  7685. let labeledElements = null;
  7686. node.elementTypes.forEach(elementNode => {
  7687. var _labeledElements;
  7688. let {
  7689. type
  7690. } = elementNode;
  7691. if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) {
  7692. this.raise(elementNode.start, TSErrors.OptionalTypeBeforeRequired);
  7693. }
  7694. seenOptionalElement = seenOptionalElement || type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType";
  7695. if (type === "TSRestType") {
  7696. elementNode = elementNode.typeAnnotation;
  7697. type = elementNode.type;
  7698. }
  7699. const isLabeled = type === "TSNamedTupleMember";
  7700. labeledElements = (_labeledElements = labeledElements) != null ? _labeledElements : isLabeled;
  7701. if (labeledElements !== isLabeled) {
  7702. this.raise(elementNode.start, TSErrors.MixedLabeledAndUnlabeledElements);
  7703. }
  7704. });
  7705. return this.finishNode(node, "TSTupleType");
  7706. }
  7707. tsParseTupleElementType() {
  7708. const {
  7709. start: startPos,
  7710. startLoc
  7711. } = this.state;
  7712. const rest = this.eat(21);
  7713. let type = this.tsParseType();
  7714. const optional = this.eat(17);
  7715. const labeled = this.eat(14);
  7716. if (labeled) {
  7717. const labeledNode = this.startNodeAtNode(type);
  7718. labeledNode.optional = optional;
  7719. if (type.type === "TSTypeReference" && !type.typeParameters && type.typeName.type === "Identifier") {
  7720. labeledNode.label = type.typeName;
  7721. } else {
  7722. this.raise(type.start, TSErrors.InvalidTupleMemberLabel);
  7723. labeledNode.label = type;
  7724. }
  7725. labeledNode.elementType = this.tsParseType();
  7726. type = this.finishNode(labeledNode, "TSNamedTupleMember");
  7727. } else if (optional) {
  7728. const optionalTypeNode = this.startNodeAtNode(type);
  7729. optionalTypeNode.typeAnnotation = type;
  7730. type = this.finishNode(optionalTypeNode, "TSOptionalType");
  7731. }
  7732. if (rest) {
  7733. const restNode = this.startNodeAt(startPos, startLoc);
  7734. restNode.typeAnnotation = type;
  7735. type = this.finishNode(restNode, "TSRestType");
  7736. }
  7737. return type;
  7738. }
  7739. tsParseParenthesizedType() {
  7740. const node = this.startNode();
  7741. this.expect(10);
  7742. node.typeAnnotation = this.tsParseType();
  7743. this.expect(11);
  7744. return this.finishNode(node, "TSParenthesizedType");
  7745. }
  7746. tsParseFunctionOrConstructorType(type, abstract) {
  7747. const node = this.startNode();
  7748. if (type === "TSConstructorType") {
  7749. node.abstract = !!abstract;
  7750. if (abstract) this.next();
  7751. this.next();
  7752. }
  7753. this.tsFillSignature(19, node);
  7754. return this.finishNode(node, type);
  7755. }
  7756. tsParseLiteralTypeNode() {
  7757. const node = this.startNode();
  7758. node.literal = (() => {
  7759. switch (this.state.type) {
  7760. case 124:
  7761. case 125:
  7762. case 123:
  7763. case 79:
  7764. case 80:
  7765. return this.parseExprAtom();
  7766. default:
  7767. throw this.unexpected();
  7768. }
  7769. })();
  7770. return this.finishNode(node, "TSLiteralType");
  7771. }
  7772. tsParseTemplateLiteralType() {
  7773. const node = this.startNode();
  7774. node.literal = this.parseTemplate(false);
  7775. return this.finishNode(node, "TSLiteralType");
  7776. }
  7777. parseTemplateSubstitution() {
  7778. if (this.state.inType) return this.tsParseType();
  7779. return super.parseTemplateSubstitution();
  7780. }
  7781. tsParseThisTypeOrThisTypePredicate() {
  7782. const thisKeyword = this.tsParseThisTypeNode();
  7783. if (this.isContextual(107) && !this.hasPrecedingLineBreak()) {
  7784. return this.tsParseThisTypePredicate(thisKeyword);
  7785. } else {
  7786. return thisKeyword;
  7787. }
  7788. }
  7789. tsParseNonArrayType() {
  7790. switch (this.state.type) {
  7791. case 123:
  7792. case 124:
  7793. case 125:
  7794. case 79:
  7795. case 80:
  7796. return this.tsParseLiteralTypeNode();
  7797. case 47:
  7798. if (this.state.value === "-") {
  7799. const node = this.startNode();
  7800. const nextToken = this.lookahead();
  7801. if (nextToken.type !== 124 && nextToken.type !== 125) {
  7802. throw this.unexpected();
  7803. }
  7804. node.literal = this.parseMaybeUnary();
  7805. return this.finishNode(node, "TSLiteralType");
  7806. }
  7807. break;
  7808. case 72:
  7809. return this.tsParseThisTypeOrThisTypePredicate();
  7810. case 81:
  7811. return this.tsParseTypeQuery();
  7812. case 77:
  7813. return this.tsParseImportType();
  7814. case 5:
  7815. return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral();
  7816. case 0:
  7817. return this.tsParseTupleType();
  7818. case 10:
  7819. return this.tsParseParenthesizedType();
  7820. case 22:
  7821. return this.tsParseTemplateLiteralType();
  7822. default:
  7823. {
  7824. const {
  7825. type
  7826. } = this.state;
  7827. if (tokenIsIdentifier(type) || type === 82 || type === 78) {
  7828. const nodeType = type === 82 ? "TSVoidKeyword" : type === 78 ? "TSNullKeyword" : keywordTypeFromName(this.state.value);
  7829. if (nodeType !== undefined && this.lookaheadCharCode() !== 46) {
  7830. const node = this.startNode();
  7831. this.next();
  7832. return this.finishNode(node, nodeType);
  7833. }
  7834. return this.tsParseTypeReference();
  7835. }
  7836. }
  7837. }
  7838. throw this.unexpected();
  7839. }
  7840. tsParseArrayTypeOrHigher() {
  7841. let type = this.tsParseNonArrayType();
  7842. while (!this.hasPrecedingLineBreak() && this.eat(0)) {
  7843. if (this.match(3)) {
  7844. const node = this.startNodeAtNode(type);
  7845. node.elementType = type;
  7846. this.expect(3);
  7847. type = this.finishNode(node, "TSArrayType");
  7848. } else {
  7849. const node = this.startNodeAtNode(type);
  7850. node.objectType = type;
  7851. node.indexType = this.tsParseType();
  7852. this.expect(3);
  7853. type = this.finishNode(node, "TSIndexedAccessType");
  7854. }
  7855. }
  7856. return type;
  7857. }
  7858. tsParseTypeOperator() {
  7859. const node = this.startNode();
  7860. const operator = this.state.value;
  7861. this.next();
  7862. node.operator = operator;
  7863. node.typeAnnotation = this.tsParseTypeOperatorOrHigher();
  7864. if (operator === "readonly") {
  7865. this.tsCheckTypeAnnotationForReadOnly(node);
  7866. }
  7867. return this.finishNode(node, "TSTypeOperator");
  7868. }
  7869. tsCheckTypeAnnotationForReadOnly(node) {
  7870. switch (node.typeAnnotation.type) {
  7871. case "TSTupleType":
  7872. case "TSArrayType":
  7873. return;
  7874. default:
  7875. this.raise(node.start, TSErrors.UnexpectedReadonly);
  7876. }
  7877. }
  7878. tsParseInferType() {
  7879. const node = this.startNode();
  7880. this.expectContextual(106);
  7881. const typeParameter = this.startNode();
  7882. typeParameter.name = this.tsParseTypeParameterName();
  7883. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  7884. return this.finishNode(node, "TSInferType");
  7885. }
  7886. tsParseTypeOperatorOrHigher() {
  7887. const isTypeOperator = tokenIsTSTypeOperator(this.state.type) && !this.state.containsEsc;
  7888. return isTypeOperator ? this.tsParseTypeOperator() : this.isContextual(106) ? this.tsParseInferType() : this.tsParseArrayTypeOrHigher();
  7889. }
  7890. tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) {
  7891. const node = this.startNode();
  7892. const hasLeadingOperator = this.eat(operator);
  7893. const types = [];
  7894. do {
  7895. types.push(parseConstituentType());
  7896. } while (this.eat(operator));
  7897. if (types.length === 1 && !hasLeadingOperator) {
  7898. return types[0];
  7899. }
  7900. node.types = types;
  7901. return this.finishNode(node, kind);
  7902. }
  7903. tsParseIntersectionTypeOrHigher() {
  7904. return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), 41);
  7905. }
  7906. tsParseUnionTypeOrHigher() {
  7907. return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), 39);
  7908. }
  7909. tsIsStartOfFunctionType() {
  7910. if (this.match(43)) {
  7911. return true;
  7912. }
  7913. return this.match(10) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this));
  7914. }
  7915. tsSkipParameterStart() {
  7916. if (tokenIsIdentifier(this.state.type) || this.match(72)) {
  7917. this.next();
  7918. return true;
  7919. }
  7920. if (this.match(5)) {
  7921. let braceStackCounter = 1;
  7922. this.next();
  7923. while (braceStackCounter > 0) {
  7924. if (this.match(5)) {
  7925. ++braceStackCounter;
  7926. } else if (this.match(8)) {
  7927. --braceStackCounter;
  7928. }
  7929. this.next();
  7930. }
  7931. return true;
  7932. }
  7933. if (this.match(0)) {
  7934. let braceStackCounter = 1;
  7935. this.next();
  7936. while (braceStackCounter > 0) {
  7937. if (this.match(0)) {
  7938. ++braceStackCounter;
  7939. } else if (this.match(3)) {
  7940. --braceStackCounter;
  7941. }
  7942. this.next();
  7943. }
  7944. return true;
  7945. }
  7946. return false;
  7947. }
  7948. tsIsUnambiguouslyStartOfFunctionType() {
  7949. this.next();
  7950. if (this.match(11) || this.match(21)) {
  7951. return true;
  7952. }
  7953. if (this.tsSkipParameterStart()) {
  7954. if (this.match(14) || this.match(12) || this.match(17) || this.match(27)) {
  7955. return true;
  7956. }
  7957. if (this.match(11)) {
  7958. this.next();
  7959. if (this.match(19)) {
  7960. return true;
  7961. }
  7962. }
  7963. }
  7964. return false;
  7965. }
  7966. tsParseTypeOrTypePredicateAnnotation(returnToken) {
  7967. return this.tsInType(() => {
  7968. const t = this.startNode();
  7969. this.expect(returnToken);
  7970. const node = this.startNode();
  7971. const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));
  7972. if (asserts && this.match(72)) {
  7973. let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate();
  7974. if (thisTypePredicate.type === "TSThisType") {
  7975. node.parameterName = thisTypePredicate;
  7976. node.asserts = true;
  7977. node.typeAnnotation = null;
  7978. thisTypePredicate = this.finishNode(node, "TSTypePredicate");
  7979. } else {
  7980. this.resetStartLocationFromNode(thisTypePredicate, node);
  7981. thisTypePredicate.asserts = true;
  7982. }
  7983. t.typeAnnotation = thisTypePredicate;
  7984. return this.finishNode(t, "TSTypeAnnotation");
  7985. }
  7986. const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));
  7987. if (!typePredicateVariable) {
  7988. if (!asserts) {
  7989. return this.tsParseTypeAnnotation(false, t);
  7990. }
  7991. node.parameterName = this.parseIdentifier();
  7992. node.asserts = asserts;
  7993. node.typeAnnotation = null;
  7994. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  7995. return this.finishNode(t, "TSTypeAnnotation");
  7996. }
  7997. const type = this.tsParseTypeAnnotation(false);
  7998. node.parameterName = typePredicateVariable;
  7999. node.typeAnnotation = type;
  8000. node.asserts = asserts;
  8001. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  8002. return this.finishNode(t, "TSTypeAnnotation");
  8003. });
  8004. }
  8005. tsTryParseTypeOrTypePredicateAnnotation() {
  8006. return this.match(14) ? this.tsParseTypeOrTypePredicateAnnotation(14) : undefined;
  8007. }
  8008. tsTryParseTypeAnnotation() {
  8009. return this.match(14) ? this.tsParseTypeAnnotation() : undefined;
  8010. }
  8011. tsTryParseType() {
  8012. return this.tsEatThenParseType(14);
  8013. }
  8014. tsParseTypePredicatePrefix() {
  8015. const id = this.parseIdentifier();
  8016. if (this.isContextual(107) && !this.hasPrecedingLineBreak()) {
  8017. this.next();
  8018. return id;
  8019. }
  8020. }
  8021. tsParseTypePredicateAsserts() {
  8022. if (this.state.type !== 100) {
  8023. return false;
  8024. }
  8025. const containsEsc = this.state.containsEsc;
  8026. this.next();
  8027. if (!tokenIsIdentifier(this.state.type) && !this.match(72)) {
  8028. return false;
  8029. }
  8030. if (containsEsc) {
  8031. this.raise(this.state.lastTokStart, ErrorMessages.InvalidEscapedReservedWord, "asserts");
  8032. }
  8033. return true;
  8034. }
  8035. tsParseTypeAnnotation(eatColon = true, t = this.startNode()) {
  8036. this.tsInType(() => {
  8037. if (eatColon) this.expect(14);
  8038. t.typeAnnotation = this.tsParseType();
  8039. });
  8040. return this.finishNode(t, "TSTypeAnnotation");
  8041. }
  8042. tsParseType() {
  8043. assert(this.state.inType);
  8044. const type = this.tsParseNonConditionalType();
  8045. if (this.hasPrecedingLineBreak() || !this.eat(75)) {
  8046. return type;
  8047. }
  8048. const node = this.startNodeAtNode(type);
  8049. node.checkType = type;
  8050. node.extendsType = this.tsParseNonConditionalType();
  8051. this.expect(17);
  8052. node.trueType = this.tsParseType();
  8053. this.expect(14);
  8054. node.falseType = this.tsParseType();
  8055. return this.finishNode(node, "TSConditionalType");
  8056. }
  8057. isAbstractConstructorSignature() {
  8058. return this.isContextual(114) && this.lookahead().type === 71;
  8059. }
  8060. tsParseNonConditionalType() {
  8061. if (this.tsIsStartOfFunctionType()) {
  8062. return this.tsParseFunctionOrConstructorType("TSFunctionType");
  8063. }
  8064. if (this.match(71)) {
  8065. return this.tsParseFunctionOrConstructorType("TSConstructorType");
  8066. } else if (this.isAbstractConstructorSignature()) {
  8067. return this.tsParseFunctionOrConstructorType("TSConstructorType", true);
  8068. }
  8069. return this.tsParseUnionTypeOrHigher();
  8070. }
  8071. tsParseTypeAssertion() {
  8072. if (this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) {
  8073. this.raise(this.state.start, TSErrors.ReservedTypeAssertion);
  8074. }
  8075. const node = this.startNode();
  8076. const _const = this.tsTryNextParseConstantContext();
  8077. node.typeAnnotation = _const || this.tsNextThenParseType();
  8078. this.expect(44);
  8079. node.expression = this.parseMaybeUnary();
  8080. return this.finishNode(node, "TSTypeAssertion");
  8081. }
  8082. tsParseHeritageClause(descriptor) {
  8083. const originalStart = this.state.start;
  8084. const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", this.tsParseExpressionWithTypeArguments.bind(this));
  8085. if (!delimitedList.length) {
  8086. this.raise(originalStart, TSErrors.EmptyHeritageClauseType, descriptor);
  8087. }
  8088. return delimitedList;
  8089. }
  8090. tsParseExpressionWithTypeArguments() {
  8091. const node = this.startNode();
  8092. node.expression = this.tsParseEntityName(false);
  8093. if (this.match(43)) {
  8094. node.typeParameters = this.tsParseTypeArguments();
  8095. }
  8096. return this.finishNode(node, "TSExpressionWithTypeArguments");
  8097. }
  8098. tsParseInterfaceDeclaration(node) {
  8099. if (tokenIsIdentifier(this.state.type)) {
  8100. node.id = this.parseIdentifier();
  8101. this.checkLVal(node.id, "typescript interface declaration", BIND_TS_INTERFACE);
  8102. } else {
  8103. node.id = null;
  8104. this.raise(this.state.start, TSErrors.MissingInterfaceName);
  8105. }
  8106. node.typeParameters = this.tsTryParseTypeParameters();
  8107. if (this.eat(75)) {
  8108. node.extends = this.tsParseHeritageClause("extends");
  8109. }
  8110. const body = this.startNode();
  8111. body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this));
  8112. node.body = this.finishNode(body, "TSInterfaceBody");
  8113. return this.finishNode(node, "TSInterfaceDeclaration");
  8114. }
  8115. tsParseTypeAliasDeclaration(node) {
  8116. node.id = this.parseIdentifier();
  8117. this.checkLVal(node.id, "typescript type alias", BIND_TS_TYPE);
  8118. node.typeParameters = this.tsTryParseTypeParameters();
  8119. node.typeAnnotation = this.tsInType(() => {
  8120. this.expect(27);
  8121. if (this.isContextual(105) && this.lookahead().type !== 16) {
  8122. const node = this.startNode();
  8123. this.next();
  8124. return this.finishNode(node, "TSIntrinsicKeyword");
  8125. }
  8126. return this.tsParseType();
  8127. });
  8128. this.semicolon();
  8129. return this.finishNode(node, "TSTypeAliasDeclaration");
  8130. }
  8131. tsInNoContext(cb) {
  8132. const oldContext = this.state.context;
  8133. this.state.context = [oldContext[0]];
  8134. try {
  8135. return cb();
  8136. } finally {
  8137. this.state.context = oldContext;
  8138. }
  8139. }
  8140. tsInType(cb) {
  8141. const oldInType = this.state.inType;
  8142. this.state.inType = true;
  8143. try {
  8144. return cb();
  8145. } finally {
  8146. this.state.inType = oldInType;
  8147. }
  8148. }
  8149. tsEatThenParseType(token) {
  8150. return !this.match(token) ? undefined : this.tsNextThenParseType();
  8151. }
  8152. tsExpectThenParseType(token) {
  8153. return this.tsDoThenParseType(() => this.expect(token));
  8154. }
  8155. tsNextThenParseType() {
  8156. return this.tsDoThenParseType(() => this.next());
  8157. }
  8158. tsDoThenParseType(cb) {
  8159. return this.tsInType(() => {
  8160. cb();
  8161. return this.tsParseType();
  8162. });
  8163. }
  8164. tsParseEnumMember() {
  8165. const node = this.startNode();
  8166. node.id = this.match(123) ? this.parseExprAtom() : this.parseIdentifier(true);
  8167. if (this.eat(27)) {
  8168. node.initializer = this.parseMaybeAssignAllowIn();
  8169. }
  8170. return this.finishNode(node, "TSEnumMember");
  8171. }
  8172. tsParseEnumDeclaration(node, isConst) {
  8173. if (isConst) node.const = true;
  8174. node.id = this.parseIdentifier();
  8175. this.checkLVal(node.id, "typescript enum declaration", isConst ? BIND_TS_CONST_ENUM : BIND_TS_ENUM);
  8176. this.expect(5);
  8177. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  8178. this.expect(8);
  8179. return this.finishNode(node, "TSEnumDeclaration");
  8180. }
  8181. tsParseModuleBlock() {
  8182. const node = this.startNode();
  8183. this.scope.enter(SCOPE_OTHER);
  8184. this.expect(5);
  8185. this.parseBlockOrModuleBlockBody(node.body = [], undefined, true, 8);
  8186. this.scope.exit();
  8187. return this.finishNode(node, "TSModuleBlock");
  8188. }
  8189. tsParseModuleOrNamespaceDeclaration(node, nested = false) {
  8190. node.id = this.parseIdentifier();
  8191. if (!nested) {
  8192. this.checkLVal(node.id, "module or namespace declaration", BIND_TS_NAMESPACE);
  8193. }
  8194. if (this.eat(16)) {
  8195. const inner = this.startNode();
  8196. this.tsParseModuleOrNamespaceDeclaration(inner, true);
  8197. node.body = inner;
  8198. } else {
  8199. this.scope.enter(SCOPE_TS_MODULE);
  8200. this.prodParam.enter(PARAM);
  8201. node.body = this.tsParseModuleBlock();
  8202. this.prodParam.exit();
  8203. this.scope.exit();
  8204. }
  8205. return this.finishNode(node, "TSModuleDeclaration");
  8206. }
  8207. tsParseAmbientExternalModuleDeclaration(node) {
  8208. if (this.isContextual(103)) {
  8209. node.global = true;
  8210. node.id = this.parseIdentifier();
  8211. } else if (this.match(123)) {
  8212. node.id = this.parseExprAtom();
  8213. } else {
  8214. this.unexpected();
  8215. }
  8216. if (this.match(5)) {
  8217. this.scope.enter(SCOPE_TS_MODULE);
  8218. this.prodParam.enter(PARAM);
  8219. node.body = this.tsParseModuleBlock();
  8220. this.prodParam.exit();
  8221. this.scope.exit();
  8222. } else {
  8223. this.semicolon();
  8224. }
  8225. return this.finishNode(node, "TSModuleDeclaration");
  8226. }
  8227. tsParseImportEqualsDeclaration(node, isExport) {
  8228. node.isExport = isExport || false;
  8229. node.id = this.parseIdentifier();
  8230. this.checkLVal(node.id, "import equals declaration", BIND_LEXICAL);
  8231. this.expect(27);
  8232. const moduleReference = this.tsParseModuleReference();
  8233. if (node.importKind === "type" && moduleReference.type !== "TSExternalModuleReference") {
  8234. this.raise(moduleReference.start, TSErrors.ImportAliasHasImportType);
  8235. }
  8236. node.moduleReference = moduleReference;
  8237. this.semicolon();
  8238. return this.finishNode(node, "TSImportEqualsDeclaration");
  8239. }
  8240. tsIsExternalModuleReference() {
  8241. return this.isContextual(110) && this.lookaheadCharCode() === 40;
  8242. }
  8243. tsParseModuleReference() {
  8244. return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false);
  8245. }
  8246. tsParseExternalModuleReference() {
  8247. const node = this.startNode();
  8248. this.expectContextual(110);
  8249. this.expect(10);
  8250. if (!this.match(123)) {
  8251. throw this.unexpected();
  8252. }
  8253. node.expression = this.parseExprAtom();
  8254. this.expect(11);
  8255. return this.finishNode(node, "TSExternalModuleReference");
  8256. }
  8257. tsLookAhead(f) {
  8258. const state = this.state.clone();
  8259. const res = f();
  8260. this.state = state;
  8261. return res;
  8262. }
  8263. tsTryParseAndCatch(f) {
  8264. const result = this.tryParse(abort => f() || abort());
  8265. if (result.aborted || !result.node) return undefined;
  8266. if (result.error) this.state = result.failState;
  8267. return result.node;
  8268. }
  8269. tsTryParse(f) {
  8270. const state = this.state.clone();
  8271. const result = f();
  8272. if (result !== undefined && result !== false) {
  8273. return result;
  8274. } else {
  8275. this.state = state;
  8276. return undefined;
  8277. }
  8278. }
  8279. tsTryParseDeclare(nany) {
  8280. if (this.isLineTerminator()) {
  8281. return;
  8282. }
  8283. let starttype = this.state.type;
  8284. let kind;
  8285. if (this.isContextual(93)) {
  8286. starttype = 68;
  8287. kind = "let";
  8288. }
  8289. return this.tsInAmbientContext(() => {
  8290. switch (starttype) {
  8291. case 62:
  8292. nany.declare = true;
  8293. return this.parseFunctionStatement(nany, false, true);
  8294. case 74:
  8295. nany.declare = true;
  8296. return this.parseClass(nany, true, false);
  8297. case 69:
  8298. if (this.match(69) && this.isLookaheadContextual("enum")) {
  8299. this.expect(69);
  8300. this.expectContextual(116);
  8301. return this.tsParseEnumDeclaration(nany, true);
  8302. }
  8303. case 68:
  8304. kind = kind || this.state.value;
  8305. return this.parseVarStatement(nany, kind);
  8306. case 103:
  8307. return this.tsParseAmbientExternalModuleDeclaration(nany);
  8308. default:
  8309. {
  8310. if (tokenIsIdentifier(starttype)) {
  8311. return this.tsParseDeclaration(nany, this.state.value, true);
  8312. }
  8313. }
  8314. }
  8315. });
  8316. }
  8317. tsTryParseExportDeclaration() {
  8318. return this.tsParseDeclaration(this.startNode(), this.state.value, true);
  8319. }
  8320. tsParseExpressionStatement(node, expr) {
  8321. switch (expr.name) {
  8322. case "declare":
  8323. {
  8324. const declaration = this.tsTryParseDeclare(node);
  8325. if (declaration) {
  8326. declaration.declare = true;
  8327. return declaration;
  8328. }
  8329. break;
  8330. }
  8331. case "global":
  8332. if (this.match(5)) {
  8333. this.scope.enter(SCOPE_TS_MODULE);
  8334. this.prodParam.enter(PARAM);
  8335. const mod = node;
  8336. mod.global = true;
  8337. mod.id = expr;
  8338. mod.body = this.tsParseModuleBlock();
  8339. this.scope.exit();
  8340. this.prodParam.exit();
  8341. return this.finishNode(mod, "TSModuleDeclaration");
  8342. }
  8343. break;
  8344. default:
  8345. return this.tsParseDeclaration(node, expr.name, false);
  8346. }
  8347. }
  8348. tsParseDeclaration(node, value, next) {
  8349. switch (value) {
  8350. case "abstract":
  8351. if (this.tsCheckLineTerminator(next) && (this.match(74) || tokenIsIdentifier(this.state.type))) {
  8352. return this.tsParseAbstractDeclaration(node);
  8353. }
  8354. break;
  8355. case "enum":
  8356. if (next || tokenIsIdentifier(this.state.type)) {
  8357. if (next) this.next();
  8358. return this.tsParseEnumDeclaration(node, false);
  8359. }
  8360. break;
  8361. case "interface":
  8362. if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
  8363. return this.tsParseInterfaceDeclaration(node);
  8364. }
  8365. break;
  8366. case "module":
  8367. if (this.tsCheckLineTerminator(next)) {
  8368. if (this.match(123)) {
  8369. return this.tsParseAmbientExternalModuleDeclaration(node);
  8370. } else if (tokenIsIdentifier(this.state.type)) {
  8371. return this.tsParseModuleOrNamespaceDeclaration(node);
  8372. }
  8373. }
  8374. break;
  8375. case "namespace":
  8376. if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
  8377. return this.tsParseModuleOrNamespaceDeclaration(node);
  8378. }
  8379. break;
  8380. case "type":
  8381. if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
  8382. return this.tsParseTypeAliasDeclaration(node);
  8383. }
  8384. break;
  8385. }
  8386. }
  8387. tsCheckLineTerminator(next) {
  8388. if (next) {
  8389. if (this.hasFollowingLineBreak()) return false;
  8390. this.next();
  8391. return true;
  8392. }
  8393. return !this.isLineTerminator();
  8394. }
  8395. tsTryParseGenericAsyncArrowFunction(startPos, startLoc) {
  8396. if (!this.match(43)) {
  8397. return undefined;
  8398. }
  8399. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8400. this.state.maybeInArrowParameters = true;
  8401. const res = this.tsTryParseAndCatch(() => {
  8402. const node = this.startNodeAt(startPos, startLoc);
  8403. node.typeParameters = this.tsParseTypeParameters();
  8404. super.parseFunctionParams(node);
  8405. node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation();
  8406. this.expect(19);
  8407. return node;
  8408. });
  8409. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8410. if (!res) {
  8411. return undefined;
  8412. }
  8413. return this.parseArrowExpression(res, null, true);
  8414. }
  8415. tsParseTypeArguments() {
  8416. const node = this.startNode();
  8417. node.params = this.tsInType(() => this.tsInNoContext(() => {
  8418. this.expect(43);
  8419. return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this));
  8420. }));
  8421. if (node.params.length === 0) {
  8422. this.raise(node.start, TSErrors.EmptyTypeArguments);
  8423. }
  8424. this.expect(44);
  8425. return this.finishNode(node, "TSTypeParameterInstantiation");
  8426. }
  8427. tsIsDeclarationStart() {
  8428. return tokenIsTSDeclarationStart(this.state.type);
  8429. }
  8430. isExportDefaultSpecifier() {
  8431. if (this.tsIsDeclarationStart()) return false;
  8432. return super.isExportDefaultSpecifier();
  8433. }
  8434. parseAssignableListItem(allowModifiers, decorators) {
  8435. const startPos = this.state.start;
  8436. const startLoc = this.state.startLoc;
  8437. let accessibility;
  8438. let readonly = false;
  8439. let override = false;
  8440. if (allowModifiers !== undefined) {
  8441. const modified = {};
  8442. this.tsParseModifiers(modified, ["public", "private", "protected", "override", "readonly"]);
  8443. accessibility = modified.accessibility;
  8444. override = modified.override;
  8445. readonly = modified.readonly;
  8446. if (allowModifiers === false && (accessibility || readonly || override)) {
  8447. this.raise(startPos, TSErrors.UnexpectedParameterModifier);
  8448. }
  8449. }
  8450. const left = this.parseMaybeDefault();
  8451. this.parseAssignableListItemTypes(left);
  8452. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  8453. if (accessibility || readonly || override) {
  8454. const pp = this.startNodeAt(startPos, startLoc);
  8455. if (decorators.length) {
  8456. pp.decorators = decorators;
  8457. }
  8458. if (accessibility) pp.accessibility = accessibility;
  8459. if (readonly) pp.readonly = readonly;
  8460. if (override) pp.override = override;
  8461. if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") {
  8462. this.raise(pp.start, TSErrors.UnsupportedParameterPropertyKind);
  8463. }
  8464. pp.parameter = elt;
  8465. return this.finishNode(pp, "TSParameterProperty");
  8466. }
  8467. if (decorators.length) {
  8468. left.decorators = decorators;
  8469. }
  8470. return elt;
  8471. }
  8472. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  8473. if (this.match(14)) {
  8474. node.returnType = this.tsParseTypeOrTypePredicateAnnotation(14);
  8475. }
  8476. const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" || type === "ClassPrivateMethod" ? "TSDeclareMethod" : undefined;
  8477. if (bodilessType && !this.match(5) && this.isLineTerminator()) {
  8478. this.finishNode(node, bodilessType);
  8479. return;
  8480. }
  8481. if (bodilessType === "TSDeclareFunction" && this.state.isAmbientContext) {
  8482. this.raise(node.start, TSErrors.DeclareFunctionHasImplementation);
  8483. if (node.declare) {
  8484. super.parseFunctionBodyAndFinish(node, bodilessType, isMethod);
  8485. return;
  8486. }
  8487. }
  8488. super.parseFunctionBodyAndFinish(node, type, isMethod);
  8489. }
  8490. registerFunctionStatementId(node) {
  8491. if (!node.body && node.id) {
  8492. this.checkLVal(node.id, "function name", BIND_TS_AMBIENT);
  8493. } else {
  8494. super.registerFunctionStatementId(...arguments);
  8495. }
  8496. }
  8497. tsCheckForInvalidTypeCasts(items) {
  8498. items.forEach(node => {
  8499. if ((node == null ? void 0 : node.type) === "TSTypeCastExpression") {
  8500. this.raise(node.typeAnnotation.start, TSErrors.UnexpectedTypeAnnotation);
  8501. }
  8502. });
  8503. }
  8504. toReferencedList(exprList, isInParens) {
  8505. this.tsCheckForInvalidTypeCasts(exprList);
  8506. return exprList;
  8507. }
  8508. parseArrayLike(...args) {
  8509. const node = super.parseArrayLike(...args);
  8510. if (node.type === "ArrayExpression") {
  8511. this.tsCheckForInvalidTypeCasts(node.elements);
  8512. }
  8513. return node;
  8514. }
  8515. parseSubscript(base, startPos, startLoc, noCalls, state) {
  8516. if (!this.hasPrecedingLineBreak() && this.match(33)) {
  8517. this.state.canStartJSXElement = false;
  8518. this.next();
  8519. const nonNullExpression = this.startNodeAt(startPos, startLoc);
  8520. nonNullExpression.expression = base;
  8521. return this.finishNode(nonNullExpression, "TSNonNullExpression");
  8522. }
  8523. let isOptionalCall = false;
  8524. if (this.match(18) && this.lookaheadCharCode() === 60) {
  8525. if (noCalls) {
  8526. state.stop = true;
  8527. return base;
  8528. }
  8529. state.optionalChainMember = isOptionalCall = true;
  8530. this.next();
  8531. }
  8532. if (this.match(43)) {
  8533. let missingParenErrorPos;
  8534. const result = this.tsTryParseAndCatch(() => {
  8535. if (!noCalls && this.atPossibleAsyncArrow(base)) {
  8536. const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startPos, startLoc);
  8537. if (asyncArrowFn) {
  8538. return asyncArrowFn;
  8539. }
  8540. }
  8541. const node = this.startNodeAt(startPos, startLoc);
  8542. node.callee = base;
  8543. const typeArguments = this.tsParseTypeArguments();
  8544. if (typeArguments) {
  8545. if (isOptionalCall && !this.match(10)) {
  8546. missingParenErrorPos = this.state.pos;
  8547. this.unexpected();
  8548. }
  8549. if (!noCalls && this.eat(10)) {
  8550. node.arguments = this.parseCallExpressionArguments(11, false);
  8551. this.tsCheckForInvalidTypeCasts(node.arguments);
  8552. node.typeParameters = typeArguments;
  8553. if (state.optionalChainMember) {
  8554. node.optional = isOptionalCall;
  8555. }
  8556. return this.finishCallExpression(node, state.optionalChainMember);
  8557. } else if (this.match(22)) {
  8558. const result = this.parseTaggedTemplateExpression(base, startPos, startLoc, state);
  8559. result.typeParameters = typeArguments;
  8560. return result;
  8561. }
  8562. }
  8563. this.unexpected();
  8564. });
  8565. if (missingParenErrorPos) {
  8566. this.unexpected(missingParenErrorPos, 10);
  8567. }
  8568. if (result) return result;
  8569. }
  8570. return super.parseSubscript(base, startPos, startLoc, noCalls, state);
  8571. }
  8572. parseNewArguments(node) {
  8573. if (this.match(43)) {
  8574. const typeParameters = this.tsTryParseAndCatch(() => {
  8575. const args = this.tsParseTypeArguments();
  8576. if (!this.match(10)) this.unexpected();
  8577. return args;
  8578. });
  8579. if (typeParameters) {
  8580. node.typeParameters = typeParameters;
  8581. }
  8582. }
  8583. super.parseNewArguments(node);
  8584. }
  8585. parseExprOp(left, leftStartPos, leftStartLoc, minPrec) {
  8586. if (tokenOperatorPrecedence(52) > minPrec && !this.hasPrecedingLineBreak() && this.isContextual(87)) {
  8587. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  8588. node.expression = left;
  8589. const _const = this.tsTryNextParseConstantContext();
  8590. if (_const) {
  8591. node.typeAnnotation = _const;
  8592. } else {
  8593. node.typeAnnotation = this.tsNextThenParseType();
  8594. }
  8595. this.finishNode(node, "TSAsExpression");
  8596. this.reScan_lt_gt();
  8597. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec);
  8598. }
  8599. return super.parseExprOp(left, leftStartPos, leftStartLoc, minPrec);
  8600. }
  8601. checkReservedWord(word, startLoc, checkKeywords, isBinding) {}
  8602. checkDuplicateExports() {}
  8603. parseImport(node) {
  8604. node.importKind = "value";
  8605. if (tokenIsIdentifier(this.state.type) || this.match(49) || this.match(5)) {
  8606. let ahead = this.lookahead();
  8607. if (this.isContextual(120) && ahead.type !== 12 && ahead.type !== 91 && ahead.type !== 27) {
  8608. node.importKind = "type";
  8609. this.next();
  8610. ahead = this.lookahead();
  8611. }
  8612. if (tokenIsIdentifier(this.state.type) && ahead.type === 27) {
  8613. return this.tsParseImportEqualsDeclaration(node);
  8614. }
  8615. }
  8616. const importNode = super.parseImport(node);
  8617. if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") {
  8618. this.raise(importNode.start, TSErrors.TypeImportCannotSpecifyDefaultAndNamed);
  8619. }
  8620. return importNode;
  8621. }
  8622. parseExport(node) {
  8623. if (this.match(77)) {
  8624. this.next();
  8625. if (this.isContextual(120) && this.lookaheadCharCode() !== 61) {
  8626. node.importKind = "type";
  8627. this.next();
  8628. } else {
  8629. node.importKind = "value";
  8630. }
  8631. return this.tsParseImportEqualsDeclaration(node, true);
  8632. } else if (this.eat(27)) {
  8633. const assign = node;
  8634. assign.expression = this.parseExpression();
  8635. this.semicolon();
  8636. return this.finishNode(assign, "TSExportAssignment");
  8637. } else if (this.eatContextual(87)) {
  8638. const decl = node;
  8639. this.expectContextual(118);
  8640. decl.id = this.parseIdentifier();
  8641. this.semicolon();
  8642. return this.finishNode(decl, "TSNamespaceExportDeclaration");
  8643. } else {
  8644. if (this.isContextual(120) && this.lookahead().type === 5) {
  8645. this.next();
  8646. node.exportKind = "type";
  8647. } else {
  8648. node.exportKind = "value";
  8649. }
  8650. return super.parseExport(node);
  8651. }
  8652. }
  8653. isAbstractClass() {
  8654. return this.isContextual(114) && this.lookahead().type === 74;
  8655. }
  8656. parseExportDefaultExpression() {
  8657. if (this.isAbstractClass()) {
  8658. const cls = this.startNode();
  8659. this.next();
  8660. cls.abstract = true;
  8661. this.parseClass(cls, true, true);
  8662. return cls;
  8663. }
  8664. if (this.match(119)) {
  8665. const interfaceNode = this.startNode();
  8666. this.next();
  8667. const result = this.tsParseInterfaceDeclaration(interfaceNode);
  8668. if (result) return result;
  8669. }
  8670. return super.parseExportDefaultExpression();
  8671. }
  8672. parseStatementContent(context, topLevel) {
  8673. if (this.state.type === 69) {
  8674. const ahead = this.lookahead();
  8675. if (ahead.type === 116) {
  8676. const node = this.startNode();
  8677. this.next();
  8678. this.expectContextual(116);
  8679. return this.tsParseEnumDeclaration(node, true);
  8680. }
  8681. }
  8682. return super.parseStatementContent(context, topLevel);
  8683. }
  8684. parseAccessModifier() {
  8685. return this.tsParseModifier(["public", "protected", "private"]);
  8686. }
  8687. tsHasSomeModifiers(member, modifiers) {
  8688. return modifiers.some(modifier => {
  8689. if (tsIsAccessModifier(modifier)) {
  8690. return member.accessibility === modifier;
  8691. }
  8692. return !!member[modifier];
  8693. });
  8694. }
  8695. tsIsStartOfStaticBlocks() {
  8696. return this.isContextual(98) && this.lookaheadCharCode() === 123;
  8697. }
  8698. parseClassMember(classBody, member, state) {
  8699. const modifiers = ["declare", "private", "public", "protected", "override", "abstract", "readonly", "static"];
  8700. this.tsParseModifiers(member, modifiers, undefined, undefined, true);
  8701. const callParseClassMemberWithIsStatic = () => {
  8702. if (this.tsIsStartOfStaticBlocks()) {
  8703. this.next();
  8704. this.next();
  8705. if (this.tsHasSomeModifiers(member, modifiers)) {
  8706. this.raise(this.state.pos, TSErrors.StaticBlockCannotHaveModifier);
  8707. }
  8708. this.parseClassStaticBlock(classBody, member);
  8709. } else {
  8710. this.parseClassMemberWithIsStatic(classBody, member, state, !!member.static);
  8711. }
  8712. };
  8713. if (member.declare) {
  8714. this.tsInAmbientContext(callParseClassMemberWithIsStatic);
  8715. } else {
  8716. callParseClassMemberWithIsStatic();
  8717. }
  8718. }
  8719. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  8720. const idx = this.tsTryParseIndexSignature(member);
  8721. if (idx) {
  8722. classBody.body.push(idx);
  8723. if (member.abstract) {
  8724. this.raise(member.start, TSErrors.IndexSignatureHasAbstract);
  8725. }
  8726. if (member.accessibility) {
  8727. this.raise(member.start, TSErrors.IndexSignatureHasAccessibility, member.accessibility);
  8728. }
  8729. if (member.declare) {
  8730. this.raise(member.start, TSErrors.IndexSignatureHasDeclare);
  8731. }
  8732. if (member.override) {
  8733. this.raise(member.start, TSErrors.IndexSignatureHasOverride);
  8734. }
  8735. return;
  8736. }
  8737. if (!this.state.inAbstractClass && member.abstract) {
  8738. this.raise(member.start, TSErrors.NonAbstractClassHasAbstractMethod);
  8739. }
  8740. if (member.override) {
  8741. if (!state.hadSuperClass) {
  8742. this.raise(member.start, TSErrors.OverrideNotInSubClass);
  8743. }
  8744. }
  8745. super.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  8746. }
  8747. parsePostMemberNameModifiers(methodOrProp) {
  8748. const optional = this.eat(17);
  8749. if (optional) methodOrProp.optional = true;
  8750. if (methodOrProp.readonly && this.match(10)) {
  8751. this.raise(methodOrProp.start, TSErrors.ClassMethodHasReadonly);
  8752. }
  8753. if (methodOrProp.declare && this.match(10)) {
  8754. this.raise(methodOrProp.start, TSErrors.ClassMethodHasDeclare);
  8755. }
  8756. }
  8757. parseExpressionStatement(node, expr) {
  8758. const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr) : undefined;
  8759. return decl || super.parseExpressionStatement(node, expr);
  8760. }
  8761. shouldParseExportDeclaration() {
  8762. if (this.tsIsDeclarationStart()) return true;
  8763. return super.shouldParseExportDeclaration();
  8764. }
  8765. parseConditional(expr, startPos, startLoc, refExpressionErrors) {
  8766. if (!this.state.maybeInArrowParameters || !this.match(17)) {
  8767. return super.parseConditional(expr, startPos, startLoc, refExpressionErrors);
  8768. }
  8769. const result = this.tryParse(() => super.parseConditional(expr, startPos, startLoc));
  8770. if (!result.node) {
  8771. if (result.error) {
  8772. super.setOptionalParametersError(refExpressionErrors, result.error);
  8773. }
  8774. return expr;
  8775. }
  8776. if (result.error) this.state = result.failState;
  8777. return result.node;
  8778. }
  8779. parseParenItem(node, startPos, startLoc) {
  8780. node = super.parseParenItem(node, startPos, startLoc);
  8781. if (this.eat(17)) {
  8782. node.optional = true;
  8783. this.resetEndLocation(node);
  8784. }
  8785. if (this.match(14)) {
  8786. const typeCastNode = this.startNodeAt(startPos, startLoc);
  8787. typeCastNode.expression = node;
  8788. typeCastNode.typeAnnotation = this.tsParseTypeAnnotation();
  8789. return this.finishNode(typeCastNode, "TSTypeCastExpression");
  8790. }
  8791. return node;
  8792. }
  8793. parseExportDeclaration(node) {
  8794. const startPos = this.state.start;
  8795. const startLoc = this.state.startLoc;
  8796. const isDeclare = this.eatContextual(115);
  8797. if (isDeclare && (this.isContextual(115) || !this.shouldParseExportDeclaration())) {
  8798. throw this.raise(this.state.start, TSErrors.ExpectedAmbientAfterExportDeclare);
  8799. }
  8800. let declaration;
  8801. if (tokenIsIdentifier(this.state.type)) {
  8802. declaration = this.tsTryParseExportDeclaration();
  8803. }
  8804. if (!declaration) {
  8805. declaration = super.parseExportDeclaration(node);
  8806. }
  8807. if (declaration && (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare)) {
  8808. node.exportKind = "type";
  8809. }
  8810. if (declaration && isDeclare) {
  8811. this.resetStartLocation(declaration, startPos, startLoc);
  8812. declaration.declare = true;
  8813. }
  8814. return declaration;
  8815. }
  8816. parseClassId(node, isStatement, optionalId) {
  8817. if ((!isStatement || optionalId) && this.isContextual(104)) {
  8818. return;
  8819. }
  8820. super.parseClassId(node, isStatement, optionalId, node.declare ? BIND_TS_AMBIENT : BIND_CLASS);
  8821. const typeParameters = this.tsTryParseTypeParameters();
  8822. if (typeParameters) node.typeParameters = typeParameters;
  8823. }
  8824. parseClassPropertyAnnotation(node) {
  8825. if (!node.optional && this.eat(33)) {
  8826. node.definite = true;
  8827. }
  8828. const type = this.tsTryParseTypeAnnotation();
  8829. if (type) node.typeAnnotation = type;
  8830. }
  8831. parseClassProperty(node) {
  8832. this.parseClassPropertyAnnotation(node);
  8833. if (this.state.isAmbientContext && this.match(27)) {
  8834. this.raise(this.state.start, TSErrors.DeclareClassFieldHasInitializer);
  8835. }
  8836. if (node.abstract && this.match(27)) {
  8837. const {
  8838. key
  8839. } = node;
  8840. this.raise(this.state.start, TSErrors.AbstractPropertyHasInitializer, key.type === "Identifier" && !node.computed ? key.name : `[${this.input.slice(key.start, key.end)}]`);
  8841. }
  8842. return super.parseClassProperty(node);
  8843. }
  8844. parseClassPrivateProperty(node) {
  8845. if (node.abstract) {
  8846. this.raise(node.start, TSErrors.PrivateElementHasAbstract);
  8847. }
  8848. if (node.accessibility) {
  8849. this.raise(node.start, TSErrors.PrivateElementHasAccessibility, node.accessibility);
  8850. }
  8851. this.parseClassPropertyAnnotation(node);
  8852. return super.parseClassPrivateProperty(node);
  8853. }
  8854. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  8855. const typeParameters = this.tsTryParseTypeParameters();
  8856. if (typeParameters && isConstructor) {
  8857. this.raise(typeParameters.start, TSErrors.ConstructorHasTypeParameters);
  8858. }
  8859. if (method.declare && (method.kind === "get" || method.kind === "set")) {
  8860. this.raise(method.start, TSErrors.DeclareAccessor, method.kind);
  8861. }
  8862. if (typeParameters) method.typeParameters = typeParameters;
  8863. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  8864. }
  8865. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  8866. const typeParameters = this.tsTryParseTypeParameters();
  8867. if (typeParameters) method.typeParameters = typeParameters;
  8868. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  8869. }
  8870. declareClassPrivateMethodInScope(node, kind) {
  8871. if (node.type === "TSDeclareMethod") return;
  8872. if (node.type === "MethodDefinition" && !node.value.body) return;
  8873. super.declareClassPrivateMethodInScope(node, kind);
  8874. }
  8875. parseClassSuper(node) {
  8876. super.parseClassSuper(node);
  8877. if (node.superClass && this.match(43)) {
  8878. node.superTypeParameters = this.tsParseTypeArguments();
  8879. }
  8880. if (this.eatContextual(104)) {
  8881. node.implements = this.tsParseHeritageClause("implements");
  8882. }
  8883. }
  8884. parseObjPropValue(prop, ...args) {
  8885. const typeParameters = this.tsTryParseTypeParameters();
  8886. if (typeParameters) prop.typeParameters = typeParameters;
  8887. super.parseObjPropValue(prop, ...args);
  8888. }
  8889. parseFunctionParams(node, allowModifiers) {
  8890. const typeParameters = this.tsTryParseTypeParameters();
  8891. if (typeParameters) node.typeParameters = typeParameters;
  8892. super.parseFunctionParams(node, allowModifiers);
  8893. }
  8894. parseVarId(decl, kind) {
  8895. super.parseVarId(decl, kind);
  8896. if (decl.id.type === "Identifier" && this.eat(33)) {
  8897. decl.definite = true;
  8898. }
  8899. const type = this.tsTryParseTypeAnnotation();
  8900. if (type) {
  8901. decl.id.typeAnnotation = type;
  8902. this.resetEndLocation(decl.id);
  8903. }
  8904. }
  8905. parseAsyncArrowFromCallExpression(node, call) {
  8906. if (this.match(14)) {
  8907. node.returnType = this.tsParseTypeAnnotation();
  8908. }
  8909. return super.parseAsyncArrowFromCallExpression(node, call);
  8910. }
  8911. parseMaybeAssign(...args) {
  8912. var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2, _jsx4, _typeCast3;
  8913. let state;
  8914. let jsx;
  8915. let typeCast;
  8916. if (this.hasPlugin("jsx") && (this.match(132) || this.match(43))) {
  8917. state = this.state.clone();
  8918. jsx = this.tryParse(() => super.parseMaybeAssign(...args), state);
  8919. if (!jsx.error) return jsx.node;
  8920. const {
  8921. context
  8922. } = this.state;
  8923. if (context[context.length - 1] === types.j_oTag) {
  8924. context.length -= 2;
  8925. } else if (context[context.length - 1] === types.j_expr) {
  8926. context.length -= 1;
  8927. }
  8928. }
  8929. if (!((_jsx = jsx) != null && _jsx.error) && !this.match(43)) {
  8930. return super.parseMaybeAssign(...args);
  8931. }
  8932. let typeParameters;
  8933. state = state || this.state.clone();
  8934. const arrow = this.tryParse(abort => {
  8935. var _expr$extra, _typeParameters;
  8936. typeParameters = this.tsParseTypeParameters();
  8937. const expr = super.parseMaybeAssign(...args);
  8938. if (expr.type !== "ArrowFunctionExpression" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) {
  8939. abort();
  8940. }
  8941. if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) {
  8942. this.resetStartLocationFromNode(expr, typeParameters);
  8943. }
  8944. expr.typeParameters = typeParameters;
  8945. return expr;
  8946. }, state);
  8947. if (!arrow.error && !arrow.aborted) {
  8948. if (typeParameters) this.reportReservedArrowTypeParam(typeParameters);
  8949. return arrow.node;
  8950. }
  8951. if (!jsx) {
  8952. assert(!this.hasPlugin("jsx"));
  8953. typeCast = this.tryParse(() => super.parseMaybeAssign(...args), state);
  8954. if (!typeCast.error) return typeCast.node;
  8955. }
  8956. if ((_jsx2 = jsx) != null && _jsx2.node) {
  8957. this.state = jsx.failState;
  8958. return jsx.node;
  8959. }
  8960. if (arrow.node) {
  8961. this.state = arrow.failState;
  8962. if (typeParameters) this.reportReservedArrowTypeParam(typeParameters);
  8963. return arrow.node;
  8964. }
  8965. if ((_typeCast = typeCast) != null && _typeCast.node) {
  8966. this.state = typeCast.failState;
  8967. return typeCast.node;
  8968. }
  8969. if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error;
  8970. if (arrow.thrown) throw arrow.error;
  8971. if ((_typeCast2 = typeCast) != null && _typeCast2.thrown) throw typeCast.error;
  8972. throw ((_jsx4 = jsx) == null ? void 0 : _jsx4.error) || arrow.error || ((_typeCast3 = typeCast) == null ? void 0 : _typeCast3.error);
  8973. }
  8974. reportReservedArrowTypeParam(node) {
  8975. var _node$extra;
  8976. if (node.params.length === 1 && !((_node$extra = node.extra) != null && _node$extra.trailingComma) && this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) {
  8977. this.raise(node.start, TSErrors.ReservedArrowTypeParam);
  8978. }
  8979. }
  8980. parseMaybeUnary(refExpressionErrors) {
  8981. if (!this.hasPlugin("jsx") && this.match(43)) {
  8982. return this.tsParseTypeAssertion();
  8983. } else {
  8984. return super.parseMaybeUnary(refExpressionErrors);
  8985. }
  8986. }
  8987. parseArrow(node) {
  8988. if (this.match(14)) {
  8989. const result = this.tryParse(abort => {
  8990. const returnType = this.tsParseTypeOrTypePredicateAnnotation(14);
  8991. if (this.canInsertSemicolon() || !this.match(19)) abort();
  8992. return returnType;
  8993. });
  8994. if (result.aborted) return;
  8995. if (!result.thrown) {
  8996. if (result.error) this.state = result.failState;
  8997. node.returnType = result.node;
  8998. }
  8999. }
  9000. return super.parseArrow(node);
  9001. }
  9002. parseAssignableListItemTypes(param) {
  9003. if (this.eat(17)) {
  9004. if (param.type !== "Identifier" && !this.state.isAmbientContext && !this.state.inType) {
  9005. this.raise(param.start, TSErrors.PatternIsOptional);
  9006. }
  9007. param.optional = true;
  9008. }
  9009. const type = this.tsTryParseTypeAnnotation();
  9010. if (type) param.typeAnnotation = type;
  9011. this.resetEndLocation(param);
  9012. return param;
  9013. }
  9014. isAssignable(node, isBinding) {
  9015. switch (node.type) {
  9016. case "TSTypeCastExpression":
  9017. return this.isAssignable(node.expression, isBinding);
  9018. case "TSParameterProperty":
  9019. return true;
  9020. default:
  9021. return super.isAssignable(node, isBinding);
  9022. }
  9023. }
  9024. toAssignable(node, isLHS = false) {
  9025. switch (node.type) {
  9026. case "TSTypeCastExpression":
  9027. return super.toAssignable(this.typeCastToParameter(node), isLHS);
  9028. case "TSParameterProperty":
  9029. return super.toAssignable(node, isLHS);
  9030. case "ParenthesizedExpression":
  9031. return this.toAssignableParenthesizedExpression(node, isLHS);
  9032. case "TSAsExpression":
  9033. case "TSNonNullExpression":
  9034. case "TSTypeAssertion":
  9035. node.expression = this.toAssignable(node.expression, isLHS);
  9036. return node;
  9037. default:
  9038. return super.toAssignable(node, isLHS);
  9039. }
  9040. }
  9041. toAssignableParenthesizedExpression(node, isLHS) {
  9042. switch (node.expression.type) {
  9043. case "TSAsExpression":
  9044. case "TSNonNullExpression":
  9045. case "TSTypeAssertion":
  9046. case "ParenthesizedExpression":
  9047. node.expression = this.toAssignable(node.expression, isLHS);
  9048. return node;
  9049. default:
  9050. return super.toAssignable(node, isLHS);
  9051. }
  9052. }
  9053. checkLVal(expr, contextDescription, ...args) {
  9054. var _expr$extra2;
  9055. switch (expr.type) {
  9056. case "TSTypeCastExpression":
  9057. return;
  9058. case "TSParameterProperty":
  9059. this.checkLVal(expr.parameter, "parameter property", ...args);
  9060. return;
  9061. case "TSAsExpression":
  9062. case "TSTypeAssertion":
  9063. if (!args[0] && contextDescription !== "parenthesized expression" && !((_expr$extra2 = expr.extra) != null && _expr$extra2.parenthesized)) {
  9064. this.raise(expr.start, ErrorMessages.InvalidLhs, contextDescription);
  9065. break;
  9066. }
  9067. this.checkLVal(expr.expression, "parenthesized expression", ...args);
  9068. return;
  9069. case "TSNonNullExpression":
  9070. this.checkLVal(expr.expression, contextDescription, ...args);
  9071. return;
  9072. default:
  9073. super.checkLVal(expr, contextDescription, ...args);
  9074. return;
  9075. }
  9076. }
  9077. parseBindingAtom() {
  9078. switch (this.state.type) {
  9079. case 72:
  9080. return this.parseIdentifier(true);
  9081. default:
  9082. return super.parseBindingAtom();
  9083. }
  9084. }
  9085. parseMaybeDecoratorArguments(expr) {
  9086. if (this.match(43)) {
  9087. const typeArguments = this.tsParseTypeArguments();
  9088. if (this.match(10)) {
  9089. const call = super.parseMaybeDecoratorArguments(expr);
  9090. call.typeParameters = typeArguments;
  9091. return call;
  9092. }
  9093. this.unexpected(this.state.start, 10);
  9094. }
  9095. return super.parseMaybeDecoratorArguments(expr);
  9096. }
  9097. checkCommaAfterRest(close) {
  9098. if (this.state.isAmbientContext && this.match(12) && this.lookaheadCharCode() === close) {
  9099. this.next();
  9100. } else {
  9101. super.checkCommaAfterRest(close);
  9102. }
  9103. }
  9104. isClassMethod() {
  9105. return this.match(43) || super.isClassMethod();
  9106. }
  9107. isClassProperty() {
  9108. return this.match(33) || this.match(14) || super.isClassProperty();
  9109. }
  9110. parseMaybeDefault(...args) {
  9111. const node = super.parseMaybeDefault(...args);
  9112. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  9113. this.raise(node.typeAnnotation.start, TSErrors.TypeAnnotationAfterAssign);
  9114. }
  9115. return node;
  9116. }
  9117. getTokenFromCode(code) {
  9118. if (this.state.inType) {
  9119. if (code === 62) {
  9120. return this.finishOp(44, 1);
  9121. }
  9122. if (code === 60) {
  9123. return this.finishOp(43, 1);
  9124. }
  9125. }
  9126. return super.getTokenFromCode(code);
  9127. }
  9128. reScan_lt_gt() {
  9129. const {
  9130. type
  9131. } = this.state;
  9132. if (type === 43) {
  9133. this.state.pos -= 1;
  9134. this.readToken_lt();
  9135. } else if (type === 44) {
  9136. this.state.pos -= 1;
  9137. this.readToken_gt();
  9138. }
  9139. }
  9140. toAssignableList(exprList) {
  9141. for (let i = 0; i < exprList.length; i++) {
  9142. const expr = exprList[i];
  9143. if (!expr) continue;
  9144. switch (expr.type) {
  9145. case "TSTypeCastExpression":
  9146. exprList[i] = this.typeCastToParameter(expr);
  9147. break;
  9148. case "TSAsExpression":
  9149. case "TSTypeAssertion":
  9150. if (!this.state.maybeInArrowParameters) {
  9151. exprList[i] = this.typeCastToParameter(expr);
  9152. } else {
  9153. this.raise(expr.start, TSErrors.UnexpectedTypeCastInParameter);
  9154. }
  9155. break;
  9156. }
  9157. }
  9158. return super.toAssignableList(...arguments);
  9159. }
  9160. typeCastToParameter(node) {
  9161. node.expression.typeAnnotation = node.typeAnnotation;
  9162. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  9163. return node.expression;
  9164. }
  9165. shouldParseArrow(params) {
  9166. if (this.match(14)) {
  9167. return params.every(expr => this.isAssignable(expr, true));
  9168. }
  9169. return super.shouldParseArrow(params);
  9170. }
  9171. shouldParseAsyncArrow() {
  9172. return this.match(14) || super.shouldParseAsyncArrow();
  9173. }
  9174. canHaveLeadingDecorator() {
  9175. return super.canHaveLeadingDecorator() || this.isAbstractClass();
  9176. }
  9177. jsxParseOpeningElementAfterName(node) {
  9178. if (this.match(43)) {
  9179. const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArguments());
  9180. if (typeArguments) node.typeParameters = typeArguments;
  9181. }
  9182. return super.jsxParseOpeningElementAfterName(node);
  9183. }
  9184. getGetterSetterExpectedParamCount(method) {
  9185. const baseCount = super.getGetterSetterExpectedParamCount(method);
  9186. const params = this.getObjectOrClassMethodParams(method);
  9187. const firstParam = params[0];
  9188. const hasContextParam = firstParam && this.isThisParam(firstParam);
  9189. return hasContextParam ? baseCount + 1 : baseCount;
  9190. }
  9191. parseCatchClauseParam() {
  9192. const param = super.parseCatchClauseParam();
  9193. const type = this.tsTryParseTypeAnnotation();
  9194. if (type) {
  9195. param.typeAnnotation = type;
  9196. this.resetEndLocation(param);
  9197. }
  9198. return param;
  9199. }
  9200. tsInAmbientContext(cb) {
  9201. const oldIsAmbientContext = this.state.isAmbientContext;
  9202. this.state.isAmbientContext = true;
  9203. try {
  9204. return cb();
  9205. } finally {
  9206. this.state.isAmbientContext = oldIsAmbientContext;
  9207. }
  9208. }
  9209. parseClass(node, ...args) {
  9210. const oldInAbstractClass = this.state.inAbstractClass;
  9211. this.state.inAbstractClass = !!node.abstract;
  9212. try {
  9213. return super.parseClass(node, ...args);
  9214. } finally {
  9215. this.state.inAbstractClass = oldInAbstractClass;
  9216. }
  9217. }
  9218. tsParseAbstractDeclaration(node) {
  9219. if (this.match(74)) {
  9220. node.abstract = true;
  9221. return this.parseClass(node, true, false);
  9222. } else if (this.isContextual(119)) {
  9223. if (!this.hasFollowingLineBreak()) {
  9224. node.abstract = true;
  9225. this.raise(node.start, TSErrors.NonClassMethodPropertyHasAbstractModifer);
  9226. this.next();
  9227. return this.tsParseInterfaceDeclaration(node);
  9228. }
  9229. } else {
  9230. this.unexpected(null, 74);
  9231. }
  9232. }
  9233. parseMethod(...args) {
  9234. const method = super.parseMethod(...args);
  9235. if (method.abstract) {
  9236. const hasBody = this.hasPlugin("estree") ? !!method.value.body : !!method.body;
  9237. if (hasBody) {
  9238. const {
  9239. key
  9240. } = method;
  9241. this.raise(method.start, TSErrors.AbstractMethodHasImplementation, key.type === "Identifier" && !method.computed ? key.name : `[${this.input.slice(key.start, key.end)}]`);
  9242. }
  9243. }
  9244. return method;
  9245. }
  9246. tsParseTypeParameterName() {
  9247. const typeName = this.parseIdentifier();
  9248. return typeName.name;
  9249. }
  9250. shouldParseAsAmbientContext() {
  9251. return !!this.getPluginOption("typescript", "dts");
  9252. }
  9253. parse() {
  9254. if (this.shouldParseAsAmbientContext()) {
  9255. this.state.isAmbientContext = true;
  9256. }
  9257. return super.parse();
  9258. }
  9259. getExpression() {
  9260. if (this.shouldParseAsAmbientContext()) {
  9261. this.state.isAmbientContext = true;
  9262. }
  9263. return super.getExpression();
  9264. }
  9265. parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) {
  9266. if (!isString && isMaybeTypeOnly) {
  9267. this.parseTypeOnlyImportExportSpecifier(node, false, isInTypeExport);
  9268. return this.finishNode(node, "ExportSpecifier");
  9269. }
  9270. node.exportKind = "value";
  9271. return super.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly);
  9272. }
  9273. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly) {
  9274. if (!importedIsString && isMaybeTypeOnly) {
  9275. this.parseTypeOnlyImportExportSpecifier(specifier, true, isInTypeOnlyImport);
  9276. return this.finishNode(specifier, "ImportSpecifier");
  9277. }
  9278. specifier.importKind = "value";
  9279. return super.parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly);
  9280. }
  9281. parseTypeOnlyImportExportSpecifier(node, isImport, isInTypeOnlyImportExport) {
  9282. const leftOfAsKey = isImport ? "imported" : "local";
  9283. const rightOfAsKey = isImport ? "local" : "exported";
  9284. let leftOfAs = node[leftOfAsKey];
  9285. let rightOfAs;
  9286. let hasTypeSpecifier = false;
  9287. let canParseAsKeyword = true;
  9288. const pos = leftOfAs.start;
  9289. if (this.isContextual(87)) {
  9290. const firstAs = this.parseIdentifier();
  9291. if (this.isContextual(87)) {
  9292. const secondAs = this.parseIdentifier();
  9293. if (tokenIsKeywordOrIdentifier(this.state.type)) {
  9294. hasTypeSpecifier = true;
  9295. leftOfAs = firstAs;
  9296. rightOfAs = this.parseIdentifier();
  9297. canParseAsKeyword = false;
  9298. } else {
  9299. rightOfAs = secondAs;
  9300. canParseAsKeyword = false;
  9301. }
  9302. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  9303. canParseAsKeyword = false;
  9304. rightOfAs = this.parseIdentifier();
  9305. } else {
  9306. hasTypeSpecifier = true;
  9307. leftOfAs = firstAs;
  9308. }
  9309. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  9310. hasTypeSpecifier = true;
  9311. leftOfAs = this.parseIdentifier();
  9312. }
  9313. if (hasTypeSpecifier && isInTypeOnlyImportExport) {
  9314. this.raise(pos, isImport ? TSErrors.TypeModifierIsUsedInTypeImports : TSErrors.TypeModifierIsUsedInTypeExports);
  9315. }
  9316. node[leftOfAsKey] = leftOfAs;
  9317. node[rightOfAsKey] = rightOfAs;
  9318. const kindKey = isImport ? "importKind" : "exportKind";
  9319. node[kindKey] = hasTypeSpecifier ? "type" : "value";
  9320. if (canParseAsKeyword && this.eatContextual(87)) {
  9321. node[rightOfAsKey] = isImport ? this.parseIdentifier() : this.parseModuleExportName();
  9322. }
  9323. if (!node[rightOfAsKey]) {
  9324. node[rightOfAsKey] = cloneIdentifier(node[leftOfAsKey]);
  9325. }
  9326. if (isImport) {
  9327. this.checkLVal(node[rightOfAsKey], "import specifier", BIND_LEXICAL);
  9328. }
  9329. }
  9330. });
  9331. const PlaceHolderErrors = makeErrorTemplates({
  9332. ClassNameIsRequired: "A class name is required."
  9333. }, ErrorCodes.SyntaxError);
  9334. var placeholders = (superClass => class extends superClass {
  9335. parsePlaceholder(expectedNode) {
  9336. if (this.match(134)) {
  9337. const node = this.startNode();
  9338. this.next();
  9339. this.assertNoSpace("Unexpected space in placeholder.");
  9340. node.name = super.parseIdentifier(true);
  9341. this.assertNoSpace("Unexpected space in placeholder.");
  9342. this.expect(134);
  9343. return this.finishPlaceholder(node, expectedNode);
  9344. }
  9345. }
  9346. finishPlaceholder(node, expectedNode) {
  9347. const isFinished = !!(node.expectedNode && node.type === "Placeholder");
  9348. node.expectedNode = expectedNode;
  9349. return isFinished ? node : this.finishNode(node, "Placeholder");
  9350. }
  9351. getTokenFromCode(code) {
  9352. if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) {
  9353. return this.finishOp(134, 2);
  9354. }
  9355. return super.getTokenFromCode(...arguments);
  9356. }
  9357. parseExprAtom() {
  9358. return this.parsePlaceholder("Expression") || super.parseExprAtom(...arguments);
  9359. }
  9360. parseIdentifier() {
  9361. return this.parsePlaceholder("Identifier") || super.parseIdentifier(...arguments);
  9362. }
  9363. checkReservedWord(word) {
  9364. if (word !== undefined) super.checkReservedWord(...arguments);
  9365. }
  9366. parseBindingAtom() {
  9367. return this.parsePlaceholder("Pattern") || super.parseBindingAtom(...arguments);
  9368. }
  9369. checkLVal(expr) {
  9370. if (expr.type !== "Placeholder") super.checkLVal(...arguments);
  9371. }
  9372. toAssignable(node) {
  9373. if (node && node.type === "Placeholder" && node.expectedNode === "Expression") {
  9374. node.expectedNode = "Pattern";
  9375. return node;
  9376. }
  9377. return super.toAssignable(...arguments);
  9378. }
  9379. isLet(context) {
  9380. if (super.isLet(context)) {
  9381. return true;
  9382. }
  9383. if (!this.isContextual(93)) {
  9384. return false;
  9385. }
  9386. if (context) return false;
  9387. const nextToken = this.lookahead();
  9388. if (nextToken.type === 134) {
  9389. return true;
  9390. }
  9391. return false;
  9392. }
  9393. verifyBreakContinue(node) {
  9394. if (node.label && node.label.type === "Placeholder") return;
  9395. super.verifyBreakContinue(...arguments);
  9396. }
  9397. parseExpressionStatement(node, expr) {
  9398. if (expr.type !== "Placeholder" || expr.extra && expr.extra.parenthesized) {
  9399. return super.parseExpressionStatement(...arguments);
  9400. }
  9401. if (this.match(14)) {
  9402. const stmt = node;
  9403. stmt.label = this.finishPlaceholder(expr, "Identifier");
  9404. this.next();
  9405. stmt.body = this.parseStatement("label");
  9406. return this.finishNode(stmt, "LabeledStatement");
  9407. }
  9408. this.semicolon();
  9409. node.name = expr.name;
  9410. return this.finishPlaceholder(node, "Statement");
  9411. }
  9412. parseBlock() {
  9413. return this.parsePlaceholder("BlockStatement") || super.parseBlock(...arguments);
  9414. }
  9415. parseFunctionId() {
  9416. return this.parsePlaceholder("Identifier") || super.parseFunctionId(...arguments);
  9417. }
  9418. parseClass(node, isStatement, optionalId) {
  9419. const type = isStatement ? "ClassDeclaration" : "ClassExpression";
  9420. this.next();
  9421. this.takeDecorators(node);
  9422. const oldStrict = this.state.strict;
  9423. const placeholder = this.parsePlaceholder("Identifier");
  9424. if (placeholder) {
  9425. if (this.match(75) || this.match(134) || this.match(5)) {
  9426. node.id = placeholder;
  9427. } else if (optionalId || !isStatement) {
  9428. node.id = null;
  9429. node.body = this.finishPlaceholder(placeholder, "ClassBody");
  9430. return this.finishNode(node, type);
  9431. } else {
  9432. this.unexpected(null, PlaceHolderErrors.ClassNameIsRequired);
  9433. }
  9434. } else {
  9435. this.parseClassId(node, isStatement, optionalId);
  9436. }
  9437. this.parseClassSuper(node);
  9438. node.body = this.parsePlaceholder("ClassBody") || this.parseClassBody(!!node.superClass, oldStrict);
  9439. return this.finishNode(node, type);
  9440. }
  9441. parseExport(node) {
  9442. const placeholder = this.parsePlaceholder("Identifier");
  9443. if (!placeholder) return super.parseExport(...arguments);
  9444. if (!this.isContextual(91) && !this.match(12)) {
  9445. node.specifiers = [];
  9446. node.source = null;
  9447. node.declaration = this.finishPlaceholder(placeholder, "Declaration");
  9448. return this.finishNode(node, "ExportNamedDeclaration");
  9449. }
  9450. this.expectPlugin("exportDefaultFrom");
  9451. const specifier = this.startNode();
  9452. specifier.exported = placeholder;
  9453. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  9454. return super.parseExport(node);
  9455. }
  9456. isExportDefaultSpecifier() {
  9457. if (this.match(59)) {
  9458. const next = this.nextTokenStart();
  9459. if (this.isUnparsedContextual(next, "from")) {
  9460. if (this.input.startsWith(tokenLabelName(134), this.nextTokenStartSince(next + 4))) {
  9461. return true;
  9462. }
  9463. }
  9464. }
  9465. return super.isExportDefaultSpecifier();
  9466. }
  9467. maybeParseExportDefaultSpecifier(node) {
  9468. if (node.specifiers && node.specifiers.length > 0) {
  9469. return true;
  9470. }
  9471. return super.maybeParseExportDefaultSpecifier(...arguments);
  9472. }
  9473. checkExport(node) {
  9474. const {
  9475. specifiers
  9476. } = node;
  9477. if (specifiers != null && specifiers.length) {
  9478. node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder");
  9479. }
  9480. super.checkExport(node);
  9481. node.specifiers = specifiers;
  9482. }
  9483. parseImport(node) {
  9484. const placeholder = this.parsePlaceholder("Identifier");
  9485. if (!placeholder) return super.parseImport(...arguments);
  9486. node.specifiers = [];
  9487. if (!this.isContextual(91) && !this.match(12)) {
  9488. node.source = this.finishPlaceholder(placeholder, "StringLiteral");
  9489. this.semicolon();
  9490. return this.finishNode(node, "ImportDeclaration");
  9491. }
  9492. const specifier = this.startNodeAtNode(placeholder);
  9493. specifier.local = placeholder;
  9494. this.finishNode(specifier, "ImportDefaultSpecifier");
  9495. node.specifiers.push(specifier);
  9496. if (this.eat(12)) {
  9497. const hasStarImport = this.maybeParseStarImportSpecifier(node);
  9498. if (!hasStarImport) this.parseNamedImportSpecifiers(node);
  9499. }
  9500. this.expectContextual(91);
  9501. node.source = this.parseImportSource();
  9502. this.semicolon();
  9503. return this.finishNode(node, "ImportDeclaration");
  9504. }
  9505. parseImportSource() {
  9506. return this.parsePlaceholder("StringLiteral") || super.parseImportSource(...arguments);
  9507. }
  9508. });
  9509. var v8intrinsic = (superClass => class extends superClass {
  9510. parseV8Intrinsic() {
  9511. if (this.match(48)) {
  9512. const v8IntrinsicStart = this.state.start;
  9513. const node = this.startNode();
  9514. this.next();
  9515. if (tokenIsIdentifier(this.state.type)) {
  9516. const name = this.parseIdentifierName(this.state.start);
  9517. const identifier = this.createIdentifier(node, name);
  9518. identifier.type = "V8IntrinsicIdentifier";
  9519. if (this.match(10)) {
  9520. return identifier;
  9521. }
  9522. }
  9523. this.unexpected(v8IntrinsicStart);
  9524. }
  9525. }
  9526. parseExprAtom() {
  9527. return this.parseV8Intrinsic() || super.parseExprAtom(...arguments);
  9528. }
  9529. });
  9530. function hasPlugin(plugins, name) {
  9531. return plugins.some(plugin => {
  9532. if (Array.isArray(plugin)) {
  9533. return plugin[0] === name;
  9534. } else {
  9535. return plugin === name;
  9536. }
  9537. });
  9538. }
  9539. function getPluginOption(plugins, name, option) {
  9540. const plugin = plugins.find(plugin => {
  9541. if (Array.isArray(plugin)) {
  9542. return plugin[0] === name;
  9543. } else {
  9544. return plugin === name;
  9545. }
  9546. });
  9547. if (plugin && Array.isArray(plugin)) {
  9548. return plugin[1][option];
  9549. }
  9550. return null;
  9551. }
  9552. const PIPELINE_PROPOSALS = ["minimal", "fsharp", "hack", "smart"];
  9553. const TOPIC_TOKENS = ["^", "%", "#"];
  9554. const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"];
  9555. function validatePlugins(plugins) {
  9556. if (hasPlugin(plugins, "decorators")) {
  9557. if (hasPlugin(plugins, "decorators-legacy")) {
  9558. throw new Error("Cannot use the decorators and decorators-legacy plugin together");
  9559. }
  9560. const decoratorsBeforeExport = getPluginOption(plugins, "decorators", "decoratorsBeforeExport");
  9561. if (decoratorsBeforeExport == null) {
  9562. 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'.");
  9563. } else if (typeof decoratorsBeforeExport !== "boolean") {
  9564. throw new Error("'decoratorsBeforeExport' must be a boolean.");
  9565. }
  9566. }
  9567. if (hasPlugin(plugins, "flow") && hasPlugin(plugins, "typescript")) {
  9568. throw new Error("Cannot combine flow and typescript plugins.");
  9569. }
  9570. if (hasPlugin(plugins, "placeholders") && hasPlugin(plugins, "v8intrinsic")) {
  9571. throw new Error("Cannot combine placeholders and v8intrinsic plugins.");
  9572. }
  9573. if (hasPlugin(plugins, "pipelineOperator")) {
  9574. const proposal = getPluginOption(plugins, "pipelineOperator", "proposal");
  9575. if (!PIPELINE_PROPOSALS.includes(proposal)) {
  9576. const proposalList = PIPELINE_PROPOSALS.map(p => `"${p}"`).join(", ");
  9577. throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${proposalList}.`);
  9578. }
  9579. const tupleSyntaxIsHash = hasPlugin(plugins, "recordAndTuple") && getPluginOption(plugins, "recordAndTuple", "syntaxType") === "hash";
  9580. if (proposal === "hack") {
  9581. if (hasPlugin(plugins, "placeholders")) {
  9582. throw new Error("Cannot combine placeholders plugin and Hack-style pipes.");
  9583. }
  9584. if (hasPlugin(plugins, "v8intrinsic")) {
  9585. throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes.");
  9586. }
  9587. const topicToken = getPluginOption(plugins, "pipelineOperator", "topicToken");
  9588. if (!TOPIC_TOKENS.includes(topicToken)) {
  9589. const tokenList = TOPIC_TOKENS.map(t => `"${t}"`).join(", ");
  9590. throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${tokenList}.`);
  9591. }
  9592. if (topicToken === "#" && tupleSyntaxIsHash) {
  9593. throw new Error('Plugin conflict between `["pipelineOperator", { proposal: "hack", topicToken: "#" }]` and `["recordAndtuple", { syntaxType: "hash"}]`.');
  9594. }
  9595. } else if (proposal === "smart" && tupleSyntaxIsHash) {
  9596. throw new Error('Plugin conflict between `["pipelineOperator", { proposal: "smart" }]` and `["recordAndtuple", { syntaxType: "hash"}]`.');
  9597. }
  9598. }
  9599. if (hasPlugin(plugins, "moduleAttributes")) {
  9600. {
  9601. if (hasPlugin(plugins, "importAssertions")) {
  9602. throw new Error("Cannot combine importAssertions and moduleAttributes plugins.");
  9603. }
  9604. const moduleAttributesVerionPluginOption = getPluginOption(plugins, "moduleAttributes", "version");
  9605. if (moduleAttributesVerionPluginOption !== "may-2020") {
  9606. throw new Error("The 'moduleAttributes' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is 'may-2020'.");
  9607. }
  9608. }
  9609. }
  9610. if (hasPlugin(plugins, "recordAndTuple") && !RECORD_AND_TUPLE_SYNTAX_TYPES.includes(getPluginOption(plugins, "recordAndTuple", "syntaxType"))) {
  9611. throw new Error("'recordAndTuple' requires 'syntaxType' option whose value should be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", "));
  9612. }
  9613. if (hasPlugin(plugins, "asyncDoExpressions") && !hasPlugin(plugins, "doExpressions")) {
  9614. const error = new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins.");
  9615. error.missingPlugins = "doExpressions";
  9616. throw error;
  9617. }
  9618. }
  9619. const mixinPlugins = {
  9620. estree,
  9621. jsx,
  9622. flow,
  9623. typescript,
  9624. v8intrinsic,
  9625. placeholders
  9626. };
  9627. const mixinPluginNames = Object.keys(mixinPlugins);
  9628. const defaultOptions = {
  9629. sourceType: "script",
  9630. sourceFilename: undefined,
  9631. startColumn: 0,
  9632. startLine: 1,
  9633. allowAwaitOutsideFunction: false,
  9634. allowReturnOutsideFunction: false,
  9635. allowImportExportEverywhere: false,
  9636. allowSuperOutsideMethod: false,
  9637. allowUndeclaredExports: false,
  9638. plugins: [],
  9639. strictMode: null,
  9640. ranges: false,
  9641. tokens: false,
  9642. createParenthesizedExpressions: false,
  9643. errorRecovery: false,
  9644. attachComment: true
  9645. };
  9646. function getOptions(opts) {
  9647. const options = {};
  9648. for (const key of Object.keys(defaultOptions)) {
  9649. options[key] = opts && opts[key] != null ? opts[key] : defaultOptions[key];
  9650. }
  9651. return options;
  9652. }
  9653. const unwrapParenthesizedExpression = node => {
  9654. return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node;
  9655. };
  9656. class LValParser extends NodeUtils {
  9657. toAssignable(node, isLHS = false) {
  9658. var _node$extra, _node$extra3;
  9659. let parenthesized = undefined;
  9660. if (node.type === "ParenthesizedExpression" || (_node$extra = node.extra) != null && _node$extra.parenthesized) {
  9661. parenthesized = unwrapParenthesizedExpression(node);
  9662. if (isLHS) {
  9663. if (parenthesized.type === "Identifier") {
  9664. this.expressionScope.recordParenthesizedIdentifierError(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  9665. } else if (parenthesized.type !== "MemberExpression") {
  9666. this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  9667. }
  9668. } else {
  9669. this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  9670. }
  9671. }
  9672. switch (node.type) {
  9673. case "Identifier":
  9674. case "ObjectPattern":
  9675. case "ArrayPattern":
  9676. case "AssignmentPattern":
  9677. case "RestElement":
  9678. break;
  9679. case "ObjectExpression":
  9680. node.type = "ObjectPattern";
  9681. for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) {
  9682. var _node$extra2;
  9683. const prop = node.properties[i];
  9684. const isLast = i === last;
  9685. this.toAssignableObjectExpressionProp(prop, isLast, isLHS);
  9686. if (isLast && prop.type === "RestElement" && (_node$extra2 = node.extra) != null && _node$extra2.trailingComma) {
  9687. this.raiseRestNotLast(node.extra.trailingComma);
  9688. }
  9689. }
  9690. break;
  9691. case "ObjectProperty":
  9692. this.toAssignable(node.value, isLHS);
  9693. break;
  9694. case "SpreadElement":
  9695. {
  9696. this.checkToRestConversion(node);
  9697. node.type = "RestElement";
  9698. const arg = node.argument;
  9699. this.toAssignable(arg, isLHS);
  9700. break;
  9701. }
  9702. case "ArrayExpression":
  9703. node.type = "ArrayPattern";
  9704. this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingComma, isLHS);
  9705. break;
  9706. case "AssignmentExpression":
  9707. if (node.operator !== "=") {
  9708. this.raise(node.left.end, ErrorMessages.MissingEqInAssignment);
  9709. }
  9710. node.type = "AssignmentPattern";
  9711. delete node.operator;
  9712. this.toAssignable(node.left, isLHS);
  9713. break;
  9714. case "ParenthesizedExpression":
  9715. this.toAssignable(parenthesized, isLHS);
  9716. break;
  9717. }
  9718. return node;
  9719. }
  9720. toAssignableObjectExpressionProp(prop, isLast, isLHS) {
  9721. if (prop.type === "ObjectMethod") {
  9722. const error = prop.kind === "get" || prop.kind === "set" ? ErrorMessages.PatternHasAccessor : ErrorMessages.PatternHasMethod;
  9723. this.raise(prop.key.start, error);
  9724. } else if (prop.type === "SpreadElement" && !isLast) {
  9725. this.raiseRestNotLast(prop.start);
  9726. } else {
  9727. this.toAssignable(prop, isLHS);
  9728. }
  9729. }
  9730. toAssignableList(exprList, trailingCommaPos, isLHS) {
  9731. let end = exprList.length;
  9732. if (end) {
  9733. const last = exprList[end - 1];
  9734. if ((last == null ? void 0 : last.type) === "RestElement") {
  9735. --end;
  9736. } else if ((last == null ? void 0 : last.type) === "SpreadElement") {
  9737. last.type = "RestElement";
  9738. let arg = last.argument;
  9739. this.toAssignable(arg, isLHS);
  9740. arg = unwrapParenthesizedExpression(arg);
  9741. if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern" && arg.type !== "ObjectPattern") {
  9742. this.unexpected(arg.start);
  9743. }
  9744. if (trailingCommaPos) {
  9745. this.raiseTrailingCommaAfterRest(trailingCommaPos);
  9746. }
  9747. --end;
  9748. }
  9749. }
  9750. for (let i = 0; i < end; i++) {
  9751. const elt = exprList[i];
  9752. if (elt) {
  9753. this.toAssignable(elt, isLHS);
  9754. if (elt.type === "RestElement") {
  9755. this.raiseRestNotLast(elt.start);
  9756. }
  9757. }
  9758. }
  9759. return exprList;
  9760. }
  9761. isAssignable(node, isBinding) {
  9762. switch (node.type) {
  9763. case "Identifier":
  9764. case "ObjectPattern":
  9765. case "ArrayPattern":
  9766. case "AssignmentPattern":
  9767. case "RestElement":
  9768. return true;
  9769. case "ObjectExpression":
  9770. {
  9771. const last = node.properties.length - 1;
  9772. return node.properties.every((prop, i) => {
  9773. return prop.type !== "ObjectMethod" && (i === last || prop.type !== "SpreadElement") && this.isAssignable(prop);
  9774. });
  9775. }
  9776. case "ObjectProperty":
  9777. return this.isAssignable(node.value);
  9778. case "SpreadElement":
  9779. return this.isAssignable(node.argument);
  9780. case "ArrayExpression":
  9781. return node.elements.every(element => element === null || this.isAssignable(element));
  9782. case "AssignmentExpression":
  9783. return node.operator === "=";
  9784. case "ParenthesizedExpression":
  9785. return this.isAssignable(node.expression);
  9786. case "MemberExpression":
  9787. case "OptionalMemberExpression":
  9788. return !isBinding;
  9789. default:
  9790. return false;
  9791. }
  9792. }
  9793. toReferencedList(exprList, isParenthesizedExpr) {
  9794. return exprList;
  9795. }
  9796. toReferencedListDeep(exprList, isParenthesizedExpr) {
  9797. this.toReferencedList(exprList, isParenthesizedExpr);
  9798. for (const expr of exprList) {
  9799. if ((expr == null ? void 0 : expr.type) === "ArrayExpression") {
  9800. this.toReferencedListDeep(expr.elements);
  9801. }
  9802. }
  9803. }
  9804. parseSpread(refExpressionErrors, refNeedsArrowPos) {
  9805. const node = this.startNode();
  9806. this.next();
  9807. node.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, undefined, refNeedsArrowPos);
  9808. return this.finishNode(node, "SpreadElement");
  9809. }
  9810. parseRestBinding() {
  9811. const node = this.startNode();
  9812. this.next();
  9813. node.argument = this.parseBindingAtom();
  9814. return this.finishNode(node, "RestElement");
  9815. }
  9816. parseBindingAtom() {
  9817. switch (this.state.type) {
  9818. case 0:
  9819. {
  9820. const node = this.startNode();
  9821. this.next();
  9822. node.elements = this.parseBindingList(3, 93, true);
  9823. return this.finishNode(node, "ArrayPattern");
  9824. }
  9825. case 5:
  9826. return this.parseObjectLike(8, true);
  9827. }
  9828. return this.parseIdentifier();
  9829. }
  9830. parseBindingList(close, closeCharCode, allowEmpty, allowModifiers) {
  9831. const elts = [];
  9832. let first = true;
  9833. while (!this.eat(close)) {
  9834. if (first) {
  9835. first = false;
  9836. } else {
  9837. this.expect(12);
  9838. }
  9839. if (allowEmpty && this.match(12)) {
  9840. elts.push(null);
  9841. } else if (this.eat(close)) {
  9842. break;
  9843. } else if (this.match(21)) {
  9844. elts.push(this.parseAssignableListItemTypes(this.parseRestBinding()));
  9845. this.checkCommaAfterRest(closeCharCode);
  9846. this.expect(close);
  9847. break;
  9848. } else {
  9849. const decorators = [];
  9850. if (this.match(24) && this.hasPlugin("decorators")) {
  9851. this.raise(this.state.start, ErrorMessages.UnsupportedParameterDecorator);
  9852. }
  9853. while (this.match(24)) {
  9854. decorators.push(this.parseDecorator());
  9855. }
  9856. elts.push(this.parseAssignableListItem(allowModifiers, decorators));
  9857. }
  9858. }
  9859. return elts;
  9860. }
  9861. parseBindingRestProperty(prop) {
  9862. this.next();
  9863. prop.argument = this.parseIdentifier();
  9864. this.checkCommaAfterRest(125);
  9865. return this.finishNode(prop, "RestElement");
  9866. }
  9867. parseBindingProperty() {
  9868. const prop = this.startNode();
  9869. const {
  9870. type,
  9871. start: startPos,
  9872. startLoc
  9873. } = this.state;
  9874. if (type === 21) {
  9875. return this.parseBindingRestProperty(prop);
  9876. } else {
  9877. this.parsePropertyName(prop);
  9878. }
  9879. prop.method = false;
  9880. this.parseObjPropValue(prop, startPos, startLoc, false, false, true, false);
  9881. return prop;
  9882. }
  9883. parseAssignableListItem(allowModifiers, decorators) {
  9884. const left = this.parseMaybeDefault();
  9885. this.parseAssignableListItemTypes(left);
  9886. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  9887. if (decorators.length) {
  9888. left.decorators = decorators;
  9889. }
  9890. return elt;
  9891. }
  9892. parseAssignableListItemTypes(param) {
  9893. return param;
  9894. }
  9895. parseMaybeDefault(startPos, startLoc, left) {
  9896. var _startLoc, _startPos, _left;
  9897. startLoc = (_startLoc = startLoc) != null ? _startLoc : this.state.startLoc;
  9898. startPos = (_startPos = startPos) != null ? _startPos : this.state.start;
  9899. left = (_left = left) != null ? _left : this.parseBindingAtom();
  9900. if (!this.eat(27)) return left;
  9901. const node = this.startNodeAt(startPos, startLoc);
  9902. node.left = left;
  9903. node.right = this.parseMaybeAssignAllowIn();
  9904. return this.finishNode(node, "AssignmentPattern");
  9905. }
  9906. checkLVal(expr, contextDescription, bindingType = BIND_NONE, checkClashes, disallowLetBinding, strictModeChanged = false) {
  9907. switch (expr.type) {
  9908. case "Identifier":
  9909. {
  9910. const {
  9911. name
  9912. } = expr;
  9913. if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(name, this.inModule) : isStrictBindOnlyReservedWord(name))) {
  9914. this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.StrictEvalArguments : ErrorMessages.StrictEvalArgumentsBinding, name);
  9915. }
  9916. if (checkClashes) {
  9917. if (checkClashes.has(name)) {
  9918. this.raise(expr.start, ErrorMessages.ParamDupe);
  9919. } else {
  9920. checkClashes.add(name);
  9921. }
  9922. }
  9923. if (disallowLetBinding && name === "let") {
  9924. this.raise(expr.start, ErrorMessages.LetInLexicalBinding);
  9925. }
  9926. if (!(bindingType & BIND_NONE)) {
  9927. this.scope.declareName(name, bindingType, expr.start);
  9928. }
  9929. break;
  9930. }
  9931. case "MemberExpression":
  9932. if (bindingType !== BIND_NONE) {
  9933. this.raise(expr.start, ErrorMessages.InvalidPropertyBindingPattern);
  9934. }
  9935. break;
  9936. case "ObjectPattern":
  9937. for (let prop of expr.properties) {
  9938. if (this.isObjectProperty(prop)) prop = prop.value;else if (this.isObjectMethod(prop)) continue;
  9939. this.checkLVal(prop, "object destructuring pattern", bindingType, checkClashes, disallowLetBinding);
  9940. }
  9941. break;
  9942. case "ArrayPattern":
  9943. for (const elem of expr.elements) {
  9944. if (elem) {
  9945. this.checkLVal(elem, "array destructuring pattern", bindingType, checkClashes, disallowLetBinding);
  9946. }
  9947. }
  9948. break;
  9949. case "AssignmentPattern":
  9950. this.checkLVal(expr.left, "assignment pattern", bindingType, checkClashes);
  9951. break;
  9952. case "RestElement":
  9953. this.checkLVal(expr.argument, "rest element", bindingType, checkClashes);
  9954. break;
  9955. case "ParenthesizedExpression":
  9956. this.checkLVal(expr.expression, "parenthesized expression", bindingType, checkClashes);
  9957. break;
  9958. default:
  9959. {
  9960. this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.InvalidLhs : ErrorMessages.InvalidLhsBinding, contextDescription);
  9961. }
  9962. }
  9963. }
  9964. checkToRestConversion(node) {
  9965. if (node.argument.type !== "Identifier" && node.argument.type !== "MemberExpression") {
  9966. this.raise(node.argument.start, ErrorMessages.InvalidRestAssignmentPattern);
  9967. }
  9968. }
  9969. checkCommaAfterRest(close) {
  9970. if (this.match(12)) {
  9971. if (this.lookaheadCharCode() === close) {
  9972. this.raiseTrailingCommaAfterRest(this.state.start);
  9973. } else {
  9974. this.raiseRestNotLast(this.state.start);
  9975. }
  9976. }
  9977. }
  9978. raiseRestNotLast(pos) {
  9979. throw this.raise(pos, ErrorMessages.ElementAfterRest);
  9980. }
  9981. raiseTrailingCommaAfterRest(pos) {
  9982. this.raise(pos, ErrorMessages.RestTrailingComma);
  9983. }
  9984. }
  9985. const invalidHackPipeBodies = new Map([["ArrowFunctionExpression", "arrow function"], ["AssignmentExpression", "assignment"], ["ConditionalExpression", "conditional"], ["YieldExpression", "yield"]]);
  9986. class ExpressionParser extends LValParser {
  9987. checkProto(prop, isRecord, protoRef, refExpressionErrors) {
  9988. if (prop.type === "SpreadElement" || this.isObjectMethod(prop) || prop.computed || prop.shorthand) {
  9989. return;
  9990. }
  9991. const key = prop.key;
  9992. const name = key.type === "Identifier" ? key.name : key.value;
  9993. if (name === "__proto__") {
  9994. if (isRecord) {
  9995. this.raise(key.start, ErrorMessages.RecordNoProto);
  9996. return;
  9997. }
  9998. if (protoRef.used) {
  9999. if (refExpressionErrors) {
  10000. if (refExpressionErrors.doubleProto === -1) {
  10001. refExpressionErrors.doubleProto = key.start;
  10002. }
  10003. } else {
  10004. this.raise(key.start, ErrorMessages.DuplicateProto);
  10005. }
  10006. }
  10007. protoRef.used = true;
  10008. }
  10009. }
  10010. shouldExitDescending(expr, potentialArrowAt) {
  10011. return expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt;
  10012. }
  10013. getExpression() {
  10014. this.enterInitialScopes();
  10015. this.nextToken();
  10016. const expr = this.parseExpression();
  10017. if (!this.match(129)) {
  10018. this.unexpected();
  10019. }
  10020. this.finalizeRemainingComments();
  10021. expr.comments = this.state.comments;
  10022. expr.errors = this.state.errors;
  10023. if (this.options.tokens) {
  10024. expr.tokens = this.tokens;
  10025. }
  10026. return expr;
  10027. }
  10028. parseExpression(disallowIn, refExpressionErrors) {
  10029. if (disallowIn) {
  10030. return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  10031. }
  10032. return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  10033. }
  10034. parseExpressionBase(refExpressionErrors) {
  10035. const startPos = this.state.start;
  10036. const startLoc = this.state.startLoc;
  10037. const expr = this.parseMaybeAssign(refExpressionErrors);
  10038. if (this.match(12)) {
  10039. const node = this.startNodeAt(startPos, startLoc);
  10040. node.expressions = [expr];
  10041. while (this.eat(12)) {
  10042. node.expressions.push(this.parseMaybeAssign(refExpressionErrors));
  10043. }
  10044. this.toReferencedList(node.expressions);
  10045. return this.finishNode(node, "SequenceExpression");
  10046. }
  10047. return expr;
  10048. }
  10049. parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse) {
  10050. return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse));
  10051. }
  10052. parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse) {
  10053. return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse));
  10054. }
  10055. setOptionalParametersError(refExpressionErrors, resultError) {
  10056. var _resultError$pos;
  10057. refExpressionErrors.optionalParameters = (_resultError$pos = resultError == null ? void 0 : resultError.pos) != null ? _resultError$pos : this.state.start;
  10058. }
  10059. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  10060. const startPos = this.state.start;
  10061. const startLoc = this.state.startLoc;
  10062. if (this.isContextual(99)) {
  10063. if (this.prodParam.hasYield) {
  10064. let left = this.parseYield();
  10065. if (afterLeftParse) {
  10066. left = afterLeftParse.call(this, left, startPos, startLoc);
  10067. }
  10068. return left;
  10069. }
  10070. }
  10071. let ownExpressionErrors;
  10072. if (refExpressionErrors) {
  10073. ownExpressionErrors = false;
  10074. } else {
  10075. refExpressionErrors = new ExpressionErrors();
  10076. ownExpressionErrors = true;
  10077. }
  10078. const {
  10079. type
  10080. } = this.state;
  10081. if (type === 10 || tokenIsIdentifier(type)) {
  10082. this.state.potentialArrowAt = this.state.start;
  10083. }
  10084. let left = this.parseMaybeConditional(refExpressionErrors);
  10085. if (afterLeftParse) {
  10086. left = afterLeftParse.call(this, left, startPos, startLoc);
  10087. }
  10088. if (tokenIsAssignment(this.state.type)) {
  10089. const node = this.startNodeAt(startPos, startLoc);
  10090. const operator = this.state.value;
  10091. node.operator = operator;
  10092. if (this.match(27)) {
  10093. node.left = this.toAssignable(left, true);
  10094. if (refExpressionErrors.doubleProto >= startPos) {
  10095. refExpressionErrors.doubleProto = -1;
  10096. }
  10097. if (refExpressionErrors.shorthandAssign >= startPos) {
  10098. refExpressionErrors.shorthandAssign = -1;
  10099. }
  10100. } else {
  10101. node.left = left;
  10102. }
  10103. this.checkLVal(left, "assignment expression");
  10104. this.next();
  10105. node.right = this.parseMaybeAssign();
  10106. return this.finishNode(node, "AssignmentExpression");
  10107. } else if (ownExpressionErrors) {
  10108. this.checkExpressionErrors(refExpressionErrors, true);
  10109. }
  10110. return left;
  10111. }
  10112. parseMaybeConditional(refExpressionErrors) {
  10113. const startPos = this.state.start;
  10114. const startLoc = this.state.startLoc;
  10115. const potentialArrowAt = this.state.potentialArrowAt;
  10116. const expr = this.parseExprOps(refExpressionErrors);
  10117. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  10118. return expr;
  10119. }
  10120. return this.parseConditional(expr, startPos, startLoc, refExpressionErrors);
  10121. }
  10122. parseConditional(expr, startPos, startLoc, refExpressionErrors) {
  10123. if (this.eat(17)) {
  10124. const node = this.startNodeAt(startPos, startLoc);
  10125. node.test = expr;
  10126. node.consequent = this.parseMaybeAssignAllowIn();
  10127. this.expect(14);
  10128. node.alternate = this.parseMaybeAssign();
  10129. return this.finishNode(node, "ConditionalExpression");
  10130. }
  10131. return expr;
  10132. }
  10133. parseMaybeUnaryOrPrivate(refExpressionErrors) {
  10134. return this.match(128) ? this.parsePrivateName() : this.parseMaybeUnary(refExpressionErrors);
  10135. }
  10136. parseExprOps(refExpressionErrors) {
  10137. const startPos = this.state.start;
  10138. const startLoc = this.state.startLoc;
  10139. const potentialArrowAt = this.state.potentialArrowAt;
  10140. const expr = this.parseMaybeUnaryOrPrivate(refExpressionErrors);
  10141. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  10142. return expr;
  10143. }
  10144. return this.parseExprOp(expr, startPos, startLoc, -1);
  10145. }
  10146. parseExprOp(left, leftStartPos, leftStartLoc, minPrec) {
  10147. if (this.isPrivateName(left)) {
  10148. const value = this.getPrivateNameSV(left);
  10149. const {
  10150. start
  10151. } = left;
  10152. if (minPrec >= tokenOperatorPrecedence(52) || !this.prodParam.hasIn || !this.match(52)) {
  10153. this.raise(start, ErrorMessages.PrivateInExpectedIn, value);
  10154. }
  10155. this.classScope.usePrivateName(value, start);
  10156. }
  10157. const op = this.state.type;
  10158. if (tokenIsOperator(op) && (this.prodParam.hasIn || !this.match(52))) {
  10159. let prec = tokenOperatorPrecedence(op);
  10160. if (prec > minPrec) {
  10161. if (op === 35) {
  10162. this.expectPlugin("pipelineOperator");
  10163. if (this.state.inFSharpPipelineDirectBody) {
  10164. return left;
  10165. }
  10166. this.checkPipelineAtInfixOperator(left, leftStartPos);
  10167. }
  10168. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  10169. node.left = left;
  10170. node.operator = this.state.value;
  10171. const logical = op === 37 || op === 38;
  10172. const coalesce = op === 36;
  10173. if (coalesce) {
  10174. prec = tokenOperatorPrecedence(38);
  10175. }
  10176. this.next();
  10177. if (op === 35 && this.getPluginOption("pipelineOperator", "proposal") === "minimal") {
  10178. if (this.state.type === 90 && this.prodParam.hasAwait) {
  10179. throw this.raise(this.state.start, ErrorMessages.UnexpectedAwaitAfterPipelineBody);
  10180. }
  10181. }
  10182. node.right = this.parseExprOpRightExpr(op, prec);
  10183. this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression");
  10184. const nextOp = this.state.type;
  10185. if (coalesce && (nextOp === 37 || nextOp === 38) || logical && nextOp === 36) {
  10186. throw this.raise(this.state.start, ErrorMessages.MixingCoalesceWithLogical);
  10187. }
  10188. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec);
  10189. }
  10190. }
  10191. return left;
  10192. }
  10193. parseExprOpRightExpr(op, prec) {
  10194. const startPos = this.state.start;
  10195. const startLoc = this.state.startLoc;
  10196. switch (op) {
  10197. case 35:
  10198. switch (this.getPluginOption("pipelineOperator", "proposal")) {
  10199. case "hack":
  10200. return this.withTopicBindingContext(() => {
  10201. return this.parseHackPipeBody();
  10202. });
  10203. case "smart":
  10204. return this.withTopicBindingContext(() => {
  10205. if (this.prodParam.hasYield && this.isContextual(99)) {
  10206. throw this.raise(this.state.start, ErrorMessages.PipeBodyIsTighter, this.state.value);
  10207. }
  10208. return this.parseSmartPipelineBodyInStyle(this.parseExprOpBaseRightExpr(op, prec), startPos, startLoc);
  10209. });
  10210. case "fsharp":
  10211. return this.withSoloAwaitPermittingContext(() => {
  10212. return this.parseFSharpPipelineBody(prec);
  10213. });
  10214. }
  10215. default:
  10216. return this.parseExprOpBaseRightExpr(op, prec);
  10217. }
  10218. }
  10219. parseExprOpBaseRightExpr(op, prec) {
  10220. const startPos = this.state.start;
  10221. const startLoc = this.state.startLoc;
  10222. return this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startPos, startLoc, tokenIsRightAssociative(op) ? prec - 1 : prec);
  10223. }
  10224. parseHackPipeBody() {
  10225. var _body$extra;
  10226. const {
  10227. start
  10228. } = this.state;
  10229. const body = this.parseMaybeAssign();
  10230. if (invalidHackPipeBodies.has(body.type) && !((_body$extra = body.extra) != null && _body$extra.parenthesized)) {
  10231. this.raise(start, ErrorMessages.PipeUnparenthesizedBody, invalidHackPipeBodies.get(body.type));
  10232. }
  10233. if (!this.topicReferenceWasUsedInCurrentContext()) {
  10234. this.raise(start, ErrorMessages.PipeTopicUnused);
  10235. }
  10236. return body;
  10237. }
  10238. checkExponentialAfterUnary(node) {
  10239. if (this.match(51)) {
  10240. this.raise(node.argument.start, ErrorMessages.UnexpectedTokenUnaryExponentiation);
  10241. }
  10242. }
  10243. parseMaybeUnary(refExpressionErrors, sawUnary) {
  10244. const startPos = this.state.start;
  10245. const startLoc = this.state.startLoc;
  10246. const isAwait = this.isContextual(90);
  10247. if (isAwait && this.isAwaitAllowed()) {
  10248. this.next();
  10249. const expr = this.parseAwait(startPos, startLoc);
  10250. if (!sawUnary) this.checkExponentialAfterUnary(expr);
  10251. return expr;
  10252. }
  10253. const update = this.match(32);
  10254. const node = this.startNode();
  10255. if (tokenIsPrefix(this.state.type)) {
  10256. node.operator = this.state.value;
  10257. node.prefix = true;
  10258. if (this.match(66)) {
  10259. this.expectPlugin("throwExpressions");
  10260. }
  10261. const isDelete = this.match(83);
  10262. this.next();
  10263. node.argument = this.parseMaybeUnary(null, true);
  10264. this.checkExpressionErrors(refExpressionErrors, true);
  10265. if (this.state.strict && isDelete) {
  10266. const arg = node.argument;
  10267. if (arg.type === "Identifier") {
  10268. this.raise(node.start, ErrorMessages.StrictDelete);
  10269. } else if (this.hasPropertyAsPrivateName(arg)) {
  10270. this.raise(node.start, ErrorMessages.DeletePrivateField);
  10271. }
  10272. }
  10273. if (!update) {
  10274. if (!sawUnary) this.checkExponentialAfterUnary(node);
  10275. return this.finishNode(node, "UnaryExpression");
  10276. }
  10277. }
  10278. const expr = this.parseUpdate(node, update, refExpressionErrors);
  10279. if (isAwait) {
  10280. const {
  10281. type
  10282. } = this.state;
  10283. const startsExpr = this.hasPlugin("v8intrinsic") ? tokenCanStartExpression(type) : tokenCanStartExpression(type) && !this.match(48);
  10284. if (startsExpr && !this.isAmbiguousAwait()) {
  10285. this.raiseOverwrite(startPos, ErrorMessages.AwaitNotInAsyncContext);
  10286. return this.parseAwait(startPos, startLoc);
  10287. }
  10288. }
  10289. return expr;
  10290. }
  10291. parseUpdate(node, update, refExpressionErrors) {
  10292. if (update) {
  10293. this.checkLVal(node.argument, "prefix operation");
  10294. return this.finishNode(node, "UpdateExpression");
  10295. }
  10296. const startPos = this.state.start;
  10297. const startLoc = this.state.startLoc;
  10298. let expr = this.parseExprSubscripts(refExpressionErrors);
  10299. if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
  10300. while (tokenIsPostfix(this.state.type) && !this.canInsertSemicolon()) {
  10301. const node = this.startNodeAt(startPos, startLoc);
  10302. node.operator = this.state.value;
  10303. node.prefix = false;
  10304. node.argument = expr;
  10305. this.checkLVal(expr, "postfix operation");
  10306. this.next();
  10307. expr = this.finishNode(node, "UpdateExpression");
  10308. }
  10309. return expr;
  10310. }
  10311. parseExprSubscripts(refExpressionErrors) {
  10312. const startPos = this.state.start;
  10313. const startLoc = this.state.startLoc;
  10314. const potentialArrowAt = this.state.potentialArrowAt;
  10315. const expr = this.parseExprAtom(refExpressionErrors);
  10316. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  10317. return expr;
  10318. }
  10319. return this.parseSubscripts(expr, startPos, startLoc);
  10320. }
  10321. parseSubscripts(base, startPos, startLoc, noCalls) {
  10322. const state = {
  10323. optionalChainMember: false,
  10324. maybeAsyncArrow: this.atPossibleAsyncArrow(base),
  10325. stop: false
  10326. };
  10327. do {
  10328. base = this.parseSubscript(base, startPos, startLoc, noCalls, state);
  10329. state.maybeAsyncArrow = false;
  10330. } while (!state.stop);
  10331. return base;
  10332. }
  10333. parseSubscript(base, startPos, startLoc, noCalls, state) {
  10334. if (!noCalls && this.eat(15)) {
  10335. return this.parseBind(base, startPos, startLoc, noCalls, state);
  10336. } else if (this.match(22)) {
  10337. return this.parseTaggedTemplateExpression(base, startPos, startLoc, state);
  10338. }
  10339. let optional = false;
  10340. if (this.match(18)) {
  10341. if (noCalls && this.lookaheadCharCode() === 40) {
  10342. state.stop = true;
  10343. return base;
  10344. }
  10345. state.optionalChainMember = optional = true;
  10346. this.next();
  10347. }
  10348. if (!noCalls && this.match(10)) {
  10349. return this.parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional);
  10350. } else {
  10351. const computed = this.eat(0);
  10352. if (computed || optional || this.eat(16)) {
  10353. return this.parseMember(base, startPos, startLoc, state, computed, optional);
  10354. } else {
  10355. state.stop = true;
  10356. return base;
  10357. }
  10358. }
  10359. }
  10360. parseMember(base, startPos, startLoc, state, computed, optional) {
  10361. const node = this.startNodeAt(startPos, startLoc);
  10362. node.object = base;
  10363. node.computed = computed;
  10364. const privateName = !computed && this.match(128) && this.state.value;
  10365. const property = computed ? this.parseExpression() : privateName ? this.parsePrivateName() : this.parseIdentifier(true);
  10366. if (privateName !== false) {
  10367. if (node.object.type === "Super") {
  10368. this.raise(startPos, ErrorMessages.SuperPrivateField);
  10369. }
  10370. this.classScope.usePrivateName(privateName, property.start);
  10371. }
  10372. node.property = property;
  10373. if (computed) {
  10374. this.expect(3);
  10375. }
  10376. if (state.optionalChainMember) {
  10377. node.optional = optional;
  10378. return this.finishNode(node, "OptionalMemberExpression");
  10379. } else {
  10380. return this.finishNode(node, "MemberExpression");
  10381. }
  10382. }
  10383. parseBind(base, startPos, startLoc, noCalls, state) {
  10384. const node = this.startNodeAt(startPos, startLoc);
  10385. node.object = base;
  10386. node.callee = this.parseNoCallExpr();
  10387. state.stop = true;
  10388. return this.parseSubscripts(this.finishNode(node, "BindExpression"), startPos, startLoc, noCalls);
  10389. }
  10390. parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional) {
  10391. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  10392. let refExpressionErrors = null;
  10393. this.state.maybeInArrowParameters = true;
  10394. this.next();
  10395. let node = this.startNodeAt(startPos, startLoc);
  10396. node.callee = base;
  10397. if (state.maybeAsyncArrow) {
  10398. this.expressionScope.enter(newAsyncArrowScope());
  10399. refExpressionErrors = new ExpressionErrors();
  10400. }
  10401. if (state.optionalChainMember) {
  10402. node.optional = optional;
  10403. }
  10404. if (optional) {
  10405. node.arguments = this.parseCallExpressionArguments(11);
  10406. } else {
  10407. node.arguments = this.parseCallExpressionArguments(11, base.type === "Import", base.type !== "Super", node, refExpressionErrors);
  10408. }
  10409. this.finishCallExpression(node, state.optionalChainMember);
  10410. if (state.maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {
  10411. state.stop = true;
  10412. this.expressionScope.validateAsPattern();
  10413. this.expressionScope.exit();
  10414. node = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startPos, startLoc), node);
  10415. } else {
  10416. if (state.maybeAsyncArrow) {
  10417. this.checkExpressionErrors(refExpressionErrors, true);
  10418. this.expressionScope.exit();
  10419. }
  10420. this.toReferencedArguments(node);
  10421. }
  10422. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  10423. return node;
  10424. }
  10425. toReferencedArguments(node, isParenthesizedExpr) {
  10426. this.toReferencedListDeep(node.arguments, isParenthesizedExpr);
  10427. }
  10428. parseTaggedTemplateExpression(base, startPos, startLoc, state) {
  10429. const node = this.startNodeAt(startPos, startLoc);
  10430. node.tag = base;
  10431. node.quasi = this.parseTemplate(true);
  10432. if (state.optionalChainMember) {
  10433. this.raise(startPos, ErrorMessages.OptionalChainingNoTemplate);
  10434. }
  10435. return this.finishNode(node, "TaggedTemplateExpression");
  10436. }
  10437. atPossibleAsyncArrow(base) {
  10438. return base.type === "Identifier" && base.name === "async" && this.state.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && base.start === this.state.potentialArrowAt;
  10439. }
  10440. finishCallExpression(node, optional) {
  10441. if (node.callee.type === "Import") {
  10442. if (node.arguments.length === 2) {
  10443. {
  10444. if (!this.hasPlugin("moduleAttributes")) {
  10445. this.expectPlugin("importAssertions");
  10446. }
  10447. }
  10448. }
  10449. if (node.arguments.length === 0 || node.arguments.length > 2) {
  10450. this.raise(node.start, ErrorMessages.ImportCallArity, this.hasPlugin("importAssertions") || this.hasPlugin("moduleAttributes") ? "one or two arguments" : "one argument");
  10451. } else {
  10452. for (const arg of node.arguments) {
  10453. if (arg.type === "SpreadElement") {
  10454. this.raise(arg.start, ErrorMessages.ImportCallSpreadArgument);
  10455. }
  10456. }
  10457. }
  10458. }
  10459. return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression");
  10460. }
  10461. parseCallExpressionArguments(close, dynamicImport, allowPlaceholder, nodeForExtra, refExpressionErrors) {
  10462. const elts = [];
  10463. let first = true;
  10464. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  10465. this.state.inFSharpPipelineDirectBody = false;
  10466. while (!this.eat(close)) {
  10467. if (first) {
  10468. first = false;
  10469. } else {
  10470. this.expect(12);
  10471. if (this.match(close)) {
  10472. if (dynamicImport && !this.hasPlugin("importAssertions") && !this.hasPlugin("moduleAttributes")) {
  10473. this.raise(this.state.lastTokStart, ErrorMessages.ImportCallArgumentTrailingComma);
  10474. }
  10475. if (nodeForExtra) {
  10476. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  10477. }
  10478. this.next();
  10479. break;
  10480. }
  10481. }
  10482. elts.push(this.parseExprListItem(false, refExpressionErrors, allowPlaceholder));
  10483. }
  10484. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  10485. return elts;
  10486. }
  10487. shouldParseAsyncArrow() {
  10488. return this.match(19) && !this.canInsertSemicolon();
  10489. }
  10490. parseAsyncArrowFromCallExpression(node, call) {
  10491. var _call$extra;
  10492. this.resetPreviousNodeTrailingComments(call);
  10493. this.expect(19);
  10494. this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingComma);
  10495. if (call.innerComments) {
  10496. setInnerComments(node, call.innerComments);
  10497. }
  10498. if (call.callee.trailingComments) {
  10499. setInnerComments(node, call.callee.trailingComments);
  10500. }
  10501. return node;
  10502. }
  10503. parseNoCallExpr() {
  10504. const startPos = this.state.start;
  10505. const startLoc = this.state.startLoc;
  10506. return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  10507. }
  10508. parseExprAtom(refExpressionErrors) {
  10509. let node;
  10510. const {
  10511. type
  10512. } = this.state;
  10513. switch (type) {
  10514. case 73:
  10515. return this.parseSuper();
  10516. case 77:
  10517. node = this.startNode();
  10518. this.next();
  10519. if (this.match(16)) {
  10520. return this.parseImportMetaProperty(node);
  10521. }
  10522. if (!this.match(10)) {
  10523. this.raise(this.state.lastTokStart, ErrorMessages.UnsupportedImport);
  10524. }
  10525. return this.finishNode(node, "Import");
  10526. case 72:
  10527. node = this.startNode();
  10528. this.next();
  10529. return this.finishNode(node, "ThisExpression");
  10530. case 84:
  10531. {
  10532. return this.parseDo(this.startNode(), false);
  10533. }
  10534. case 50:
  10535. case 29:
  10536. {
  10537. this.readRegexp();
  10538. return this.parseRegExpLiteral(this.state.value);
  10539. }
  10540. case 124:
  10541. return this.parseNumericLiteral(this.state.value);
  10542. case 125:
  10543. return this.parseBigIntLiteral(this.state.value);
  10544. case 126:
  10545. return this.parseDecimalLiteral(this.state.value);
  10546. case 123:
  10547. return this.parseStringLiteral(this.state.value);
  10548. case 78:
  10549. return this.parseNullLiteral();
  10550. case 79:
  10551. return this.parseBooleanLiteral(true);
  10552. case 80:
  10553. return this.parseBooleanLiteral(false);
  10554. case 10:
  10555. {
  10556. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  10557. return this.parseParenAndDistinguishExpression(canBeArrow);
  10558. }
  10559. case 2:
  10560. case 1:
  10561. {
  10562. return this.parseArrayLike(this.state.type === 2 ? 4 : 3, false, true);
  10563. }
  10564. case 0:
  10565. {
  10566. return this.parseArrayLike(3, true, false, refExpressionErrors);
  10567. }
  10568. case 6:
  10569. case 7:
  10570. {
  10571. return this.parseObjectLike(this.state.type === 6 ? 9 : 8, false, true);
  10572. }
  10573. case 5:
  10574. {
  10575. return this.parseObjectLike(8, false, false, refExpressionErrors);
  10576. }
  10577. case 62:
  10578. return this.parseFunctionOrFunctionSent();
  10579. case 24:
  10580. this.parseDecorators();
  10581. case 74:
  10582. node = this.startNode();
  10583. this.takeDecorators(node);
  10584. return this.parseClass(node, false);
  10585. case 71:
  10586. return this.parseNewOrNewTarget();
  10587. case 22:
  10588. return this.parseTemplate(false);
  10589. case 15:
  10590. {
  10591. node = this.startNode();
  10592. this.next();
  10593. node.object = null;
  10594. const callee = node.callee = this.parseNoCallExpr();
  10595. if (callee.type === "MemberExpression") {
  10596. return this.finishNode(node, "BindExpression");
  10597. } else {
  10598. throw this.raise(callee.start, ErrorMessages.UnsupportedBind);
  10599. }
  10600. }
  10601. case 128:
  10602. {
  10603. this.raise(this.state.start, ErrorMessages.PrivateInExpectedIn, this.state.value);
  10604. return this.parsePrivateName();
  10605. }
  10606. case 31:
  10607. {
  10608. return this.parseTopicReferenceThenEqualsSign(48, "%");
  10609. }
  10610. case 30:
  10611. {
  10612. return this.parseTopicReferenceThenEqualsSign(40, "^");
  10613. }
  10614. case 40:
  10615. case 48:
  10616. case 25:
  10617. {
  10618. const pipeProposal = this.getPluginOption("pipelineOperator", "proposal");
  10619. if (pipeProposal) {
  10620. return this.parseTopicReference(pipeProposal);
  10621. } else {
  10622. throw this.unexpected();
  10623. }
  10624. }
  10625. case 43:
  10626. {
  10627. const lookaheadCh = this.input.codePointAt(this.nextTokenStart());
  10628. if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) {
  10629. this.expectOnePlugin(["jsx", "flow", "typescript"]);
  10630. break;
  10631. } else {
  10632. throw this.unexpected();
  10633. }
  10634. }
  10635. default:
  10636. if (tokenIsIdentifier(type)) {
  10637. if (this.isContextual(117) && this.lookaheadCharCode() === 123 && !this.hasFollowingLineBreak()) {
  10638. return this.parseModuleExpression();
  10639. }
  10640. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  10641. const containsEsc = this.state.containsEsc;
  10642. const id = this.parseIdentifier();
  10643. if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) {
  10644. const {
  10645. type
  10646. } = this.state;
  10647. if (type === 62) {
  10648. this.resetPreviousNodeTrailingComments(id);
  10649. this.next();
  10650. return this.parseFunction(this.startNodeAtNode(id), undefined, true);
  10651. } else if (tokenIsIdentifier(type)) {
  10652. if (this.lookaheadCharCode() === 61) {
  10653. return this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(id));
  10654. } else {
  10655. return id;
  10656. }
  10657. } else if (type === 84) {
  10658. this.resetPreviousNodeTrailingComments(id);
  10659. return this.parseDo(this.startNodeAtNode(id), true);
  10660. }
  10661. }
  10662. if (canBeArrow && this.match(19) && !this.canInsertSemicolon()) {
  10663. this.next();
  10664. return this.parseArrowExpression(this.startNodeAtNode(id), [id], false);
  10665. }
  10666. return id;
  10667. } else {
  10668. throw this.unexpected();
  10669. }
  10670. }
  10671. }
  10672. parseTopicReferenceThenEqualsSign(topicTokenType, topicTokenValue) {
  10673. const pipeProposal = this.getPluginOption("pipelineOperator", "proposal");
  10674. if (pipeProposal) {
  10675. this.state.type = topicTokenType;
  10676. this.state.value = topicTokenValue;
  10677. this.state.pos--;
  10678. this.state.end--;
  10679. this.state.endLoc.column--;
  10680. return this.parseTopicReference(pipeProposal);
  10681. } else {
  10682. throw this.unexpected();
  10683. }
  10684. }
  10685. parseTopicReference(pipeProposal) {
  10686. const node = this.startNode();
  10687. const start = this.state.start;
  10688. const tokenType = this.state.type;
  10689. this.next();
  10690. return this.finishTopicReference(node, start, pipeProposal, tokenType);
  10691. }
  10692. finishTopicReference(node, start, pipeProposal, tokenType) {
  10693. if (this.testTopicReferenceConfiguration(pipeProposal, start, tokenType)) {
  10694. let nodeType;
  10695. if (pipeProposal === "smart") {
  10696. nodeType = "PipelinePrimaryTopicReference";
  10697. } else {
  10698. nodeType = "TopicReference";
  10699. }
  10700. if (!this.topicReferenceIsAllowedInCurrentContext()) {
  10701. if (pipeProposal === "smart") {
  10702. this.raise(start, ErrorMessages.PrimaryTopicNotAllowed);
  10703. } else {
  10704. this.raise(start, ErrorMessages.PipeTopicUnbound);
  10705. }
  10706. }
  10707. this.registerTopicReference();
  10708. return this.finishNode(node, nodeType);
  10709. } else {
  10710. throw this.raise(start, ErrorMessages.PipeTopicUnconfiguredToken, tokenLabelName(tokenType));
  10711. }
  10712. }
  10713. testTopicReferenceConfiguration(pipeProposal, start, tokenType) {
  10714. switch (pipeProposal) {
  10715. case "hack":
  10716. {
  10717. const pluginTopicToken = this.getPluginOption("pipelineOperator", "topicToken");
  10718. return tokenLabelName(tokenType) === pluginTopicToken;
  10719. }
  10720. case "smart":
  10721. return tokenType === 25;
  10722. default:
  10723. throw this.raise(start, ErrorMessages.PipeTopicRequiresHackPipes);
  10724. }
  10725. }
  10726. parseAsyncArrowUnaryFunction(node) {
  10727. this.prodParam.enter(functionFlags(true, this.prodParam.hasYield));
  10728. const params = [this.parseIdentifier()];
  10729. this.prodParam.exit();
  10730. if (this.hasPrecedingLineBreak()) {
  10731. this.raise(this.state.pos, ErrorMessages.LineTerminatorBeforeArrow);
  10732. }
  10733. this.expect(19);
  10734. this.parseArrowExpression(node, params, true);
  10735. return node;
  10736. }
  10737. parseDo(node, isAsync) {
  10738. this.expectPlugin("doExpressions");
  10739. if (isAsync) {
  10740. this.expectPlugin("asyncDoExpressions");
  10741. }
  10742. node.async = isAsync;
  10743. this.next();
  10744. const oldLabels = this.state.labels;
  10745. this.state.labels = [];
  10746. if (isAsync) {
  10747. this.prodParam.enter(PARAM_AWAIT);
  10748. node.body = this.parseBlock();
  10749. this.prodParam.exit();
  10750. } else {
  10751. node.body = this.parseBlock();
  10752. }
  10753. this.state.labels = oldLabels;
  10754. return this.finishNode(node, "DoExpression");
  10755. }
  10756. parseSuper() {
  10757. const node = this.startNode();
  10758. this.next();
  10759. if (this.match(10) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) {
  10760. this.raise(node.start, ErrorMessages.SuperNotAllowed);
  10761. } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) {
  10762. this.raise(node.start, ErrorMessages.UnexpectedSuper);
  10763. }
  10764. if (!this.match(10) && !this.match(0) && !this.match(16)) {
  10765. this.raise(node.start, ErrorMessages.UnsupportedSuper);
  10766. }
  10767. return this.finishNode(node, "Super");
  10768. }
  10769. parsePrivateName() {
  10770. const node = this.startNode();
  10771. const id = this.startNodeAt(this.state.start + 1, new Position(this.state.curLine, this.state.start + 1 - this.state.lineStart));
  10772. const name = this.state.value;
  10773. this.next();
  10774. node.id = this.createIdentifier(id, name);
  10775. return this.finishNode(node, "PrivateName");
  10776. }
  10777. parseFunctionOrFunctionSent() {
  10778. const node = this.startNode();
  10779. this.next();
  10780. if (this.prodParam.hasYield && this.match(16)) {
  10781. const meta = this.createIdentifier(this.startNodeAtNode(node), "function");
  10782. this.next();
  10783. if (this.match(96)) {
  10784. this.expectPlugin("functionSent");
  10785. } else if (!this.hasPlugin("functionSent")) {
  10786. this.unexpected();
  10787. }
  10788. return this.parseMetaProperty(node, meta, "sent");
  10789. }
  10790. return this.parseFunction(node);
  10791. }
  10792. parseMetaProperty(node, meta, propertyName) {
  10793. node.meta = meta;
  10794. const containsEsc = this.state.containsEsc;
  10795. node.property = this.parseIdentifier(true);
  10796. if (node.property.name !== propertyName || containsEsc) {
  10797. this.raise(node.property.start, ErrorMessages.UnsupportedMetaProperty, meta.name, propertyName);
  10798. }
  10799. return this.finishNode(node, "MetaProperty");
  10800. }
  10801. parseImportMetaProperty(node) {
  10802. const id = this.createIdentifier(this.startNodeAtNode(node), "import");
  10803. this.next();
  10804. if (this.isContextual(94)) {
  10805. if (!this.inModule) {
  10806. this.raise(id.start, SourceTypeModuleErrorMessages.ImportMetaOutsideModule);
  10807. }
  10808. this.sawUnambiguousESM = true;
  10809. }
  10810. return this.parseMetaProperty(node, id, "meta");
  10811. }
  10812. parseLiteralAtNode(value, type, node) {
  10813. this.addExtra(node, "rawValue", value);
  10814. this.addExtra(node, "raw", this.input.slice(node.start, this.state.end));
  10815. node.value = value;
  10816. this.next();
  10817. return this.finishNode(node, type);
  10818. }
  10819. parseLiteral(value, type) {
  10820. const node = this.startNode();
  10821. return this.parseLiteralAtNode(value, type, node);
  10822. }
  10823. parseStringLiteral(value) {
  10824. return this.parseLiteral(value, "StringLiteral");
  10825. }
  10826. parseNumericLiteral(value) {
  10827. return this.parseLiteral(value, "NumericLiteral");
  10828. }
  10829. parseBigIntLiteral(value) {
  10830. return this.parseLiteral(value, "BigIntLiteral");
  10831. }
  10832. parseDecimalLiteral(value) {
  10833. return this.parseLiteral(value, "DecimalLiteral");
  10834. }
  10835. parseRegExpLiteral(value) {
  10836. const node = this.parseLiteral(value.value, "RegExpLiteral");
  10837. node.pattern = value.pattern;
  10838. node.flags = value.flags;
  10839. return node;
  10840. }
  10841. parseBooleanLiteral(value) {
  10842. const node = this.startNode();
  10843. node.value = value;
  10844. this.next();
  10845. return this.finishNode(node, "BooleanLiteral");
  10846. }
  10847. parseNullLiteral() {
  10848. const node = this.startNode();
  10849. this.next();
  10850. return this.finishNode(node, "NullLiteral");
  10851. }
  10852. parseParenAndDistinguishExpression(canBeArrow) {
  10853. const startPos = this.state.start;
  10854. const startLoc = this.state.startLoc;
  10855. let val;
  10856. this.next();
  10857. this.expressionScope.enter(newArrowHeadScope());
  10858. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  10859. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  10860. this.state.maybeInArrowParameters = true;
  10861. this.state.inFSharpPipelineDirectBody = false;
  10862. const innerStartPos = this.state.start;
  10863. const innerStartLoc = this.state.startLoc;
  10864. const exprList = [];
  10865. const refExpressionErrors = new ExpressionErrors();
  10866. let first = true;
  10867. let spreadStart;
  10868. let optionalCommaStart;
  10869. while (!this.match(11)) {
  10870. if (first) {
  10871. first = false;
  10872. } else {
  10873. this.expect(12, refExpressionErrors.optionalParameters === -1 ? null : refExpressionErrors.optionalParameters);
  10874. if (this.match(11)) {
  10875. optionalCommaStart = this.state.start;
  10876. break;
  10877. }
  10878. }
  10879. if (this.match(21)) {
  10880. const spreadNodeStartPos = this.state.start;
  10881. const spreadNodeStartLoc = this.state.startLoc;
  10882. spreadStart = this.state.start;
  10883. exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartPos, spreadNodeStartLoc));
  10884. this.checkCommaAfterRest(41);
  10885. break;
  10886. } else {
  10887. exprList.push(this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem));
  10888. }
  10889. }
  10890. const innerEndPos = this.state.lastTokEnd;
  10891. const innerEndLoc = this.state.lastTokEndLoc;
  10892. this.expect(11);
  10893. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  10894. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  10895. let arrowNode = this.startNodeAt(startPos, startLoc);
  10896. if (canBeArrow && this.shouldParseArrow(exprList) && (arrowNode = this.parseArrow(arrowNode))) {
  10897. this.expressionScope.validateAsPattern();
  10898. this.expressionScope.exit();
  10899. this.parseArrowExpression(arrowNode, exprList, false);
  10900. return arrowNode;
  10901. }
  10902. this.expressionScope.exit();
  10903. if (!exprList.length) {
  10904. this.unexpected(this.state.lastTokStart);
  10905. }
  10906. if (optionalCommaStart) this.unexpected(optionalCommaStart);
  10907. if (spreadStart) this.unexpected(spreadStart);
  10908. this.checkExpressionErrors(refExpressionErrors, true);
  10909. this.toReferencedListDeep(exprList, true);
  10910. if (exprList.length > 1) {
  10911. val = this.startNodeAt(innerStartPos, innerStartLoc);
  10912. val.expressions = exprList;
  10913. this.finishNode(val, "SequenceExpression");
  10914. this.resetEndLocation(val, innerEndPos, innerEndLoc);
  10915. } else {
  10916. val = exprList[0];
  10917. }
  10918. if (!this.options.createParenthesizedExpressions) {
  10919. this.addExtra(val, "parenthesized", true);
  10920. this.addExtra(val, "parenStart", startPos);
  10921. this.takeSurroundingComments(val, startPos, this.state.lastTokEnd);
  10922. return val;
  10923. }
  10924. const parenExpression = this.startNodeAt(startPos, startLoc);
  10925. parenExpression.expression = val;
  10926. this.finishNode(parenExpression, "ParenthesizedExpression");
  10927. return parenExpression;
  10928. }
  10929. shouldParseArrow(params) {
  10930. return !this.canInsertSemicolon();
  10931. }
  10932. parseArrow(node) {
  10933. if (this.eat(19)) {
  10934. return node;
  10935. }
  10936. }
  10937. parseParenItem(node, startPos, startLoc) {
  10938. return node;
  10939. }
  10940. parseNewOrNewTarget() {
  10941. const node = this.startNode();
  10942. this.next();
  10943. if (this.match(16)) {
  10944. const meta = this.createIdentifier(this.startNodeAtNode(node), "new");
  10945. this.next();
  10946. const metaProp = this.parseMetaProperty(node, meta, "target");
  10947. if (!this.scope.inNonArrowFunction && !this.scope.inClass) {
  10948. this.raise(metaProp.start, ErrorMessages.UnexpectedNewTarget);
  10949. }
  10950. return metaProp;
  10951. }
  10952. return this.parseNew(node);
  10953. }
  10954. parseNew(node) {
  10955. node.callee = this.parseNoCallExpr();
  10956. if (node.callee.type === "Import") {
  10957. this.raise(node.callee.start, ErrorMessages.ImportCallNotNewExpression);
  10958. } else if (this.isOptionalChain(node.callee)) {
  10959. this.raise(this.state.lastTokEnd, ErrorMessages.OptionalChainingNoNew);
  10960. } else if (this.eat(18)) {
  10961. this.raise(this.state.start, ErrorMessages.OptionalChainingNoNew);
  10962. }
  10963. this.parseNewArguments(node);
  10964. return this.finishNode(node, "NewExpression");
  10965. }
  10966. parseNewArguments(node) {
  10967. if (this.eat(10)) {
  10968. const args = this.parseExprList(11);
  10969. this.toReferencedList(args);
  10970. node.arguments = args;
  10971. } else {
  10972. node.arguments = [];
  10973. }
  10974. }
  10975. parseTemplateElement(isTagged) {
  10976. const elem = this.startNode();
  10977. if (this.state.value === null) {
  10978. if (!isTagged) {
  10979. this.raise(this.state.start + 1, ErrorMessages.InvalidEscapeSequenceTemplate);
  10980. }
  10981. }
  10982. elem.value = {
  10983. raw: this.input.slice(this.state.start, this.state.end).replace(/\r\n?/g, "\n"),
  10984. cooked: this.state.value
  10985. };
  10986. this.next();
  10987. elem.tail = this.match(22);
  10988. return this.finishNode(elem, "TemplateElement");
  10989. }
  10990. parseTemplate(isTagged) {
  10991. const node = this.startNode();
  10992. this.next();
  10993. node.expressions = [];
  10994. let curElt = this.parseTemplateElement(isTagged);
  10995. node.quasis = [curElt];
  10996. while (!curElt.tail) {
  10997. this.expect(23);
  10998. node.expressions.push(this.parseTemplateSubstitution());
  10999. this.expect(8);
  11000. node.quasis.push(curElt = this.parseTemplateElement(isTagged));
  11001. }
  11002. this.next();
  11003. return this.finishNode(node, "TemplateLiteral");
  11004. }
  11005. parseTemplateSubstitution() {
  11006. return this.parseExpression();
  11007. }
  11008. parseObjectLike(close, isPattern, isRecord, refExpressionErrors) {
  11009. if (isRecord) {
  11010. this.expectPlugin("recordAndTuple");
  11011. }
  11012. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  11013. this.state.inFSharpPipelineDirectBody = false;
  11014. const propHash = Object.create(null);
  11015. let first = true;
  11016. const node = this.startNode();
  11017. node.properties = [];
  11018. this.next();
  11019. while (!this.match(close)) {
  11020. if (first) {
  11021. first = false;
  11022. } else {
  11023. this.expect(12);
  11024. if (this.match(close)) {
  11025. this.addExtra(node, "trailingComma", this.state.lastTokStart);
  11026. break;
  11027. }
  11028. }
  11029. let prop;
  11030. if (isPattern) {
  11031. prop = this.parseBindingProperty();
  11032. } else {
  11033. prop = this.parsePropertyDefinition(refExpressionErrors);
  11034. this.checkProto(prop, isRecord, propHash, refExpressionErrors);
  11035. }
  11036. if (isRecord && !this.isObjectProperty(prop) && prop.type !== "SpreadElement") {
  11037. this.raise(prop.start, ErrorMessages.InvalidRecordProperty);
  11038. }
  11039. if (prop.shorthand) {
  11040. this.addExtra(prop, "shorthand", true);
  11041. }
  11042. node.properties.push(prop);
  11043. }
  11044. this.next();
  11045. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  11046. let type = "ObjectExpression";
  11047. if (isPattern) {
  11048. type = "ObjectPattern";
  11049. } else if (isRecord) {
  11050. type = "RecordExpression";
  11051. }
  11052. return this.finishNode(node, type);
  11053. }
  11054. maybeAsyncOrAccessorProp(prop) {
  11055. return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(0) || this.match(49));
  11056. }
  11057. parsePropertyDefinition(refExpressionErrors) {
  11058. let decorators = [];
  11059. if (this.match(24)) {
  11060. if (this.hasPlugin("decorators")) {
  11061. this.raise(this.state.start, ErrorMessages.UnsupportedPropertyDecorator);
  11062. }
  11063. while (this.match(24)) {
  11064. decorators.push(this.parseDecorator());
  11065. }
  11066. }
  11067. const prop = this.startNode();
  11068. let isAsync = false;
  11069. let isAccessor = false;
  11070. let startPos;
  11071. let startLoc;
  11072. if (this.match(21)) {
  11073. if (decorators.length) this.unexpected();
  11074. return this.parseSpread();
  11075. }
  11076. if (decorators.length) {
  11077. prop.decorators = decorators;
  11078. decorators = [];
  11079. }
  11080. prop.method = false;
  11081. if (refExpressionErrors) {
  11082. startPos = this.state.start;
  11083. startLoc = this.state.startLoc;
  11084. }
  11085. let isGenerator = this.eat(49);
  11086. this.parsePropertyNamePrefixOperator(prop);
  11087. const containsEsc = this.state.containsEsc;
  11088. const key = this.parsePropertyName(prop);
  11089. if (!isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) {
  11090. const keyName = key.name;
  11091. if (keyName === "async" && !this.hasPrecedingLineBreak()) {
  11092. isAsync = true;
  11093. this.resetPreviousNodeTrailingComments(key);
  11094. isGenerator = this.eat(49);
  11095. this.parsePropertyName(prop);
  11096. }
  11097. if (keyName === "get" || keyName === "set") {
  11098. isAccessor = true;
  11099. this.resetPreviousNodeTrailingComments(key);
  11100. prop.kind = keyName;
  11101. if (this.match(49)) {
  11102. isGenerator = true;
  11103. this.raise(this.state.pos, ErrorMessages.AccessorIsGenerator, keyName);
  11104. this.next();
  11105. }
  11106. this.parsePropertyName(prop);
  11107. }
  11108. }
  11109. this.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, false, isAccessor, refExpressionErrors);
  11110. return prop;
  11111. }
  11112. getGetterSetterExpectedParamCount(method) {
  11113. return method.kind === "get" ? 0 : 1;
  11114. }
  11115. getObjectOrClassMethodParams(method) {
  11116. return method.params;
  11117. }
  11118. checkGetterSetterParams(method) {
  11119. var _params;
  11120. const paramCount = this.getGetterSetterExpectedParamCount(method);
  11121. const params = this.getObjectOrClassMethodParams(method);
  11122. const start = method.start;
  11123. if (params.length !== paramCount) {
  11124. if (method.kind === "get") {
  11125. this.raise(start, ErrorMessages.BadGetterArity);
  11126. } else {
  11127. this.raise(start, ErrorMessages.BadSetterArity);
  11128. }
  11129. }
  11130. if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") {
  11131. this.raise(start, ErrorMessages.BadSetterRestParameter);
  11132. }
  11133. }
  11134. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  11135. if (isAccessor) {
  11136. this.parseMethod(prop, isGenerator, false, false, false, "ObjectMethod");
  11137. this.checkGetterSetterParams(prop);
  11138. return prop;
  11139. }
  11140. if (isAsync || isGenerator || this.match(10)) {
  11141. if (isPattern) this.unexpected();
  11142. prop.kind = "method";
  11143. prop.method = true;
  11144. return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod");
  11145. }
  11146. }
  11147. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  11148. prop.shorthand = false;
  11149. if (this.eat(14)) {
  11150. prop.value = isPattern ? this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssignAllowIn(refExpressionErrors);
  11151. return this.finishNode(prop, "ObjectProperty");
  11152. }
  11153. if (!prop.computed && prop.key.type === "Identifier") {
  11154. this.checkReservedWord(prop.key.name, prop.key.start, true, false);
  11155. if (isPattern) {
  11156. prop.value = this.parseMaybeDefault(startPos, startLoc, cloneIdentifier(prop.key));
  11157. } else if (this.match(27) && refExpressionErrors) {
  11158. if (refExpressionErrors.shorthandAssign === -1) {
  11159. refExpressionErrors.shorthandAssign = this.state.start;
  11160. }
  11161. prop.value = this.parseMaybeDefault(startPos, startLoc, cloneIdentifier(prop.key));
  11162. } else {
  11163. prop.value = cloneIdentifier(prop.key);
  11164. }
  11165. prop.shorthand = true;
  11166. return this.finishNode(prop, "ObjectProperty");
  11167. }
  11168. }
  11169. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  11170. const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) || this.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  11171. if (!node) this.unexpected();
  11172. return node;
  11173. }
  11174. parsePropertyName(prop) {
  11175. if (this.eat(0)) {
  11176. prop.computed = true;
  11177. prop.key = this.parseMaybeAssignAllowIn();
  11178. this.expect(3);
  11179. } else {
  11180. const {
  11181. type,
  11182. value
  11183. } = this.state;
  11184. let key;
  11185. if (tokenIsKeywordOrIdentifier(type)) {
  11186. key = this.parseIdentifier(true);
  11187. } else {
  11188. switch (type) {
  11189. case 124:
  11190. key = this.parseNumericLiteral(value);
  11191. break;
  11192. case 123:
  11193. key = this.parseStringLiteral(value);
  11194. break;
  11195. case 125:
  11196. key = this.parseBigIntLiteral(value);
  11197. break;
  11198. case 126:
  11199. key = this.parseDecimalLiteral(value);
  11200. break;
  11201. case 128:
  11202. {
  11203. const privateKeyPos = this.state.start + 1;
  11204. this.raise(privateKeyPos, ErrorMessages.UnexpectedPrivateField);
  11205. key = this.parsePrivateName();
  11206. break;
  11207. }
  11208. default:
  11209. throw this.unexpected();
  11210. }
  11211. }
  11212. prop.key = key;
  11213. if (type !== 128) {
  11214. prop.computed = false;
  11215. }
  11216. }
  11217. return prop.key;
  11218. }
  11219. initFunction(node, isAsync) {
  11220. node.id = null;
  11221. node.generator = false;
  11222. node.async = !!isAsync;
  11223. }
  11224. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  11225. this.initFunction(node, isAsync);
  11226. node.generator = !!isGenerator;
  11227. const allowModifiers = isConstructor;
  11228. this.scope.enter(SCOPE_FUNCTION | SCOPE_SUPER | (inClassScope ? SCOPE_CLASS : 0) | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  11229. this.prodParam.enter(functionFlags(isAsync, node.generator));
  11230. this.parseFunctionParams(node, allowModifiers);
  11231. this.parseFunctionBodyAndFinish(node, type, true);
  11232. this.prodParam.exit();
  11233. this.scope.exit();
  11234. return node;
  11235. }
  11236. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  11237. if (isTuple) {
  11238. this.expectPlugin("recordAndTuple");
  11239. }
  11240. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  11241. this.state.inFSharpPipelineDirectBody = false;
  11242. const node = this.startNode();
  11243. this.next();
  11244. node.elements = this.parseExprList(close, !isTuple, refExpressionErrors, node);
  11245. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  11246. return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression");
  11247. }
  11248. parseArrowExpression(node, params, isAsync, trailingCommaPos) {
  11249. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  11250. let flags = functionFlags(isAsync, false);
  11251. if (!this.match(0) && this.prodParam.hasIn) {
  11252. flags |= PARAM_IN;
  11253. }
  11254. this.prodParam.enter(flags);
  11255. this.initFunction(node, isAsync);
  11256. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  11257. if (params) {
  11258. this.state.maybeInArrowParameters = true;
  11259. this.setArrowFunctionParameters(node, params, trailingCommaPos);
  11260. }
  11261. this.state.maybeInArrowParameters = false;
  11262. this.parseFunctionBody(node, true);
  11263. this.prodParam.exit();
  11264. this.scope.exit();
  11265. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  11266. return this.finishNode(node, "ArrowFunctionExpression");
  11267. }
  11268. setArrowFunctionParameters(node, params, trailingCommaPos) {
  11269. node.params = this.toAssignableList(params, trailingCommaPos, false);
  11270. }
  11271. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  11272. this.parseFunctionBody(node, false, isMethod);
  11273. this.finishNode(node, type);
  11274. }
  11275. parseFunctionBody(node, allowExpression, isMethod = false) {
  11276. const isExpression = allowExpression && !this.match(5);
  11277. this.expressionScope.enter(newExpressionScope());
  11278. if (isExpression) {
  11279. node.body = this.parseMaybeAssign();
  11280. this.checkParams(node, false, allowExpression, false);
  11281. } else {
  11282. const oldStrict = this.state.strict;
  11283. const oldLabels = this.state.labels;
  11284. this.state.labels = [];
  11285. this.prodParam.enter(this.prodParam.currentFlags() | PARAM_RETURN);
  11286. node.body = this.parseBlock(true, false, hasStrictModeDirective => {
  11287. const nonSimple = !this.isSimpleParamList(node.params);
  11288. if (hasStrictModeDirective && nonSimple) {
  11289. const errorPos = (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.end : node.start;
  11290. this.raise(errorPos, ErrorMessages.IllegalLanguageModeDirective);
  11291. }
  11292. const strictModeChanged = !oldStrict && this.state.strict;
  11293. this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged);
  11294. if (this.state.strict && node.id) {
  11295. this.checkLVal(node.id, "function name", BIND_OUTSIDE, undefined, undefined, strictModeChanged);
  11296. }
  11297. });
  11298. this.prodParam.exit();
  11299. this.state.labels = oldLabels;
  11300. }
  11301. this.expressionScope.exit();
  11302. }
  11303. isSimpleParamList(params) {
  11304. for (let i = 0, len = params.length; i < len; i++) {
  11305. if (params[i].type !== "Identifier") return false;
  11306. }
  11307. return true;
  11308. }
  11309. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  11310. const checkClashes = new Set();
  11311. for (const param of node.params) {
  11312. this.checkLVal(param, "function parameter list", BIND_VAR, allowDuplicates ? null : checkClashes, undefined, strictModeChanged);
  11313. }
  11314. }
  11315. parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) {
  11316. const elts = [];
  11317. let first = true;
  11318. while (!this.eat(close)) {
  11319. if (first) {
  11320. first = false;
  11321. } else {
  11322. this.expect(12);
  11323. if (this.match(close)) {
  11324. if (nodeForExtra) {
  11325. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  11326. }
  11327. this.next();
  11328. break;
  11329. }
  11330. }
  11331. elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors));
  11332. }
  11333. return elts;
  11334. }
  11335. parseExprListItem(allowEmpty, refExpressionErrors, allowPlaceholder) {
  11336. let elt;
  11337. if (this.match(12)) {
  11338. if (!allowEmpty) {
  11339. this.raise(this.state.pos, ErrorMessages.UnexpectedToken, ",");
  11340. }
  11341. elt = null;
  11342. } else if (this.match(21)) {
  11343. const spreadNodeStartPos = this.state.start;
  11344. const spreadNodeStartLoc = this.state.startLoc;
  11345. elt = this.parseParenItem(this.parseSpread(refExpressionErrors), spreadNodeStartPos, spreadNodeStartLoc);
  11346. } else if (this.match(17)) {
  11347. this.expectPlugin("partialApplication");
  11348. if (!allowPlaceholder) {
  11349. this.raise(this.state.start, ErrorMessages.UnexpectedArgumentPlaceholder);
  11350. }
  11351. const node = this.startNode();
  11352. this.next();
  11353. elt = this.finishNode(node, "ArgumentPlaceholder");
  11354. } else {
  11355. elt = this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem);
  11356. }
  11357. return elt;
  11358. }
  11359. parseIdentifier(liberal) {
  11360. const node = this.startNode();
  11361. const name = this.parseIdentifierName(node.start, liberal);
  11362. return this.createIdentifier(node, name);
  11363. }
  11364. createIdentifier(node, name) {
  11365. node.name = name;
  11366. node.loc.identifierName = name;
  11367. return this.finishNode(node, "Identifier");
  11368. }
  11369. parseIdentifierName(pos, liberal) {
  11370. let name;
  11371. const {
  11372. start,
  11373. type
  11374. } = this.state;
  11375. if (tokenIsKeywordOrIdentifier(type)) {
  11376. name = this.state.value;
  11377. } else {
  11378. throw this.unexpected();
  11379. }
  11380. const tokenIsKeyword = tokenKeywordOrIdentifierIsKeyword(type);
  11381. if (liberal) {
  11382. if (tokenIsKeyword) {
  11383. this.replaceToken(122);
  11384. }
  11385. } else {
  11386. this.checkReservedWord(name, start, tokenIsKeyword, false);
  11387. }
  11388. this.next();
  11389. return name;
  11390. }
  11391. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  11392. if (word.length > 10) {
  11393. return;
  11394. }
  11395. if (!canBeReservedWord(word)) {
  11396. return;
  11397. }
  11398. if (word === "yield") {
  11399. if (this.prodParam.hasYield) {
  11400. this.raise(startLoc, ErrorMessages.YieldBindingIdentifier);
  11401. return;
  11402. }
  11403. } else if (word === "await") {
  11404. if (this.prodParam.hasAwait) {
  11405. this.raise(startLoc, ErrorMessages.AwaitBindingIdentifier);
  11406. return;
  11407. } else if (this.scope.inStaticBlock) {
  11408. this.raise(startLoc, ErrorMessages.AwaitBindingIdentifierInStaticBlock);
  11409. return;
  11410. } else {
  11411. this.expressionScope.recordAsyncArrowParametersError(startLoc, ErrorMessages.AwaitBindingIdentifier);
  11412. }
  11413. } else if (word === "arguments") {
  11414. if (this.scope.inClassAndNotInNonArrowFunction) {
  11415. this.raise(startLoc, ErrorMessages.ArgumentsInClass);
  11416. return;
  11417. }
  11418. }
  11419. if (checkKeywords && isKeyword(word)) {
  11420. this.raise(startLoc, ErrorMessages.UnexpectedKeyword, word);
  11421. return;
  11422. }
  11423. const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord;
  11424. if (reservedTest(word, this.inModule)) {
  11425. this.raise(startLoc, ErrorMessages.UnexpectedReservedWord, word);
  11426. }
  11427. }
  11428. isAwaitAllowed() {
  11429. if (this.prodParam.hasAwait) return true;
  11430. if (this.options.allowAwaitOutsideFunction && !this.scope.inFunction) {
  11431. return true;
  11432. }
  11433. return false;
  11434. }
  11435. parseAwait(startPos, startLoc) {
  11436. const node = this.startNodeAt(startPos, startLoc);
  11437. this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.AwaitExpressionFormalParameter);
  11438. if (this.eat(49)) {
  11439. this.raise(node.start, ErrorMessages.ObsoleteAwaitStar);
  11440. }
  11441. if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) {
  11442. if (this.isAmbiguousAwait()) {
  11443. this.ambiguousScriptDifferentAst = true;
  11444. } else {
  11445. this.sawUnambiguousESM = true;
  11446. }
  11447. }
  11448. if (!this.state.soloAwait) {
  11449. node.argument = this.parseMaybeUnary(null, true);
  11450. }
  11451. return this.finishNode(node, "AwaitExpression");
  11452. }
  11453. isAmbiguousAwait() {
  11454. 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);
  11455. }
  11456. parseYield() {
  11457. const node = this.startNode();
  11458. this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.YieldInParameter);
  11459. this.next();
  11460. let delegating = false;
  11461. let argument = null;
  11462. if (!this.hasPrecedingLineBreak()) {
  11463. delegating = this.eat(49);
  11464. switch (this.state.type) {
  11465. case 13:
  11466. case 129:
  11467. case 8:
  11468. case 11:
  11469. case 3:
  11470. case 9:
  11471. case 14:
  11472. case 12:
  11473. if (!delegating) break;
  11474. default:
  11475. argument = this.parseMaybeAssign();
  11476. }
  11477. }
  11478. node.delegate = delegating;
  11479. node.argument = argument;
  11480. return this.finishNode(node, "YieldExpression");
  11481. }
  11482. checkPipelineAtInfixOperator(left, leftStartPos) {
  11483. if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
  11484. if (left.type === "SequenceExpression") {
  11485. this.raise(leftStartPos, ErrorMessages.PipelineHeadSequenceExpression);
  11486. }
  11487. }
  11488. }
  11489. checkHackPipeBodyEarlyErrors(startPos) {
  11490. if (!this.topicReferenceWasUsedInCurrentContext()) {
  11491. this.raise(startPos, ErrorMessages.PipeTopicUnused);
  11492. }
  11493. }
  11494. parseSmartPipelineBodyInStyle(childExpr, startPos, startLoc) {
  11495. const bodyNode = this.startNodeAt(startPos, startLoc);
  11496. if (this.isSimpleReference(childExpr)) {
  11497. bodyNode.callee = childExpr;
  11498. return this.finishNode(bodyNode, "PipelineBareFunction");
  11499. } else {
  11500. this.checkSmartPipeTopicBodyEarlyErrors(startPos);
  11501. bodyNode.expression = childExpr;
  11502. return this.finishNode(bodyNode, "PipelineTopicExpression");
  11503. }
  11504. }
  11505. isSimpleReference(expression) {
  11506. switch (expression.type) {
  11507. case "MemberExpression":
  11508. return !expression.computed && this.isSimpleReference(expression.object);
  11509. case "Identifier":
  11510. return true;
  11511. default:
  11512. return false;
  11513. }
  11514. }
  11515. checkSmartPipeTopicBodyEarlyErrors(startPos) {
  11516. if (this.match(19)) {
  11517. throw this.raise(this.state.start, ErrorMessages.PipelineBodyNoArrow);
  11518. } else if (!this.topicReferenceWasUsedInCurrentContext()) {
  11519. this.raise(startPos, ErrorMessages.PipelineTopicUnused);
  11520. }
  11521. }
  11522. withTopicBindingContext(callback) {
  11523. const outerContextTopicState = this.state.topicContext;
  11524. this.state.topicContext = {
  11525. maxNumOfResolvableTopics: 1,
  11526. maxTopicIndex: null
  11527. };
  11528. try {
  11529. return callback();
  11530. } finally {
  11531. this.state.topicContext = outerContextTopicState;
  11532. }
  11533. }
  11534. withSmartMixTopicForbiddingContext(callback) {
  11535. const proposal = this.getPluginOption("pipelineOperator", "proposal");
  11536. if (proposal === "smart") {
  11537. const outerContextTopicState = this.state.topicContext;
  11538. this.state.topicContext = {
  11539. maxNumOfResolvableTopics: 0,
  11540. maxTopicIndex: null
  11541. };
  11542. try {
  11543. return callback();
  11544. } finally {
  11545. this.state.topicContext = outerContextTopicState;
  11546. }
  11547. } else {
  11548. return callback();
  11549. }
  11550. }
  11551. withSoloAwaitPermittingContext(callback) {
  11552. const outerContextSoloAwaitState = this.state.soloAwait;
  11553. this.state.soloAwait = true;
  11554. try {
  11555. return callback();
  11556. } finally {
  11557. this.state.soloAwait = outerContextSoloAwaitState;
  11558. }
  11559. }
  11560. allowInAnd(callback) {
  11561. const flags = this.prodParam.currentFlags();
  11562. const prodParamToSet = PARAM_IN & ~flags;
  11563. if (prodParamToSet) {
  11564. this.prodParam.enter(flags | PARAM_IN);
  11565. try {
  11566. return callback();
  11567. } finally {
  11568. this.prodParam.exit();
  11569. }
  11570. }
  11571. return callback();
  11572. }
  11573. disallowInAnd(callback) {
  11574. const flags = this.prodParam.currentFlags();
  11575. const prodParamToClear = PARAM_IN & flags;
  11576. if (prodParamToClear) {
  11577. this.prodParam.enter(flags & ~PARAM_IN);
  11578. try {
  11579. return callback();
  11580. } finally {
  11581. this.prodParam.exit();
  11582. }
  11583. }
  11584. return callback();
  11585. }
  11586. registerTopicReference() {
  11587. this.state.topicContext.maxTopicIndex = 0;
  11588. }
  11589. topicReferenceIsAllowedInCurrentContext() {
  11590. return this.state.topicContext.maxNumOfResolvableTopics >= 1;
  11591. }
  11592. topicReferenceWasUsedInCurrentContext() {
  11593. return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0;
  11594. }
  11595. parseFSharpPipelineBody(prec) {
  11596. const startPos = this.state.start;
  11597. const startLoc = this.state.startLoc;
  11598. this.state.potentialArrowAt = this.state.start;
  11599. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  11600. this.state.inFSharpPipelineDirectBody = true;
  11601. const ret = this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startPos, startLoc, prec);
  11602. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  11603. return ret;
  11604. }
  11605. parseModuleExpression() {
  11606. this.expectPlugin("moduleBlocks");
  11607. const node = this.startNode();
  11608. this.next();
  11609. this.eat(5);
  11610. const revertScopes = this.initializeScopes(true);
  11611. this.enterInitialScopes();
  11612. const program = this.startNode();
  11613. try {
  11614. node.body = this.parseProgram(program, 8, "module");
  11615. } finally {
  11616. revertScopes();
  11617. }
  11618. this.eat(8);
  11619. return this.finishNode(node, "ModuleExpression");
  11620. }
  11621. parsePropertyNamePrefixOperator(prop) {}
  11622. }
  11623. const loopLabel = {
  11624. kind: "loop"
  11625. },
  11626. switchLabel = {
  11627. kind: "switch"
  11628. };
  11629. const FUNC_NO_FLAGS = 0b000,
  11630. FUNC_STATEMENT = 0b001,
  11631. FUNC_HANGING_STATEMENT = 0b010,
  11632. FUNC_NULLABLE_ID = 0b100;
  11633. const loneSurrogate = /[\uD800-\uDFFF]/u;
  11634. const keywordRelationalOperator = /in(?:stanceof)?/y;
  11635. function babel7CompatTokens(tokens) {
  11636. for (let i = 0; i < tokens.length; i++) {
  11637. const token = tokens[i];
  11638. const {
  11639. type
  11640. } = token;
  11641. if (type === 128) {
  11642. {
  11643. const {
  11644. loc,
  11645. start,
  11646. value,
  11647. end
  11648. } = token;
  11649. const hashEndPos = start + 1;
  11650. const hashEndLoc = new Position(loc.start.line, loc.start.column + 1);
  11651. tokens.splice(i, 1, new Token({
  11652. type: getExportedToken(25),
  11653. value: "#",
  11654. start: start,
  11655. end: hashEndPos,
  11656. startLoc: loc.start,
  11657. endLoc: hashEndLoc
  11658. }), new Token({
  11659. type: getExportedToken(122),
  11660. value: value,
  11661. start: hashEndPos,
  11662. end: end,
  11663. startLoc: hashEndLoc,
  11664. endLoc: loc.end
  11665. }));
  11666. i++;
  11667. continue;
  11668. }
  11669. }
  11670. if (typeof type === "number") {
  11671. token.type = getExportedToken(type);
  11672. }
  11673. }
  11674. return tokens;
  11675. }
  11676. class StatementParser extends ExpressionParser {
  11677. parseTopLevel(file, program) {
  11678. file.program = this.parseProgram(program);
  11679. file.comments = this.state.comments;
  11680. if (this.options.tokens) file.tokens = babel7CompatTokens(this.tokens);
  11681. return this.finishNode(file, "File");
  11682. }
  11683. parseProgram(program, end = 129, sourceType = this.options.sourceType) {
  11684. program.sourceType = sourceType;
  11685. program.interpreter = this.parseInterpreterDirective();
  11686. this.parseBlockBody(program, true, true, end);
  11687. if (this.inModule && !this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) {
  11688. for (const [name] of Array.from(this.scope.undefinedExports)) {
  11689. const pos = this.scope.undefinedExports.get(name);
  11690. this.raise(pos, ErrorMessages.ModuleExportUndefined, name);
  11691. }
  11692. }
  11693. return this.finishNode(program, "Program");
  11694. }
  11695. stmtToDirective(stmt) {
  11696. const directive = stmt;
  11697. directive.type = "Directive";
  11698. directive.value = directive.expression;
  11699. delete directive.expression;
  11700. const directiveLiteral = directive.value;
  11701. const expressionValue = directiveLiteral.value;
  11702. const raw = this.input.slice(directiveLiteral.start, directiveLiteral.end);
  11703. const val = directiveLiteral.value = raw.slice(1, -1);
  11704. this.addExtra(directiveLiteral, "raw", raw);
  11705. this.addExtra(directiveLiteral, "rawValue", val);
  11706. this.addExtra(directiveLiteral, "expressionValue", expressionValue);
  11707. directiveLiteral.type = "DirectiveLiteral";
  11708. return directive;
  11709. }
  11710. parseInterpreterDirective() {
  11711. if (!this.match(26)) {
  11712. return null;
  11713. }
  11714. const node = this.startNode();
  11715. node.value = this.state.value;
  11716. this.next();
  11717. return this.finishNode(node, "InterpreterDirective");
  11718. }
  11719. isLet(context) {
  11720. if (!this.isContextual(93)) {
  11721. return false;
  11722. }
  11723. return this.isLetKeyword(context);
  11724. }
  11725. isLetKeyword(context) {
  11726. const next = this.nextTokenStart();
  11727. const nextCh = this.codePointAtPos(next);
  11728. if (nextCh === 92 || nextCh === 91) {
  11729. return true;
  11730. }
  11731. if (context) return false;
  11732. if (nextCh === 123) return true;
  11733. if (isIdentifierStart(nextCh)) {
  11734. keywordRelationalOperator.lastIndex = next;
  11735. if (keywordRelationalOperator.test(this.input)) {
  11736. const endCh = this.codePointAtPos(keywordRelationalOperator.lastIndex);
  11737. if (!isIdentifierChar(endCh) && endCh !== 92) {
  11738. return false;
  11739. }
  11740. }
  11741. return true;
  11742. }
  11743. return false;
  11744. }
  11745. parseStatement(context, topLevel) {
  11746. if (this.match(24)) {
  11747. this.parseDecorators(true);
  11748. }
  11749. return this.parseStatementContent(context, topLevel);
  11750. }
  11751. parseStatementContent(context, topLevel) {
  11752. let starttype = this.state.type;
  11753. const node = this.startNode();
  11754. let kind;
  11755. if (this.isLet(context)) {
  11756. starttype = 68;
  11757. kind = "let";
  11758. }
  11759. switch (starttype) {
  11760. case 54:
  11761. return this.parseBreakContinueStatement(node, true);
  11762. case 57:
  11763. return this.parseBreakContinueStatement(node, false);
  11764. case 58:
  11765. return this.parseDebuggerStatement(node);
  11766. case 84:
  11767. return this.parseDoStatement(node);
  11768. case 85:
  11769. return this.parseForStatement(node);
  11770. case 62:
  11771. if (this.lookaheadCharCode() === 46) break;
  11772. if (context) {
  11773. if (this.state.strict) {
  11774. this.raise(this.state.start, ErrorMessages.StrictFunction);
  11775. } else if (context !== "if" && context !== "label") {
  11776. this.raise(this.state.start, ErrorMessages.SloppyFunction);
  11777. }
  11778. }
  11779. return this.parseFunctionStatement(node, false, !context);
  11780. case 74:
  11781. if (context) this.unexpected();
  11782. return this.parseClass(node, true);
  11783. case 63:
  11784. return this.parseIfStatement(node);
  11785. case 64:
  11786. return this.parseReturnStatement(node);
  11787. case 65:
  11788. return this.parseSwitchStatement(node);
  11789. case 66:
  11790. return this.parseThrowStatement(node);
  11791. case 67:
  11792. return this.parseTryStatement(node);
  11793. case 69:
  11794. case 68:
  11795. kind = kind || this.state.value;
  11796. if (context && kind !== "var") {
  11797. this.raise(this.state.start, ErrorMessages.UnexpectedLexicalDeclaration);
  11798. }
  11799. return this.parseVarStatement(node, kind);
  11800. case 86:
  11801. return this.parseWhileStatement(node);
  11802. case 70:
  11803. return this.parseWithStatement(node);
  11804. case 5:
  11805. return this.parseBlock();
  11806. case 13:
  11807. return this.parseEmptyStatement(node);
  11808. case 77:
  11809. {
  11810. const nextTokenCharCode = this.lookaheadCharCode();
  11811. if (nextTokenCharCode === 40 || nextTokenCharCode === 46) {
  11812. break;
  11813. }
  11814. }
  11815. case 76:
  11816. {
  11817. if (!this.options.allowImportExportEverywhere && !topLevel) {
  11818. this.raise(this.state.start, ErrorMessages.UnexpectedImportExport);
  11819. }
  11820. this.next();
  11821. let result;
  11822. if (starttype === 77) {
  11823. result = this.parseImport(node);
  11824. if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) {
  11825. this.sawUnambiguousESM = true;
  11826. }
  11827. } else {
  11828. result = this.parseExport(node);
  11829. if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") {
  11830. this.sawUnambiguousESM = true;
  11831. }
  11832. }
  11833. this.assertModuleNodeAllowed(node);
  11834. return result;
  11835. }
  11836. default:
  11837. {
  11838. if (this.isAsyncFunction()) {
  11839. if (context) {
  11840. this.raise(this.state.start, ErrorMessages.AsyncFunctionInSingleStatementContext);
  11841. }
  11842. this.next();
  11843. return this.parseFunctionStatement(node, true, !context);
  11844. }
  11845. }
  11846. }
  11847. const maybeName = this.state.value;
  11848. const expr = this.parseExpression();
  11849. if (tokenIsIdentifier(starttype) && expr.type === "Identifier" && this.eat(14)) {
  11850. return this.parseLabeledStatement(node, maybeName, expr, context);
  11851. } else {
  11852. return this.parseExpressionStatement(node, expr);
  11853. }
  11854. }
  11855. assertModuleNodeAllowed(node) {
  11856. if (!this.options.allowImportExportEverywhere && !this.inModule) {
  11857. this.raise(node.start, SourceTypeModuleErrorMessages.ImportOutsideModule);
  11858. }
  11859. }
  11860. takeDecorators(node) {
  11861. const decorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  11862. if (decorators.length) {
  11863. node.decorators = decorators;
  11864. this.resetStartLocationFromNode(node, decorators[0]);
  11865. this.state.decoratorStack[this.state.decoratorStack.length - 1] = [];
  11866. }
  11867. }
  11868. canHaveLeadingDecorator() {
  11869. return this.match(74);
  11870. }
  11871. parseDecorators(allowExport) {
  11872. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  11873. while (this.match(24)) {
  11874. const decorator = this.parseDecorator();
  11875. currentContextDecorators.push(decorator);
  11876. }
  11877. if (this.match(76)) {
  11878. if (!allowExport) {
  11879. this.unexpected();
  11880. }
  11881. if (this.hasPlugin("decorators") && !this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  11882. this.raise(this.state.start, ErrorMessages.DecoratorExportClass);
  11883. }
  11884. } else if (!this.canHaveLeadingDecorator()) {
  11885. throw this.raise(this.state.start, ErrorMessages.UnexpectedLeadingDecorator);
  11886. }
  11887. }
  11888. parseDecorator() {
  11889. this.expectOnePlugin(["decorators-legacy", "decorators"]);
  11890. const node = this.startNode();
  11891. this.next();
  11892. if (this.hasPlugin("decorators")) {
  11893. this.state.decoratorStack.push([]);
  11894. const startPos = this.state.start;
  11895. const startLoc = this.state.startLoc;
  11896. let expr;
  11897. if (this.eat(10)) {
  11898. expr = this.parseExpression();
  11899. this.expect(11);
  11900. } else {
  11901. expr = this.parseIdentifier(false);
  11902. while (this.eat(16)) {
  11903. const node = this.startNodeAt(startPos, startLoc);
  11904. node.object = expr;
  11905. node.property = this.parseIdentifier(true);
  11906. node.computed = false;
  11907. expr = this.finishNode(node, "MemberExpression");
  11908. }
  11909. }
  11910. node.expression = this.parseMaybeDecoratorArguments(expr);
  11911. this.state.decoratorStack.pop();
  11912. } else {
  11913. node.expression = this.parseExprSubscripts();
  11914. }
  11915. return this.finishNode(node, "Decorator");
  11916. }
  11917. parseMaybeDecoratorArguments(expr) {
  11918. if (this.eat(10)) {
  11919. const node = this.startNodeAtNode(expr);
  11920. node.callee = expr;
  11921. node.arguments = this.parseCallExpressionArguments(11, false);
  11922. this.toReferencedList(node.arguments);
  11923. return this.finishNode(node, "CallExpression");
  11924. }
  11925. return expr;
  11926. }
  11927. parseBreakContinueStatement(node, isBreak) {
  11928. this.next();
  11929. if (this.isLineTerminator()) {
  11930. node.label = null;
  11931. } else {
  11932. node.label = this.parseIdentifier();
  11933. this.semicolon();
  11934. }
  11935. this.verifyBreakContinue(node, isBreak);
  11936. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  11937. }
  11938. verifyBreakContinue(node, isBreak) {
  11939. let i;
  11940. for (i = 0; i < this.state.labels.length; ++i) {
  11941. const lab = this.state.labels[i];
  11942. if (node.label == null || lab.name === node.label.name) {
  11943. if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
  11944. if (node.label && isBreak) break;
  11945. }
  11946. }
  11947. if (i === this.state.labels.length) {
  11948. this.raise(node.start, ErrorMessages.IllegalBreakContinue, isBreak ? "break" : "continue");
  11949. }
  11950. }
  11951. parseDebuggerStatement(node) {
  11952. this.next();
  11953. this.semicolon();
  11954. return this.finishNode(node, "DebuggerStatement");
  11955. }
  11956. parseHeaderExpression() {
  11957. this.expect(10);
  11958. const val = this.parseExpression();
  11959. this.expect(11);
  11960. return val;
  11961. }
  11962. parseDoStatement(node) {
  11963. this.next();
  11964. this.state.labels.push(loopLabel);
  11965. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement("do"));
  11966. this.state.labels.pop();
  11967. this.expect(86);
  11968. node.test = this.parseHeaderExpression();
  11969. this.eat(13);
  11970. return this.finishNode(node, "DoWhileStatement");
  11971. }
  11972. parseForStatement(node) {
  11973. this.next();
  11974. this.state.labels.push(loopLabel);
  11975. let awaitAt = -1;
  11976. if (this.isAwaitAllowed() && this.eatContextual(90)) {
  11977. awaitAt = this.state.lastTokStart;
  11978. }
  11979. this.scope.enter(SCOPE_OTHER);
  11980. this.expect(10);
  11981. if (this.match(13)) {
  11982. if (awaitAt > -1) {
  11983. this.unexpected(awaitAt);
  11984. }
  11985. return this.parseFor(node, null);
  11986. }
  11987. const startsWithLet = this.isContextual(93);
  11988. const isLet = startsWithLet && this.isLetKeyword();
  11989. if (this.match(68) || this.match(69) || isLet) {
  11990. const init = this.startNode();
  11991. const kind = isLet ? "let" : this.state.value;
  11992. this.next();
  11993. this.parseVar(init, true, kind);
  11994. this.finishNode(init, "VariableDeclaration");
  11995. if ((this.match(52) || this.isContextual(95)) && init.declarations.length === 1) {
  11996. return this.parseForIn(node, init, awaitAt);
  11997. }
  11998. if (awaitAt > -1) {
  11999. this.unexpected(awaitAt);
  12000. }
  12001. return this.parseFor(node, init);
  12002. }
  12003. const startsWithAsync = this.isContextual(89);
  12004. const refExpressionErrors = new ExpressionErrors();
  12005. const init = this.parseExpression(true, refExpressionErrors);
  12006. const isForOf = this.isContextual(95);
  12007. if (isForOf) {
  12008. if (startsWithLet) {
  12009. this.raise(init.start, ErrorMessages.ForOfLet);
  12010. } else if (awaitAt === -1 && startsWithAsync && init.type === "Identifier") {
  12011. this.raise(init.start, ErrorMessages.ForOfAsync);
  12012. }
  12013. }
  12014. if (isForOf || this.match(52)) {
  12015. this.toAssignable(init, true);
  12016. const description = isForOf ? "for-of statement" : "for-in statement";
  12017. this.checkLVal(init, description);
  12018. return this.parseForIn(node, init, awaitAt);
  12019. } else {
  12020. this.checkExpressionErrors(refExpressionErrors, true);
  12021. }
  12022. if (awaitAt > -1) {
  12023. this.unexpected(awaitAt);
  12024. }
  12025. return this.parseFor(node, init);
  12026. }
  12027. parseFunctionStatement(node, isAsync, declarationPosition) {
  12028. this.next();
  12029. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), isAsync);
  12030. }
  12031. parseIfStatement(node) {
  12032. this.next();
  12033. node.test = this.parseHeaderExpression();
  12034. node.consequent = this.parseStatement("if");
  12035. node.alternate = this.eat(60) ? this.parseStatement("if") : null;
  12036. return this.finishNode(node, "IfStatement");
  12037. }
  12038. parseReturnStatement(node) {
  12039. if (!this.prodParam.hasReturn && !this.options.allowReturnOutsideFunction) {
  12040. this.raise(this.state.start, ErrorMessages.IllegalReturn);
  12041. }
  12042. this.next();
  12043. if (this.isLineTerminator()) {
  12044. node.argument = null;
  12045. } else {
  12046. node.argument = this.parseExpression();
  12047. this.semicolon();
  12048. }
  12049. return this.finishNode(node, "ReturnStatement");
  12050. }
  12051. parseSwitchStatement(node) {
  12052. this.next();
  12053. node.discriminant = this.parseHeaderExpression();
  12054. const cases = node.cases = [];
  12055. this.expect(5);
  12056. this.state.labels.push(switchLabel);
  12057. this.scope.enter(SCOPE_OTHER);
  12058. let cur;
  12059. for (let sawDefault; !this.match(8);) {
  12060. if (this.match(55) || this.match(59)) {
  12061. const isCase = this.match(55);
  12062. if (cur) this.finishNode(cur, "SwitchCase");
  12063. cases.push(cur = this.startNode());
  12064. cur.consequent = [];
  12065. this.next();
  12066. if (isCase) {
  12067. cur.test = this.parseExpression();
  12068. } else {
  12069. if (sawDefault) {
  12070. this.raise(this.state.lastTokStart, ErrorMessages.MultipleDefaultsInSwitch);
  12071. }
  12072. sawDefault = true;
  12073. cur.test = null;
  12074. }
  12075. this.expect(14);
  12076. } else {
  12077. if (cur) {
  12078. cur.consequent.push(this.parseStatement(null));
  12079. } else {
  12080. this.unexpected();
  12081. }
  12082. }
  12083. }
  12084. this.scope.exit();
  12085. if (cur) this.finishNode(cur, "SwitchCase");
  12086. this.next();
  12087. this.state.labels.pop();
  12088. return this.finishNode(node, "SwitchStatement");
  12089. }
  12090. parseThrowStatement(node) {
  12091. this.next();
  12092. if (this.hasPrecedingLineBreak()) {
  12093. this.raise(this.state.lastTokEnd, ErrorMessages.NewlineAfterThrow);
  12094. }
  12095. node.argument = this.parseExpression();
  12096. this.semicolon();
  12097. return this.finishNode(node, "ThrowStatement");
  12098. }
  12099. parseCatchClauseParam() {
  12100. const param = this.parseBindingAtom();
  12101. const simple = param.type === "Identifier";
  12102. this.scope.enter(simple ? SCOPE_SIMPLE_CATCH : 0);
  12103. this.checkLVal(param, "catch clause", BIND_LEXICAL);
  12104. return param;
  12105. }
  12106. parseTryStatement(node) {
  12107. this.next();
  12108. node.block = this.parseBlock();
  12109. node.handler = null;
  12110. if (this.match(56)) {
  12111. const clause = this.startNode();
  12112. this.next();
  12113. if (this.match(10)) {
  12114. this.expect(10);
  12115. clause.param = this.parseCatchClauseParam();
  12116. this.expect(11);
  12117. } else {
  12118. clause.param = null;
  12119. this.scope.enter(SCOPE_OTHER);
  12120. }
  12121. clause.body = this.withSmartMixTopicForbiddingContext(() => this.parseBlock(false, false));
  12122. this.scope.exit();
  12123. node.handler = this.finishNode(clause, "CatchClause");
  12124. }
  12125. node.finalizer = this.eat(61) ? this.parseBlock() : null;
  12126. if (!node.handler && !node.finalizer) {
  12127. this.raise(node.start, ErrorMessages.NoCatchOrFinally);
  12128. }
  12129. return this.finishNode(node, "TryStatement");
  12130. }
  12131. parseVarStatement(node, kind) {
  12132. this.next();
  12133. this.parseVar(node, false, kind);
  12134. this.semicolon();
  12135. return this.finishNode(node, "VariableDeclaration");
  12136. }
  12137. parseWhileStatement(node) {
  12138. this.next();
  12139. node.test = this.parseHeaderExpression();
  12140. this.state.labels.push(loopLabel);
  12141. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement("while"));
  12142. this.state.labels.pop();
  12143. return this.finishNode(node, "WhileStatement");
  12144. }
  12145. parseWithStatement(node) {
  12146. if (this.state.strict) {
  12147. this.raise(this.state.start, ErrorMessages.StrictWith);
  12148. }
  12149. this.next();
  12150. node.object = this.parseHeaderExpression();
  12151. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement("with"));
  12152. return this.finishNode(node, "WithStatement");
  12153. }
  12154. parseEmptyStatement(node) {
  12155. this.next();
  12156. return this.finishNode(node, "EmptyStatement");
  12157. }
  12158. parseLabeledStatement(node, maybeName, expr, context) {
  12159. for (const label of this.state.labels) {
  12160. if (label.name === maybeName) {
  12161. this.raise(expr.start, ErrorMessages.LabelRedeclaration, maybeName);
  12162. }
  12163. }
  12164. const kind = tokenIsLoop(this.state.type) ? "loop" : this.match(65) ? "switch" : null;
  12165. for (let i = this.state.labels.length - 1; i >= 0; i--) {
  12166. const label = this.state.labels[i];
  12167. if (label.statementStart === node.start) {
  12168. label.statementStart = this.state.start;
  12169. label.kind = kind;
  12170. } else {
  12171. break;
  12172. }
  12173. }
  12174. this.state.labels.push({
  12175. name: maybeName,
  12176. kind: kind,
  12177. statementStart: this.state.start
  12178. });
  12179. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  12180. this.state.labels.pop();
  12181. node.label = expr;
  12182. return this.finishNode(node, "LabeledStatement");
  12183. }
  12184. parseExpressionStatement(node, expr) {
  12185. node.expression = expr;
  12186. this.semicolon();
  12187. return this.finishNode(node, "ExpressionStatement");
  12188. }
  12189. parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) {
  12190. const node = this.startNode();
  12191. if (allowDirectives) {
  12192. this.state.strictErrors.clear();
  12193. }
  12194. this.expect(5);
  12195. if (createNewLexicalScope) {
  12196. this.scope.enter(SCOPE_OTHER);
  12197. }
  12198. this.parseBlockBody(node, allowDirectives, false, 8, afterBlockParse);
  12199. if (createNewLexicalScope) {
  12200. this.scope.exit();
  12201. }
  12202. return this.finishNode(node, "BlockStatement");
  12203. }
  12204. isValidDirective(stmt) {
  12205. return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized;
  12206. }
  12207. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  12208. const body = node.body = [];
  12209. const directives = node.directives = [];
  12210. this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse);
  12211. }
  12212. parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) {
  12213. const oldStrict = this.state.strict;
  12214. let hasStrictModeDirective = false;
  12215. let parsedNonDirective = false;
  12216. while (!this.match(end)) {
  12217. const stmt = this.parseStatement(null, topLevel);
  12218. if (directives && !parsedNonDirective) {
  12219. if (this.isValidDirective(stmt)) {
  12220. const directive = this.stmtToDirective(stmt);
  12221. directives.push(directive);
  12222. if (!hasStrictModeDirective && directive.value.value === "use strict") {
  12223. hasStrictModeDirective = true;
  12224. this.setStrict(true);
  12225. }
  12226. continue;
  12227. }
  12228. parsedNonDirective = true;
  12229. this.state.strictErrors.clear();
  12230. }
  12231. body.push(stmt);
  12232. }
  12233. if (afterBlockParse) {
  12234. afterBlockParse.call(this, hasStrictModeDirective);
  12235. }
  12236. if (!oldStrict) {
  12237. this.setStrict(false);
  12238. }
  12239. this.next();
  12240. }
  12241. parseFor(node, init) {
  12242. node.init = init;
  12243. this.semicolon(false);
  12244. node.test = this.match(13) ? null : this.parseExpression();
  12245. this.semicolon(false);
  12246. node.update = this.match(11) ? null : this.parseExpression();
  12247. this.expect(11);
  12248. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement("for"));
  12249. this.scope.exit();
  12250. this.state.labels.pop();
  12251. return this.finishNode(node, "ForStatement");
  12252. }
  12253. parseForIn(node, init, awaitAt) {
  12254. const isForIn = this.match(52);
  12255. this.next();
  12256. if (isForIn) {
  12257. if (awaitAt > -1) this.unexpected(awaitAt);
  12258. } else {
  12259. node.await = awaitAt > -1;
  12260. }
  12261. if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
  12262. this.raise(init.start, ErrorMessages.ForInOfLoopInitializer, isForIn ? "for-in" : "for-of");
  12263. } else if (init.type === "AssignmentPattern") {
  12264. this.raise(init.start, ErrorMessages.InvalidLhs, "for-loop");
  12265. }
  12266. node.left = init;
  12267. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn();
  12268. this.expect(11);
  12269. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement("for"));
  12270. this.scope.exit();
  12271. this.state.labels.pop();
  12272. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
  12273. }
  12274. parseVar(node, isFor, kind) {
  12275. const declarations = node.declarations = [];
  12276. const isTypescript = this.hasPlugin("typescript");
  12277. node.kind = kind;
  12278. for (;;) {
  12279. const decl = this.startNode();
  12280. this.parseVarId(decl, kind);
  12281. if (this.eat(27)) {
  12282. decl.init = isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn();
  12283. } else {
  12284. if (kind === "const" && !(this.match(52) || this.isContextual(95))) {
  12285. if (!isTypescript) {
  12286. this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Const declarations");
  12287. }
  12288. } else if (decl.id.type !== "Identifier" && !(isFor && (this.match(52) || this.isContextual(95)))) {
  12289. this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Complex binding patterns");
  12290. }
  12291. decl.init = null;
  12292. }
  12293. declarations.push(this.finishNode(decl, "VariableDeclarator"));
  12294. if (!this.eat(12)) break;
  12295. }
  12296. return node;
  12297. }
  12298. parseVarId(decl, kind) {
  12299. decl.id = this.parseBindingAtom();
  12300. this.checkLVal(decl.id, "variable declaration", kind === "var" ? BIND_VAR : BIND_LEXICAL, undefined, kind !== "var");
  12301. }
  12302. parseFunction(node, statement = FUNC_NO_FLAGS, isAsync = false) {
  12303. const isStatement = statement & FUNC_STATEMENT;
  12304. const isHangingStatement = statement & FUNC_HANGING_STATEMENT;
  12305. const requireId = !!isStatement && !(statement & FUNC_NULLABLE_ID);
  12306. this.initFunction(node, isAsync);
  12307. if (this.match(49) && isHangingStatement) {
  12308. this.raise(this.state.start, ErrorMessages.GeneratorInSingleStatementContext);
  12309. }
  12310. node.generator = this.eat(49);
  12311. if (isStatement) {
  12312. node.id = this.parseFunctionId(requireId);
  12313. }
  12314. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  12315. this.state.maybeInArrowParameters = false;
  12316. this.scope.enter(SCOPE_FUNCTION);
  12317. this.prodParam.enter(functionFlags(isAsync, node.generator));
  12318. if (!isStatement) {
  12319. node.id = this.parseFunctionId();
  12320. }
  12321. this.parseFunctionParams(node, false);
  12322. this.withSmartMixTopicForbiddingContext(() => {
  12323. this.parseFunctionBodyAndFinish(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
  12324. });
  12325. this.prodParam.exit();
  12326. this.scope.exit();
  12327. if (isStatement && !isHangingStatement) {
  12328. this.registerFunctionStatementId(node);
  12329. }
  12330. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  12331. return node;
  12332. }
  12333. parseFunctionId(requireId) {
  12334. return requireId || tokenIsIdentifier(this.state.type) ? this.parseIdentifier() : null;
  12335. }
  12336. parseFunctionParams(node, allowModifiers) {
  12337. this.expect(10);
  12338. this.expressionScope.enter(newParameterDeclarationScope());
  12339. node.params = this.parseBindingList(11, 41, false, allowModifiers);
  12340. this.expressionScope.exit();
  12341. }
  12342. registerFunctionStatementId(node) {
  12343. if (!node.id) return;
  12344. 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);
  12345. }
  12346. parseClass(node, isStatement, optionalId) {
  12347. this.next();
  12348. this.takeDecorators(node);
  12349. const oldStrict = this.state.strict;
  12350. this.state.strict = true;
  12351. this.parseClassId(node, isStatement, optionalId);
  12352. this.parseClassSuper(node);
  12353. node.body = this.parseClassBody(!!node.superClass, oldStrict);
  12354. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
  12355. }
  12356. isClassProperty() {
  12357. return this.match(27) || this.match(13) || this.match(8);
  12358. }
  12359. isClassMethod() {
  12360. return this.match(10);
  12361. }
  12362. isNonstaticConstructor(method) {
  12363. return !method.computed && !method.static && (method.key.name === "constructor" || method.key.value === "constructor");
  12364. }
  12365. parseClassBody(hadSuperClass, oldStrict) {
  12366. this.classScope.enter();
  12367. const state = {
  12368. hadConstructor: false,
  12369. hadSuperClass
  12370. };
  12371. let decorators = [];
  12372. const classBody = this.startNode();
  12373. classBody.body = [];
  12374. this.expect(5);
  12375. this.withSmartMixTopicForbiddingContext(() => {
  12376. while (!this.match(8)) {
  12377. if (this.eat(13)) {
  12378. if (decorators.length > 0) {
  12379. throw this.raise(this.state.lastTokEnd, ErrorMessages.DecoratorSemicolon);
  12380. }
  12381. continue;
  12382. }
  12383. if (this.match(24)) {
  12384. decorators.push(this.parseDecorator());
  12385. continue;
  12386. }
  12387. const member = this.startNode();
  12388. if (decorators.length) {
  12389. member.decorators = decorators;
  12390. this.resetStartLocationFromNode(member, decorators[0]);
  12391. decorators = [];
  12392. }
  12393. this.parseClassMember(classBody, member, state);
  12394. if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) {
  12395. this.raise(member.start, ErrorMessages.DecoratorConstructor);
  12396. }
  12397. }
  12398. });
  12399. this.state.strict = oldStrict;
  12400. this.next();
  12401. if (decorators.length) {
  12402. throw this.raise(this.state.start, ErrorMessages.TrailingDecorator);
  12403. }
  12404. this.classScope.exit();
  12405. return this.finishNode(classBody, "ClassBody");
  12406. }
  12407. parseClassMemberFromModifier(classBody, member) {
  12408. const key = this.parseIdentifier(true);
  12409. if (this.isClassMethod()) {
  12410. const method = member;
  12411. method.kind = "method";
  12412. method.computed = false;
  12413. method.key = key;
  12414. method.static = false;
  12415. this.pushClassMethod(classBody, method, false, false, false, false);
  12416. return true;
  12417. } else if (this.isClassProperty()) {
  12418. const prop = member;
  12419. prop.computed = false;
  12420. prop.key = key;
  12421. prop.static = false;
  12422. classBody.body.push(this.parseClassProperty(prop));
  12423. return true;
  12424. }
  12425. this.resetPreviousNodeTrailingComments(key);
  12426. return false;
  12427. }
  12428. parseClassMember(classBody, member, state) {
  12429. const isStatic = this.isContextual(98);
  12430. if (isStatic) {
  12431. if (this.parseClassMemberFromModifier(classBody, member)) {
  12432. return;
  12433. }
  12434. if (this.eat(5)) {
  12435. this.parseClassStaticBlock(classBody, member);
  12436. return;
  12437. }
  12438. }
  12439. this.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  12440. }
  12441. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  12442. const publicMethod = member;
  12443. const privateMethod = member;
  12444. const publicProp = member;
  12445. const privateProp = member;
  12446. const method = publicMethod;
  12447. const publicMember = publicMethod;
  12448. member.static = isStatic;
  12449. this.parsePropertyNamePrefixOperator(member);
  12450. if (this.eat(49)) {
  12451. method.kind = "method";
  12452. const isPrivateName = this.match(128);
  12453. this.parseClassElementName(method);
  12454. if (isPrivateName) {
  12455. this.pushClassPrivateMethod(classBody, privateMethod, true, false);
  12456. return;
  12457. }
  12458. if (this.isNonstaticConstructor(publicMethod)) {
  12459. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsGenerator);
  12460. }
  12461. this.pushClassMethod(classBody, publicMethod, true, false, false, false);
  12462. return;
  12463. }
  12464. const isContextual = tokenIsIdentifier(this.state.type) && !this.state.containsEsc;
  12465. const isPrivate = this.match(128);
  12466. const key = this.parseClassElementName(member);
  12467. const maybeQuestionTokenStart = this.state.start;
  12468. this.parsePostMemberNameModifiers(publicMember);
  12469. if (this.isClassMethod()) {
  12470. method.kind = "method";
  12471. if (isPrivate) {
  12472. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  12473. return;
  12474. }
  12475. const isConstructor = this.isNonstaticConstructor(publicMethod);
  12476. let allowsDirectSuper = false;
  12477. if (isConstructor) {
  12478. publicMethod.kind = "constructor";
  12479. if (state.hadConstructor && !this.hasPlugin("typescript")) {
  12480. this.raise(key.start, ErrorMessages.DuplicateConstructor);
  12481. }
  12482. if (isConstructor && this.hasPlugin("typescript") && member.override) {
  12483. this.raise(key.start, ErrorMessages.OverrideOnConstructor);
  12484. }
  12485. state.hadConstructor = true;
  12486. allowsDirectSuper = state.hadSuperClass;
  12487. }
  12488. this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper);
  12489. } else if (this.isClassProperty()) {
  12490. if (isPrivate) {
  12491. this.pushClassPrivateProperty(classBody, privateProp);
  12492. } else {
  12493. this.pushClassProperty(classBody, publicProp);
  12494. }
  12495. } else if (isContextual && key.name === "async" && !this.isLineTerminator()) {
  12496. this.resetPreviousNodeTrailingComments(key);
  12497. const isGenerator = this.eat(49);
  12498. if (publicMember.optional) {
  12499. this.unexpected(maybeQuestionTokenStart);
  12500. }
  12501. method.kind = "method";
  12502. const isPrivate = this.match(128);
  12503. this.parseClassElementName(method);
  12504. this.parsePostMemberNameModifiers(publicMember);
  12505. if (isPrivate) {
  12506. this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true);
  12507. } else {
  12508. if (this.isNonstaticConstructor(publicMethod)) {
  12509. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAsync);
  12510. }
  12511. this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false);
  12512. }
  12513. } else if (isContextual && (key.name === "get" || key.name === "set") && !(this.match(49) && this.isLineTerminator())) {
  12514. this.resetPreviousNodeTrailingComments(key);
  12515. method.kind = key.name;
  12516. const isPrivate = this.match(128);
  12517. this.parseClassElementName(publicMethod);
  12518. if (isPrivate) {
  12519. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  12520. } else {
  12521. if (this.isNonstaticConstructor(publicMethod)) {
  12522. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAccessor);
  12523. }
  12524. this.pushClassMethod(classBody, publicMethod, false, false, false, false);
  12525. }
  12526. this.checkGetterSetterParams(publicMethod);
  12527. } else if (this.isLineTerminator()) {
  12528. if (isPrivate) {
  12529. this.pushClassPrivateProperty(classBody, privateProp);
  12530. } else {
  12531. this.pushClassProperty(classBody, publicProp);
  12532. }
  12533. } else {
  12534. this.unexpected();
  12535. }
  12536. }
  12537. parseClassElementName(member) {
  12538. const {
  12539. type,
  12540. value,
  12541. start
  12542. } = this.state;
  12543. if ((type === 122 || type === 123) && member.static && value === "prototype") {
  12544. this.raise(start, ErrorMessages.StaticPrototype);
  12545. }
  12546. if (type === 128) {
  12547. if (value === "constructor") {
  12548. this.raise(start, ErrorMessages.ConstructorClassPrivateField);
  12549. }
  12550. const key = this.parsePrivateName();
  12551. member.key = key;
  12552. return key;
  12553. }
  12554. return this.parsePropertyName(member);
  12555. }
  12556. parseClassStaticBlock(classBody, member) {
  12557. var _member$decorators;
  12558. this.scope.enter(SCOPE_CLASS | SCOPE_STATIC_BLOCK | SCOPE_SUPER);
  12559. const oldLabels = this.state.labels;
  12560. this.state.labels = [];
  12561. this.prodParam.enter(PARAM);
  12562. const body = member.body = [];
  12563. this.parseBlockOrModuleBlockBody(body, undefined, false, 8);
  12564. this.prodParam.exit();
  12565. this.scope.exit();
  12566. this.state.labels = oldLabels;
  12567. classBody.body.push(this.finishNode(member, "StaticBlock"));
  12568. if ((_member$decorators = member.decorators) != null && _member$decorators.length) {
  12569. this.raise(member.start, ErrorMessages.DecoratorStaticBlock);
  12570. }
  12571. }
  12572. pushClassProperty(classBody, prop) {
  12573. if (!prop.computed && (prop.key.name === "constructor" || prop.key.value === "constructor")) {
  12574. this.raise(prop.key.start, ErrorMessages.ConstructorClassField);
  12575. }
  12576. classBody.body.push(this.parseClassProperty(prop));
  12577. }
  12578. pushClassPrivateProperty(classBody, prop) {
  12579. const node = this.parseClassPrivateProperty(prop);
  12580. classBody.body.push(node);
  12581. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), CLASS_ELEMENT_OTHER, node.key.start);
  12582. }
  12583. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  12584. classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true));
  12585. }
  12586. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  12587. const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true);
  12588. classBody.body.push(node);
  12589. 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;
  12590. this.declareClassPrivateMethodInScope(node, kind);
  12591. }
  12592. declareClassPrivateMethodInScope(node, kind) {
  12593. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), kind, node.key.start);
  12594. }
  12595. parsePostMemberNameModifiers(methodOrProp) {}
  12596. parseClassPrivateProperty(node) {
  12597. this.parseInitializer(node);
  12598. this.semicolon();
  12599. return this.finishNode(node, "ClassPrivateProperty");
  12600. }
  12601. parseClassProperty(node) {
  12602. this.parseInitializer(node);
  12603. this.semicolon();
  12604. return this.finishNode(node, "ClassProperty");
  12605. }
  12606. parseInitializer(node) {
  12607. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  12608. this.expressionScope.enter(newExpressionScope());
  12609. this.prodParam.enter(PARAM);
  12610. node.value = this.eat(27) ? this.parseMaybeAssignAllowIn() : null;
  12611. this.expressionScope.exit();
  12612. this.prodParam.exit();
  12613. this.scope.exit();
  12614. }
  12615. parseClassId(node, isStatement, optionalId, bindingType = BIND_CLASS) {
  12616. if (tokenIsIdentifier(this.state.type)) {
  12617. node.id = this.parseIdentifier();
  12618. if (isStatement) {
  12619. this.checkLVal(node.id, "class name", bindingType);
  12620. }
  12621. } else {
  12622. if (optionalId || !isStatement) {
  12623. node.id = null;
  12624. } else {
  12625. this.unexpected(null, ErrorMessages.MissingClassName);
  12626. }
  12627. }
  12628. }
  12629. parseClassSuper(node) {
  12630. node.superClass = this.eat(75) ? this.parseExprSubscripts() : null;
  12631. }
  12632. parseExport(node) {
  12633. const hasDefault = this.maybeParseExportDefaultSpecifier(node);
  12634. const parseAfterDefault = !hasDefault || this.eat(12);
  12635. const hasStar = parseAfterDefault && this.eatExportStar(node);
  12636. const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node);
  12637. const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(12));
  12638. const isFromRequired = hasDefault || hasStar;
  12639. if (hasStar && !hasNamespace) {
  12640. if (hasDefault) this.unexpected();
  12641. this.parseExportFrom(node, true);
  12642. return this.finishNode(node, "ExportAllDeclaration");
  12643. }
  12644. const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node);
  12645. if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers || hasNamespace && parseAfterNamespace && !hasSpecifiers) {
  12646. throw this.unexpected(null, 5);
  12647. }
  12648. let hasDeclaration;
  12649. if (isFromRequired || hasSpecifiers) {
  12650. hasDeclaration = false;
  12651. this.parseExportFrom(node, isFromRequired);
  12652. } else {
  12653. hasDeclaration = this.maybeParseExportDeclaration(node);
  12654. }
  12655. if (isFromRequired || hasSpecifiers || hasDeclaration) {
  12656. this.checkExport(node, true, false, !!node.source);
  12657. return this.finishNode(node, "ExportNamedDeclaration");
  12658. }
  12659. if (this.eat(59)) {
  12660. node.declaration = this.parseExportDefaultExpression();
  12661. this.checkExport(node, true, true);
  12662. return this.finishNode(node, "ExportDefaultDeclaration");
  12663. }
  12664. throw this.unexpected(null, 5);
  12665. }
  12666. eatExportStar(node) {
  12667. return this.eat(49);
  12668. }
  12669. maybeParseExportDefaultSpecifier(node) {
  12670. if (this.isExportDefaultSpecifier()) {
  12671. this.expectPlugin("exportDefaultFrom");
  12672. const specifier = this.startNode();
  12673. specifier.exported = this.parseIdentifier(true);
  12674. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  12675. return true;
  12676. }
  12677. return false;
  12678. }
  12679. maybeParseExportNamespaceSpecifier(node) {
  12680. if (this.isContextual(87)) {
  12681. if (!node.specifiers) node.specifiers = [];
  12682. const specifier = this.startNodeAt(this.state.lastTokStart, this.state.lastTokStartLoc);
  12683. this.next();
  12684. specifier.exported = this.parseModuleExportName();
  12685. node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
  12686. return true;
  12687. }
  12688. return false;
  12689. }
  12690. maybeParseExportNamedSpecifiers(node) {
  12691. if (this.match(5)) {
  12692. if (!node.specifiers) node.specifiers = [];
  12693. const isTypeExport = node.exportKind === "type";
  12694. node.specifiers.push(...this.parseExportSpecifiers(isTypeExport));
  12695. node.source = null;
  12696. node.declaration = null;
  12697. if (this.hasPlugin("importAssertions")) {
  12698. node.assertions = [];
  12699. }
  12700. return true;
  12701. }
  12702. return false;
  12703. }
  12704. maybeParseExportDeclaration(node) {
  12705. if (this.shouldParseExportDeclaration()) {
  12706. node.specifiers = [];
  12707. node.source = null;
  12708. if (this.hasPlugin("importAssertions")) {
  12709. node.assertions = [];
  12710. }
  12711. node.declaration = this.parseExportDeclaration(node);
  12712. return true;
  12713. }
  12714. return false;
  12715. }
  12716. isAsyncFunction() {
  12717. if (!this.isContextual(89)) return false;
  12718. const next = this.nextTokenStart();
  12719. return !lineBreak.test(this.input.slice(this.state.pos, next)) && this.isUnparsedContextual(next, "function");
  12720. }
  12721. parseExportDefaultExpression() {
  12722. const expr = this.startNode();
  12723. const isAsync = this.isAsyncFunction();
  12724. if (this.match(62) || isAsync) {
  12725. this.next();
  12726. if (isAsync) {
  12727. this.next();
  12728. }
  12729. return this.parseFunction(expr, FUNC_STATEMENT | FUNC_NULLABLE_ID, isAsync);
  12730. } else if (this.match(74)) {
  12731. return this.parseClass(expr, true, true);
  12732. } else if (this.match(24)) {
  12733. if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  12734. this.raise(this.state.start, ErrorMessages.DecoratorBeforeExport);
  12735. }
  12736. this.parseDecorators(false);
  12737. return this.parseClass(expr, true, true);
  12738. } else if (this.match(69) || this.match(68) || this.isLet()) {
  12739. throw this.raise(this.state.start, ErrorMessages.UnsupportedDefaultExport);
  12740. } else {
  12741. const res = this.parseMaybeAssignAllowIn();
  12742. this.semicolon();
  12743. return res;
  12744. }
  12745. }
  12746. parseExportDeclaration(node) {
  12747. return this.parseStatement(null);
  12748. }
  12749. isExportDefaultSpecifier() {
  12750. const {
  12751. type
  12752. } = this.state;
  12753. if (tokenIsIdentifier(type)) {
  12754. if (type === 89 && !this.state.containsEsc || type === 93) {
  12755. return false;
  12756. }
  12757. if ((type === 120 || type === 119) && !this.state.containsEsc) {
  12758. const {
  12759. type: nextType
  12760. } = this.lookahead();
  12761. if (tokenIsIdentifier(nextType) && nextType !== 91 || nextType === 5) {
  12762. this.expectOnePlugin(["flow", "typescript"]);
  12763. return false;
  12764. }
  12765. }
  12766. } else if (!this.match(59)) {
  12767. return false;
  12768. }
  12769. const next = this.nextTokenStart();
  12770. const hasFrom = this.isUnparsedContextual(next, "from");
  12771. if (this.input.charCodeAt(next) === 44 || tokenIsIdentifier(this.state.type) && hasFrom) {
  12772. return true;
  12773. }
  12774. if (this.match(59) && hasFrom) {
  12775. const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4));
  12776. return nextAfterFrom === 34 || nextAfterFrom === 39;
  12777. }
  12778. return false;
  12779. }
  12780. parseExportFrom(node, expect) {
  12781. if (this.eatContextual(91)) {
  12782. node.source = this.parseImportSource();
  12783. this.checkExport(node);
  12784. const assertions = this.maybeParseImportAssertions();
  12785. if (assertions) {
  12786. node.assertions = assertions;
  12787. }
  12788. } else if (expect) {
  12789. this.unexpected();
  12790. }
  12791. this.semicolon();
  12792. }
  12793. shouldParseExportDeclaration() {
  12794. const {
  12795. type
  12796. } = this.state;
  12797. if (type === 24) {
  12798. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  12799. if (this.hasPlugin("decorators")) {
  12800. if (this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  12801. this.unexpected(this.state.start, ErrorMessages.DecoratorBeforeExport);
  12802. } else {
  12803. return true;
  12804. }
  12805. }
  12806. }
  12807. return type === 68 || type === 69 || type === 62 || type === 74 || this.isLet() || this.isAsyncFunction();
  12808. }
  12809. checkExport(node, checkNames, isDefault, isFrom) {
  12810. if (checkNames) {
  12811. if (isDefault) {
  12812. this.checkDuplicateExports(node, "default");
  12813. if (this.hasPlugin("exportDefaultFrom")) {
  12814. var _declaration$extra;
  12815. const declaration = node.declaration;
  12816. if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 && !((_declaration$extra = declaration.extra) != null && _declaration$extra.parenthesized)) {
  12817. this.raise(declaration.start, ErrorMessages.ExportDefaultFromAsIdentifier);
  12818. }
  12819. }
  12820. } else if (node.specifiers && node.specifiers.length) {
  12821. for (const specifier of node.specifiers) {
  12822. const {
  12823. exported
  12824. } = specifier;
  12825. const exportedName = exported.type === "Identifier" ? exported.name : exported.value;
  12826. this.checkDuplicateExports(specifier, exportedName);
  12827. if (!isFrom && specifier.local) {
  12828. const {
  12829. local
  12830. } = specifier;
  12831. if (local.type !== "Identifier") {
  12832. this.raise(specifier.start, ErrorMessages.ExportBindingIsString, local.value, exportedName);
  12833. } else {
  12834. this.checkReservedWord(local.name, local.start, true, false);
  12835. this.scope.checkLocalExport(local);
  12836. }
  12837. }
  12838. }
  12839. } else if (node.declaration) {
  12840. if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") {
  12841. const id = node.declaration.id;
  12842. if (!id) throw new Error("Assertion failure");
  12843. this.checkDuplicateExports(node, id.name);
  12844. } else if (node.declaration.type === "VariableDeclaration") {
  12845. for (const declaration of node.declaration.declarations) {
  12846. this.checkDeclaration(declaration.id);
  12847. }
  12848. }
  12849. }
  12850. }
  12851. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  12852. if (currentContextDecorators.length) {
  12853. throw this.raise(node.start, ErrorMessages.UnsupportedDecoratorExport);
  12854. }
  12855. }
  12856. checkDeclaration(node) {
  12857. if (node.type === "Identifier") {
  12858. this.checkDuplicateExports(node, node.name);
  12859. } else if (node.type === "ObjectPattern") {
  12860. for (const prop of node.properties) {
  12861. this.checkDeclaration(prop);
  12862. }
  12863. } else if (node.type === "ArrayPattern") {
  12864. for (const elem of node.elements) {
  12865. if (elem) {
  12866. this.checkDeclaration(elem);
  12867. }
  12868. }
  12869. } else if (node.type === "ObjectProperty") {
  12870. this.checkDeclaration(node.value);
  12871. } else if (node.type === "RestElement") {
  12872. this.checkDeclaration(node.argument);
  12873. } else if (node.type === "AssignmentPattern") {
  12874. this.checkDeclaration(node.left);
  12875. }
  12876. }
  12877. checkDuplicateExports(node, name) {
  12878. if (this.exportedIdentifiers.has(name)) {
  12879. this.raise(node.start, name === "default" ? ErrorMessages.DuplicateDefaultExport : ErrorMessages.DuplicateExport, name);
  12880. }
  12881. this.exportedIdentifiers.add(name);
  12882. }
  12883. parseExportSpecifiers(isInTypeExport) {
  12884. const nodes = [];
  12885. let first = true;
  12886. this.expect(5);
  12887. while (!this.eat(8)) {
  12888. if (first) {
  12889. first = false;
  12890. } else {
  12891. this.expect(12);
  12892. if (this.eat(8)) break;
  12893. }
  12894. const isMaybeTypeOnly = this.isContextual(120);
  12895. const isString = this.match(123);
  12896. const node = this.startNode();
  12897. node.local = this.parseModuleExportName();
  12898. nodes.push(this.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly));
  12899. }
  12900. return nodes;
  12901. }
  12902. parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) {
  12903. if (this.eatContextual(87)) {
  12904. node.exported = this.parseModuleExportName();
  12905. } else if (isString) {
  12906. node.exported = cloneStringLiteral(node.local);
  12907. } else if (!node.exported) {
  12908. node.exported = cloneIdentifier(node.local);
  12909. }
  12910. return this.finishNode(node, "ExportSpecifier");
  12911. }
  12912. parseModuleExportName() {
  12913. if (this.match(123)) {
  12914. const result = this.parseStringLiteral(this.state.value);
  12915. const surrogate = result.value.match(loneSurrogate);
  12916. if (surrogate) {
  12917. this.raise(result.start, ErrorMessages.ModuleExportNameHasLoneSurrogate, surrogate[0].charCodeAt(0).toString(16));
  12918. }
  12919. return result;
  12920. }
  12921. return this.parseIdentifier(true);
  12922. }
  12923. parseImport(node) {
  12924. node.specifiers = [];
  12925. if (!this.match(123)) {
  12926. const hasDefault = this.maybeParseDefaultImportSpecifier(node);
  12927. const parseNext = !hasDefault || this.eat(12);
  12928. const hasStar = parseNext && this.maybeParseStarImportSpecifier(node);
  12929. if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node);
  12930. this.expectContextual(91);
  12931. }
  12932. node.source = this.parseImportSource();
  12933. const assertions = this.maybeParseImportAssertions();
  12934. if (assertions) {
  12935. node.assertions = assertions;
  12936. } else {
  12937. const attributes = this.maybeParseModuleAttributes();
  12938. if (attributes) {
  12939. node.attributes = attributes;
  12940. }
  12941. }
  12942. this.semicolon();
  12943. return this.finishNode(node, "ImportDeclaration");
  12944. }
  12945. parseImportSource() {
  12946. if (!this.match(123)) this.unexpected();
  12947. return this.parseExprAtom();
  12948. }
  12949. shouldParseDefaultImport(node) {
  12950. return tokenIsIdentifier(this.state.type);
  12951. }
  12952. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  12953. specifier.local = this.parseIdentifier();
  12954. this.checkLVal(specifier.local, contextDescription, BIND_LEXICAL);
  12955. node.specifiers.push(this.finishNode(specifier, type));
  12956. }
  12957. parseAssertEntries() {
  12958. const attrs = [];
  12959. const attrNames = new Set();
  12960. do {
  12961. if (this.match(8)) {
  12962. break;
  12963. }
  12964. const node = this.startNode();
  12965. const keyName = this.state.value;
  12966. if (attrNames.has(keyName)) {
  12967. this.raise(this.state.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, keyName);
  12968. }
  12969. attrNames.add(keyName);
  12970. if (this.match(123)) {
  12971. node.key = this.parseStringLiteral(keyName);
  12972. } else {
  12973. node.key = this.parseIdentifier(true);
  12974. }
  12975. this.expect(14);
  12976. if (!this.match(123)) {
  12977. throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue);
  12978. }
  12979. node.value = this.parseStringLiteral(this.state.value);
  12980. this.finishNode(node, "ImportAttribute");
  12981. attrs.push(node);
  12982. } while (this.eat(12));
  12983. return attrs;
  12984. }
  12985. maybeParseModuleAttributes() {
  12986. if (this.match(70) && !this.hasPrecedingLineBreak()) {
  12987. this.expectPlugin("moduleAttributes");
  12988. this.next();
  12989. } else {
  12990. if (this.hasPlugin("moduleAttributes")) return [];
  12991. return null;
  12992. }
  12993. const attrs = [];
  12994. const attributes = new Set();
  12995. do {
  12996. const node = this.startNode();
  12997. node.key = this.parseIdentifier(true);
  12998. if (node.key.name !== "type") {
  12999. this.raise(node.key.start, ErrorMessages.ModuleAttributeDifferentFromType, node.key.name);
  13000. }
  13001. if (attributes.has(node.key.name)) {
  13002. this.raise(node.key.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, node.key.name);
  13003. }
  13004. attributes.add(node.key.name);
  13005. this.expect(14);
  13006. if (!this.match(123)) {
  13007. throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue);
  13008. }
  13009. node.value = this.parseStringLiteral(this.state.value);
  13010. this.finishNode(node, "ImportAttribute");
  13011. attrs.push(node);
  13012. } while (this.eat(12));
  13013. return attrs;
  13014. }
  13015. maybeParseImportAssertions() {
  13016. if (this.isContextual(88) && !this.hasPrecedingLineBreak()) {
  13017. this.expectPlugin("importAssertions");
  13018. this.next();
  13019. } else {
  13020. if (this.hasPlugin("importAssertions")) return [];
  13021. return null;
  13022. }
  13023. this.eat(5);
  13024. const attrs = this.parseAssertEntries();
  13025. this.eat(8);
  13026. return attrs;
  13027. }
  13028. maybeParseDefaultImportSpecifier(node) {
  13029. if (this.shouldParseDefaultImport(node)) {
  13030. this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier", "default import specifier");
  13031. return true;
  13032. }
  13033. return false;
  13034. }
  13035. maybeParseStarImportSpecifier(node) {
  13036. if (this.match(49)) {
  13037. const specifier = this.startNode();
  13038. this.next();
  13039. this.expectContextual(87);
  13040. this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier", "import namespace specifier");
  13041. return true;
  13042. }
  13043. return false;
  13044. }
  13045. parseNamedImportSpecifiers(node) {
  13046. let first = true;
  13047. this.expect(5);
  13048. while (!this.eat(8)) {
  13049. if (first) {
  13050. first = false;
  13051. } else {
  13052. if (this.eat(14)) {
  13053. throw this.raise(this.state.start, ErrorMessages.DestructureNamedImport);
  13054. }
  13055. this.expect(12);
  13056. if (this.eat(8)) break;
  13057. }
  13058. const specifier = this.startNode();
  13059. const importedIsString = this.match(123);
  13060. const isMaybeTypeOnly = this.isContextual(120);
  13061. specifier.imported = this.parseModuleExportName();
  13062. const importSpecifier = this.parseImportSpecifier(specifier, importedIsString, node.importKind === "type" || node.importKind === "typeof", isMaybeTypeOnly);
  13063. node.specifiers.push(importSpecifier);
  13064. }
  13065. }
  13066. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly) {
  13067. if (this.eatContextual(87)) {
  13068. specifier.local = this.parseIdentifier();
  13069. } else {
  13070. const {
  13071. imported
  13072. } = specifier;
  13073. if (importedIsString) {
  13074. throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, imported.value);
  13075. }
  13076. this.checkReservedWord(imported.name, specifier.start, true, true);
  13077. if (!specifier.local) {
  13078. specifier.local = cloneIdentifier(imported);
  13079. }
  13080. }
  13081. this.checkLVal(specifier.local, "import specifier", BIND_LEXICAL);
  13082. return this.finishNode(specifier, "ImportSpecifier");
  13083. }
  13084. isThisParam(param) {
  13085. return param.type === "Identifier" && param.name === "this";
  13086. }
  13087. }
  13088. class Parser extends StatementParser {
  13089. constructor(options, input) {
  13090. options = getOptions(options);
  13091. super(options, input);
  13092. this.options = options;
  13093. this.initializeScopes();
  13094. this.plugins = pluginsMap(this.options.plugins);
  13095. this.filename = options.sourceFilename;
  13096. }
  13097. getScopeHandler() {
  13098. return ScopeHandler;
  13099. }
  13100. parse() {
  13101. this.enterInitialScopes();
  13102. const file = this.startNode();
  13103. const program = this.startNode();
  13104. this.nextToken();
  13105. file.errors = null;
  13106. this.parseTopLevel(file, program);
  13107. file.errors = this.state.errors;
  13108. return file;
  13109. }
  13110. }
  13111. function pluginsMap(plugins) {
  13112. const pluginMap = new Map();
  13113. for (const plugin of plugins) {
  13114. const [name, options] = Array.isArray(plugin) ? plugin : [plugin, {}];
  13115. if (!pluginMap.has(name)) pluginMap.set(name, options || {});
  13116. }
  13117. return pluginMap;
  13118. }
  13119. function parse(input, options) {
  13120. var _options;
  13121. if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") {
  13122. options = Object.assign({}, options);
  13123. try {
  13124. options.sourceType = "module";
  13125. const parser = getParser(options, input);
  13126. const ast = parser.parse();
  13127. if (parser.sawUnambiguousESM) {
  13128. return ast;
  13129. }
  13130. if (parser.ambiguousScriptDifferentAst) {
  13131. try {
  13132. options.sourceType = "script";
  13133. return getParser(options, input).parse();
  13134. } catch (_unused) {}
  13135. } else {
  13136. ast.program.sourceType = "script";
  13137. }
  13138. return ast;
  13139. } catch (moduleError) {
  13140. try {
  13141. options.sourceType = "script";
  13142. return getParser(options, input).parse();
  13143. } catch (_unused2) {}
  13144. throw moduleError;
  13145. }
  13146. } else {
  13147. return getParser(options, input).parse();
  13148. }
  13149. }
  13150. function parseExpression(input, options) {
  13151. const parser = getParser(options, input);
  13152. if (parser.options.strictMode) {
  13153. parser.state.strict = true;
  13154. }
  13155. return parser.getExpression();
  13156. }
  13157. function generateExportedTokenTypes(internalTokenTypes) {
  13158. const tokenTypes = {};
  13159. for (const typeName of Object.keys(internalTokenTypes)) {
  13160. tokenTypes[typeName] = getExportedToken(internalTokenTypes[typeName]);
  13161. }
  13162. return tokenTypes;
  13163. }
  13164. const tokTypes = generateExportedTokenTypes(tt);
  13165. function getParser(options, input) {
  13166. let cls = Parser;
  13167. if (options != null && options.plugins) {
  13168. validatePlugins(options.plugins);
  13169. cls = getParserClass(options.plugins);
  13170. }
  13171. return new cls(options, input);
  13172. }
  13173. const parserClassCache = {};
  13174. function getParserClass(pluginsFromOptions) {
  13175. const pluginList = mixinPluginNames.filter(name => hasPlugin(pluginsFromOptions, name));
  13176. const key = pluginList.join("/");
  13177. let cls = parserClassCache[key];
  13178. if (!cls) {
  13179. cls = Parser;
  13180. for (const plugin of pluginList) {
  13181. cls = mixinPlugins[plugin](cls);
  13182. }
  13183. parserClassCache[key] = cls;
  13184. }
  13185. return cls;
  13186. }
  13187. var parse_1 = parse;
  13188. var parseExpression_1 = parseExpression;
  13189. var tokTypes_1 = tokTypes;
  13190. //# sourceMappingURL=index.js.map
  13191. /*#__PURE__*/Object.defineProperty({
  13192. parse: parse_1,
  13193. parseExpression: parseExpression_1,
  13194. tokTypes: tokTypes_1
  13195. }, '__esModule', {value: true});
  13196. const isStaticExp = (p) => p.type === 4 /* SIMPLE_EXPRESSION */ && p.isStatic;
  13197. const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
  13198. function isCoreComponent(tag) {
  13199. if (isBuiltInType(tag, 'Teleport')) {
  13200. return TELEPORT;
  13201. }
  13202. else if (isBuiltInType(tag, 'Suspense')) {
  13203. return SUSPENSE;
  13204. }
  13205. else if (isBuiltInType(tag, 'KeepAlive')) {
  13206. return KEEP_ALIVE;
  13207. }
  13208. else if (isBuiltInType(tag, 'BaseTransition')) {
  13209. return BASE_TRANSITION;
  13210. }
  13211. }
  13212. const nonIdentifierRE = /^\d|[^\$\w]/;
  13213. const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
  13214. const validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/;
  13215. const validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/;
  13216. const whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g;
  13217. /**
  13218. * Simple lexer to check if an expression is a member expression. This is
  13219. * lax and only checks validity at the root level (i.e. does not validate exps
  13220. * inside square brackets), but it's ok since these are only used on template
  13221. * expressions and false positives are invalid expressions in the first place.
  13222. */
  13223. const isMemberExpressionBrowser = (path) => {
  13224. // remove whitespaces around . or [ first
  13225. path = path.trim().replace(whitespaceRE, s => s.trim());
  13226. let state = 0 /* inMemberExp */;
  13227. let stateStack = [];
  13228. let currentOpenBracketCount = 0;
  13229. let currentOpenParensCount = 0;
  13230. let currentStringType = null;
  13231. for (let i = 0; i < path.length; i++) {
  13232. const char = path.charAt(i);
  13233. switch (state) {
  13234. case 0 /* inMemberExp */:
  13235. if (char === '[') {
  13236. stateStack.push(state);
  13237. state = 1 /* inBrackets */;
  13238. currentOpenBracketCount++;
  13239. }
  13240. else if (char === '(') {
  13241. stateStack.push(state);
  13242. state = 2 /* inParens */;
  13243. currentOpenParensCount++;
  13244. }
  13245. else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) {
  13246. return false;
  13247. }
  13248. break;
  13249. case 1 /* inBrackets */:
  13250. if (char === `'` || char === `"` || char === '`') {
  13251. stateStack.push(state);
  13252. state = 3 /* inString */;
  13253. currentStringType = char;
  13254. }
  13255. else if (char === `[`) {
  13256. currentOpenBracketCount++;
  13257. }
  13258. else if (char === `]`) {
  13259. if (!--currentOpenBracketCount) {
  13260. state = stateStack.pop();
  13261. }
  13262. }
  13263. break;
  13264. case 2 /* inParens */:
  13265. if (char === `'` || char === `"` || char === '`') {
  13266. stateStack.push(state);
  13267. state = 3 /* inString */;
  13268. currentStringType = char;
  13269. }
  13270. else if (char === `(`) {
  13271. currentOpenParensCount++;
  13272. }
  13273. else if (char === `)`) {
  13274. // if the exp ends as a call then it should not be considered valid
  13275. if (i === path.length - 1) {
  13276. return false;
  13277. }
  13278. if (!--currentOpenParensCount) {
  13279. state = stateStack.pop();
  13280. }
  13281. }
  13282. break;
  13283. case 3 /* inString */:
  13284. if (char === currentStringType) {
  13285. state = stateStack.pop();
  13286. currentStringType = null;
  13287. }
  13288. break;
  13289. }
  13290. }
  13291. return !currentOpenBracketCount && !currentOpenParensCount;
  13292. };
  13293. const isMemberExpressionNode = (path, context) => {
  13294. try {
  13295. let ret = parseExpression_1(path, {
  13296. plugins: context.expressionPlugins
  13297. });
  13298. if (ret.type === 'TSAsExpression' || ret.type === 'TSTypeAssertion') {
  13299. ret = ret.expression;
  13300. }
  13301. return (ret.type === 'MemberExpression' ||
  13302. ret.type === 'OptionalMemberExpression' ||
  13303. ret.type === 'Identifier');
  13304. }
  13305. catch (e) {
  13306. return false;
  13307. }
  13308. };
  13309. const isMemberExpression = isMemberExpressionNode;
  13310. function getInnerRange(loc, offset, length) {
  13311. const source = loc.source.slice(offset, offset + length);
  13312. const newLoc = {
  13313. source,
  13314. start: advancePositionWithClone(loc.start, loc.source, offset),
  13315. end: loc.end
  13316. };
  13317. if (length != null) {
  13318. newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
  13319. }
  13320. return newLoc;
  13321. }
  13322. function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
  13323. return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
  13324. }
  13325. // advance by mutation without cloning (for performance reasons), since this
  13326. // gets called a lot in the parser
  13327. function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
  13328. let linesCount = 0;
  13329. let lastNewLinePos = -1;
  13330. for (let i = 0; i < numberOfCharacters; i++) {
  13331. if (source.charCodeAt(i) === 10 /* newline char code */) {
  13332. linesCount++;
  13333. lastNewLinePos = i;
  13334. }
  13335. }
  13336. pos.offset += numberOfCharacters;
  13337. pos.line += linesCount;
  13338. pos.column =
  13339. lastNewLinePos === -1
  13340. ? pos.column + numberOfCharacters
  13341. : numberOfCharacters - lastNewLinePos;
  13342. return pos;
  13343. }
  13344. function assert$1(condition, msg) {
  13345. /* istanbul ignore if */
  13346. if (!condition) {
  13347. throw new Error(msg || `unexpected compiler condition`);
  13348. }
  13349. }
  13350. function findDir(node, name, allowEmpty = false) {
  13351. for (let i = 0; i < node.props.length; i++) {
  13352. const p = node.props[i];
  13353. if (p.type === 7 /* DIRECTIVE */ &&
  13354. (allowEmpty || p.exp) &&
  13355. (isString(name) ? p.name === name : name.test(p.name))) {
  13356. return p;
  13357. }
  13358. }
  13359. }
  13360. function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
  13361. for (let i = 0; i < node.props.length; i++) {
  13362. const p = node.props[i];
  13363. if (p.type === 6 /* ATTRIBUTE */) {
  13364. if (dynamicOnly)
  13365. continue;
  13366. if (p.name === name && (p.value || allowEmpty)) {
  13367. return p;
  13368. }
  13369. }
  13370. else if (p.name === 'bind' &&
  13371. (p.exp || allowEmpty) &&
  13372. isStaticArgOf(p.arg, name)) {
  13373. return p;
  13374. }
  13375. }
  13376. }
  13377. function isStaticArgOf(arg, name) {
  13378. return !!(arg && isStaticExp(arg) && arg.content === name);
  13379. }
  13380. function hasDynamicKeyVBind(node) {
  13381. return node.props.some(p => p.type === 7 /* DIRECTIVE */ &&
  13382. p.name === 'bind' &&
  13383. (!p.arg || // v-bind="obj"
  13384. p.arg.type !== 4 /* SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
  13385. !p.arg.isStatic) // v-bind:[foo]
  13386. );
  13387. }
  13388. function isText(node) {
  13389. return node.type === 5 /* INTERPOLATION */ || node.type === 2 /* TEXT */;
  13390. }
  13391. function isVSlot(p) {
  13392. return p.type === 7 /* DIRECTIVE */ && p.name === 'slot';
  13393. }
  13394. function isTemplateNode(node) {
  13395. return (node.type === 1 /* ELEMENT */ && node.tagType === 3 /* TEMPLATE */);
  13396. }
  13397. function isSlotOutlet(node) {
  13398. return node.type === 1 /* ELEMENT */ && node.tagType === 2 /* SLOT */;
  13399. }
  13400. function getVNodeHelper(ssr, isComponent) {
  13401. return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE;
  13402. }
  13403. function getVNodeBlockHelper(ssr, isComponent) {
  13404. return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK;
  13405. }
  13406. const propsHelperSet = new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]);
  13407. function getUnnormalizedProps(props, callPath = []) {
  13408. if (props &&
  13409. !isString(props) &&
  13410. props.type === 14 /* JS_CALL_EXPRESSION */) {
  13411. const callee = props.callee;
  13412. if (!isString(callee) && propsHelperSet.has(callee)) {
  13413. return getUnnormalizedProps(props.arguments[0], callPath.concat(props));
  13414. }
  13415. }
  13416. return [props, callPath];
  13417. }
  13418. function injectProp(node, prop, context) {
  13419. let propsWithInjection;
  13420. /**
  13421. * 1. mergeProps(...)
  13422. * 2. toHandlers(...)
  13423. * 3. normalizeProps(...)
  13424. * 4. normalizeProps(guardReactiveProps(...))
  13425. *
  13426. * we need to get the real props before normalization
  13427. */
  13428. let props = node.type === 13 /* VNODE_CALL */ ? node.props : node.arguments[2];
  13429. let callPath = [];
  13430. let parentCall;
  13431. if (props &&
  13432. !isString(props) &&
  13433. props.type === 14 /* JS_CALL_EXPRESSION */) {
  13434. const ret = getUnnormalizedProps(props);
  13435. props = ret[0];
  13436. callPath = ret[1];
  13437. parentCall = callPath[callPath.length - 1];
  13438. }
  13439. if (props == null || isString(props)) {
  13440. propsWithInjection = createObjectExpression([prop]);
  13441. }
  13442. else if (props.type === 14 /* JS_CALL_EXPRESSION */) {
  13443. // merged props... add ours
  13444. // only inject key to object literal if it's the first argument so that
  13445. // if doesn't override user provided keys
  13446. const first = props.arguments[0];
  13447. if (!isString(first) && first.type === 15 /* JS_OBJECT_EXPRESSION */) {
  13448. first.properties.unshift(prop);
  13449. }
  13450. else {
  13451. if (props.callee === TO_HANDLERS) {
  13452. // #2366
  13453. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  13454. createObjectExpression([prop]),
  13455. props
  13456. ]);
  13457. }
  13458. else {
  13459. props.arguments.unshift(createObjectExpression([prop]));
  13460. }
  13461. }
  13462. !propsWithInjection && (propsWithInjection = props);
  13463. }
  13464. else if (props.type === 15 /* JS_OBJECT_EXPRESSION */) {
  13465. let alreadyExists = false;
  13466. // check existing key to avoid overriding user provided keys
  13467. if (prop.key.type === 4 /* SIMPLE_EXPRESSION */) {
  13468. const propKeyName = prop.key.content;
  13469. alreadyExists = props.properties.some(p => p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
  13470. p.key.content === propKeyName);
  13471. }
  13472. if (!alreadyExists) {
  13473. props.properties.unshift(prop);
  13474. }
  13475. propsWithInjection = props;
  13476. }
  13477. else {
  13478. // single v-bind with expression, return a merged replacement
  13479. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  13480. createObjectExpression([prop]),
  13481. props
  13482. ]);
  13483. // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(props))`,
  13484. // it will be rewritten as `normalizeProps(mergeProps({ key: 0 }, props))`,
  13485. // the `guardReactiveProps` will no longer be needed
  13486. if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) {
  13487. parentCall = callPath[callPath.length - 2];
  13488. }
  13489. }
  13490. if (node.type === 13 /* VNODE_CALL */) {
  13491. if (parentCall) {
  13492. parentCall.arguments[0] = propsWithInjection;
  13493. }
  13494. else {
  13495. node.props = propsWithInjection;
  13496. }
  13497. }
  13498. else {
  13499. if (parentCall) {
  13500. parentCall.arguments[0] = propsWithInjection;
  13501. }
  13502. else {
  13503. node.arguments[2] = propsWithInjection;
  13504. }
  13505. }
  13506. }
  13507. function toValidAssetId(name, type) {
  13508. // see issue#4422, we need adding identifier on validAssetId if variable `name` has specific character
  13509. return `_${type}_${name.replace(/[^\w]/g, (searchValue, replaceValue) => {
  13510. return searchValue === '-' ? '_' : name.charCodeAt(replaceValue).toString();
  13511. })}`;
  13512. }
  13513. // Check if a node contains expressions that reference current context scope ids
  13514. function hasScopeRef(node, ids) {
  13515. if (!node || Object.keys(ids).length === 0) {
  13516. return false;
  13517. }
  13518. switch (node.type) {
  13519. case 1 /* ELEMENT */:
  13520. for (let i = 0; i < node.props.length; i++) {
  13521. const p = node.props[i];
  13522. if (p.type === 7 /* DIRECTIVE */ &&
  13523. (hasScopeRef(p.arg, ids) || hasScopeRef(p.exp, ids))) {
  13524. return true;
  13525. }
  13526. }
  13527. return node.children.some(c => hasScopeRef(c, ids));
  13528. case 11 /* FOR */:
  13529. if (hasScopeRef(node.source, ids)) {
  13530. return true;
  13531. }
  13532. return node.children.some(c => hasScopeRef(c, ids));
  13533. case 9 /* IF */:
  13534. return node.branches.some(b => hasScopeRef(b, ids));
  13535. case 10 /* IF_BRANCH */:
  13536. if (hasScopeRef(node.condition, ids)) {
  13537. return true;
  13538. }
  13539. return node.children.some(c => hasScopeRef(c, ids));
  13540. case 4 /* SIMPLE_EXPRESSION */:
  13541. return (!node.isStatic &&
  13542. isSimpleIdentifier(node.content) &&
  13543. !!ids[node.content]);
  13544. case 8 /* COMPOUND_EXPRESSION */:
  13545. return node.children.some(c => isObject(c) && hasScopeRef(c, ids));
  13546. case 5 /* INTERPOLATION */:
  13547. case 12 /* TEXT_CALL */:
  13548. return hasScopeRef(node.content, ids);
  13549. case 2 /* TEXT */:
  13550. case 3 /* COMMENT */:
  13551. return false;
  13552. default:
  13553. return false;
  13554. }
  13555. }
  13556. function getMemoedVNodeCall(node) {
  13557. if (node.type === 14 /* JS_CALL_EXPRESSION */ && node.callee === WITH_MEMO) {
  13558. return node.arguments[1].returns;
  13559. }
  13560. else {
  13561. return node;
  13562. }
  13563. }
  13564. function makeBlock(node, { helper, removeHelper, inSSR }) {
  13565. if (!node.isBlock) {
  13566. node.isBlock = true;
  13567. removeHelper(getVNodeHelper(inSSR, node.isComponent));
  13568. helper(OPEN_BLOCK);
  13569. helper(getVNodeBlockHelper(inSSR, node.isComponent));
  13570. }
  13571. }
  13572. const deprecationData = {
  13573. ["COMPILER_IS_ON_ELEMENT" /* COMPILER_IS_ON_ELEMENT */]: {
  13574. message: `Platform-native elements with "is" prop will no longer be ` +
  13575. `treated as components in Vue 3 unless the "is" value is explicitly ` +
  13576. `prefixed with "vue:".`,
  13577. link: `https://v3.vuejs.org/guide/migration/custom-elements-interop.html`
  13578. },
  13579. ["COMPILER_V_BIND_SYNC" /* COMPILER_V_BIND_SYNC */]: {
  13580. message: key => `.sync modifier for v-bind has been removed. Use v-model with ` +
  13581. `argument instead. \`v-bind:${key}.sync\` should be changed to ` +
  13582. `\`v-model:${key}\`.`,
  13583. link: `https://v3.vuejs.org/guide/migration/v-model.html`
  13584. },
  13585. ["COMPILER_V_BIND_PROP" /* COMPILER_V_BIND_PROP */]: {
  13586. message: `.prop modifier for v-bind has been removed and no longer necessary. ` +
  13587. `Vue 3 will automatically set a binding as DOM property when appropriate.`
  13588. },
  13589. ["COMPILER_V_BIND_OBJECT_ORDER" /* COMPILER_V_BIND_OBJECT_ORDER */]: {
  13590. message: `v-bind="obj" usage is now order sensitive and behaves like JavaScript ` +
  13591. `object spread: it will now overwrite an existing non-mergeable attribute ` +
  13592. `that appears before v-bind in the case of conflict. ` +
  13593. `To retain 2.x behavior, move v-bind to make it the first attribute. ` +
  13594. `You can also suppress this warning if the usage is intended.`,
  13595. link: `https://v3.vuejs.org/guide/migration/v-bind.html`
  13596. },
  13597. ["COMPILER_V_ON_NATIVE" /* COMPILER_V_ON_NATIVE */]: {
  13598. message: `.native modifier for v-on has been removed as is no longer necessary.`,
  13599. link: `https://v3.vuejs.org/guide/migration/v-on-native-modifier-removed.html`
  13600. },
  13601. ["COMPILER_V_IF_V_FOR_PRECEDENCE" /* COMPILER_V_IF_V_FOR_PRECEDENCE */]: {
  13602. message: `v-if / v-for precedence when used on the same element has changed ` +
  13603. `in Vue 3: v-if now takes higher precedence and will no longer have ` +
  13604. `access to v-for scope variables. It is best to avoid the ambiguity ` +
  13605. `with <template> tags or use a computed property that filters v-for ` +
  13606. `data source.`,
  13607. link: `https://v3.vuejs.org/guide/migration/v-if-v-for.html`
  13608. },
  13609. ["COMPILER_NATIVE_TEMPLATE" /* COMPILER_NATIVE_TEMPLATE */]: {
  13610. message: `<template> with no special directives will render as a native template ` +
  13611. `element instead of its inner content in Vue 3.`
  13612. },
  13613. ["COMPILER_INLINE_TEMPLATE" /* COMPILER_INLINE_TEMPLATE */]: {
  13614. message: `"inline-template" has been removed in Vue 3.`,
  13615. link: `https://v3.vuejs.org/guide/migration/inline-template-attribute.html`
  13616. },
  13617. ["COMPILER_FILTER" /* COMPILER_FILTERS */]: {
  13618. message: `filters have been removed in Vue 3. ` +
  13619. `The "|" symbol will be treated as native JavaScript bitwise OR operator. ` +
  13620. `Use method calls or computed properties instead.`,
  13621. link: `https://v3.vuejs.org/guide/migration/filters.html`
  13622. }
  13623. };
  13624. function getCompatValue(key, context) {
  13625. const config = context.options
  13626. ? context.options.compatConfig
  13627. : context.compatConfig;
  13628. const value = config && config[key];
  13629. if (key === 'MODE') {
  13630. return value || 3; // compiler defaults to v3 behavior
  13631. }
  13632. else {
  13633. return value;
  13634. }
  13635. }
  13636. function isCompatEnabled(key, context) {
  13637. const mode = getCompatValue('MODE', context);
  13638. const value = getCompatValue(key, context);
  13639. // in v3 mode, only enable if explicitly set to true
  13640. // otherwise enable for any non-false value
  13641. return mode === 3 ? value === true : value !== false;
  13642. }
  13643. function checkCompatEnabled(key, context, loc, ...args) {
  13644. const enabled = isCompatEnabled(key, context);
  13645. if (enabled) {
  13646. warnDeprecation(key, context, loc, ...args);
  13647. }
  13648. return enabled;
  13649. }
  13650. function warnDeprecation(key, context, loc, ...args) {
  13651. const val = getCompatValue(key, context);
  13652. if (val === 'suppress-warning') {
  13653. return;
  13654. }
  13655. const { message, link } = deprecationData[key];
  13656. const msg = `(deprecation ${key}) ${typeof message === 'function' ? message(...args) : message}${link ? `\n Details: ${link}` : ``}`;
  13657. const err = new SyntaxError(msg);
  13658. err.code = key;
  13659. if (loc)
  13660. err.loc = loc;
  13661. context.onWarn(err);
  13662. }
  13663. // The default decoder only provides escapes for characters reserved as part of
  13664. // the template syntax, and is only used if the custom renderer did not provide
  13665. // a platform-specific decoder.
  13666. const decodeRE = /&(gt|lt|amp|apos|quot);/g;
  13667. const decodeMap = {
  13668. gt: '>',
  13669. lt: '<',
  13670. amp: '&',
  13671. apos: "'",
  13672. quot: '"'
  13673. };
  13674. const defaultParserOptions = {
  13675. delimiters: [`{{`, `}}`],
  13676. getNamespace: () => 0 /* HTML */,
  13677. getTextMode: () => 0 /* DATA */,
  13678. isVoidTag: NO,
  13679. isPreTag: NO,
  13680. isCustomElement: NO,
  13681. decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
  13682. onError: defaultOnError,
  13683. onWarn: defaultOnWarn,
  13684. comments: true
  13685. };
  13686. function baseParse(content, options = {}) {
  13687. const context = createParserContext(content, options);
  13688. const start = getCursor(context);
  13689. return createRoot(parseChildren(context, 0 /* DATA */, []), getSelection(context, start));
  13690. }
  13691. function createParserContext(content, rawOptions) {
  13692. const options = extend({}, defaultParserOptions);
  13693. let key;
  13694. for (key in rawOptions) {
  13695. // @ts-ignore
  13696. options[key] =
  13697. rawOptions[key] === undefined
  13698. ? defaultParserOptions[key]
  13699. : rawOptions[key];
  13700. }
  13701. return {
  13702. options,
  13703. column: 1,
  13704. line: 1,
  13705. offset: 0,
  13706. originalSource: content,
  13707. source: content,
  13708. inPre: false,
  13709. inVPre: false,
  13710. onWarn: options.onWarn
  13711. };
  13712. }
  13713. function parseChildren(context, mode, ancestors) {
  13714. const parent = last(ancestors);
  13715. const ns = parent ? parent.ns : 0 /* HTML */;
  13716. const nodes = [];
  13717. while (!isEnd(context, mode, ancestors)) {
  13718. const s = context.source;
  13719. let node = undefined;
  13720. if (mode === 0 /* DATA */ || mode === 1 /* RCDATA */) {
  13721. if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
  13722. // '{{'
  13723. node = parseInterpolation(context, mode);
  13724. }
  13725. else if (mode === 0 /* DATA */ && s[0] === '<') {
  13726. // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
  13727. if (s.length === 1) {
  13728. emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 1);
  13729. }
  13730. else if (s[1] === '!') {
  13731. // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
  13732. if (startsWith(s, '<!--')) {
  13733. node = parseComment(context);
  13734. }
  13735. else if (startsWith(s, '<!DOCTYPE')) {
  13736. // Ignore DOCTYPE by a limitation.
  13737. node = parseBogusComment(context);
  13738. }
  13739. else if (startsWith(s, '<![CDATA[')) {
  13740. if (ns !== 0 /* HTML */) {
  13741. node = parseCDATA(context, ancestors);
  13742. }
  13743. else {
  13744. emitError(context, 1 /* CDATA_IN_HTML_CONTENT */);
  13745. node = parseBogusComment(context);
  13746. }
  13747. }
  13748. else {
  13749. emitError(context, 11 /* INCORRECTLY_OPENED_COMMENT */);
  13750. node = parseBogusComment(context);
  13751. }
  13752. }
  13753. else if (s[1] === '/') {
  13754. // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
  13755. if (s.length === 2) {
  13756. emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 2);
  13757. }
  13758. else if (s[2] === '>') {
  13759. emitError(context, 14 /* MISSING_END_TAG_NAME */, 2);
  13760. advanceBy(context, 3);
  13761. continue;
  13762. }
  13763. else if (/[a-z]/i.test(s[2])) {
  13764. emitError(context, 23 /* X_INVALID_END_TAG */);
  13765. parseTag(context, 1 /* End */, parent);
  13766. continue;
  13767. }
  13768. else {
  13769. emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
  13770. node = parseBogusComment(context);
  13771. }
  13772. }
  13773. else if (/[a-z]/i.test(s[1])) {
  13774. node = parseElement(context, ancestors);
  13775. }
  13776. else if (s[1] === '?') {
  13777. emitError(context, 21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
  13778. node = parseBogusComment(context);
  13779. }
  13780. else {
  13781. emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
  13782. }
  13783. }
  13784. }
  13785. if (!node) {
  13786. node = parseText(context, mode);
  13787. }
  13788. if (isArray(node)) {
  13789. for (let i = 0; i < node.length; i++) {
  13790. pushNode(nodes, node[i]);
  13791. }
  13792. }
  13793. else {
  13794. pushNode(nodes, node);
  13795. }
  13796. }
  13797. // Whitespace handling strategy like v2
  13798. let removedWhitespace = false;
  13799. if (mode !== 2 /* RAWTEXT */ && mode !== 1 /* RCDATA */) {
  13800. const shouldCondense = context.options.whitespace !== 'preserve';
  13801. for (let i = 0; i < nodes.length; i++) {
  13802. const node = nodes[i];
  13803. if (!context.inPre && node.type === 2 /* TEXT */) {
  13804. if (!/[^\t\r\n\f ]/.test(node.content)) {
  13805. const prev = nodes[i - 1];
  13806. const next = nodes[i + 1];
  13807. // Remove if:
  13808. // - the whitespace is the first or last node, or:
  13809. // - (condense mode) the whitespace is adjacent to a comment, or:
  13810. // - (condense mode) the whitespace is between two elements AND contains newline
  13811. if (!prev ||
  13812. !next ||
  13813. (shouldCondense &&
  13814. (prev.type === 3 /* COMMENT */ ||
  13815. next.type === 3 /* COMMENT */ ||
  13816. (prev.type === 1 /* ELEMENT */ &&
  13817. next.type === 1 /* ELEMENT */ &&
  13818. /[\r\n]/.test(node.content))))) {
  13819. removedWhitespace = true;
  13820. nodes[i] = null;
  13821. }
  13822. else {
  13823. // Otherwise, the whitespace is condensed into a single space
  13824. node.content = ' ';
  13825. }
  13826. }
  13827. else if (shouldCondense) {
  13828. // in condense mode, consecutive whitespaces in text are condensed
  13829. // down to a single space.
  13830. node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
  13831. }
  13832. }
  13833. // Remove comment nodes if desired by configuration.
  13834. else if (node.type === 3 /* COMMENT */ && !context.options.comments) {
  13835. removedWhitespace = true;
  13836. nodes[i] = null;
  13837. }
  13838. }
  13839. if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
  13840. // remove leading newline per html spec
  13841. // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
  13842. const first = nodes[0];
  13843. if (first && first.type === 2 /* TEXT */) {
  13844. first.content = first.content.replace(/^\r?\n/, '');
  13845. }
  13846. }
  13847. }
  13848. return removedWhitespace ? nodes.filter(Boolean) : nodes;
  13849. }
  13850. function pushNode(nodes, node) {
  13851. if (node.type === 2 /* TEXT */) {
  13852. const prev = last(nodes);
  13853. // Merge if both this and the previous node are text and those are
  13854. // consecutive. This happens for cases like "a < b".
  13855. if (prev &&
  13856. prev.type === 2 /* TEXT */ &&
  13857. prev.loc.end.offset === node.loc.start.offset) {
  13858. prev.content += node.content;
  13859. prev.loc.end = node.loc.end;
  13860. prev.loc.source += node.loc.source;
  13861. return;
  13862. }
  13863. }
  13864. nodes.push(node);
  13865. }
  13866. function parseCDATA(context, ancestors) {
  13867. advanceBy(context, 9);
  13868. const nodes = parseChildren(context, 3 /* CDATA */, ancestors);
  13869. if (context.source.length === 0) {
  13870. emitError(context, 6 /* EOF_IN_CDATA */);
  13871. }
  13872. else {
  13873. advanceBy(context, 3);
  13874. }
  13875. return nodes;
  13876. }
  13877. function parseComment(context) {
  13878. const start = getCursor(context);
  13879. let content;
  13880. // Regular comment.
  13881. const match = /--(\!)?>/.exec(context.source);
  13882. if (!match) {
  13883. content = context.source.slice(4);
  13884. advanceBy(context, context.source.length);
  13885. emitError(context, 7 /* EOF_IN_COMMENT */);
  13886. }
  13887. else {
  13888. if (match.index <= 3) {
  13889. emitError(context, 0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
  13890. }
  13891. if (match[1]) {
  13892. emitError(context, 10 /* INCORRECTLY_CLOSED_COMMENT */);
  13893. }
  13894. content = context.source.slice(4, match.index);
  13895. // Advancing with reporting nested comments.
  13896. const s = context.source.slice(0, match.index);
  13897. let prevIndex = 1, nestedIndex = 0;
  13898. while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
  13899. advanceBy(context, nestedIndex - prevIndex + 1);
  13900. if (nestedIndex + 4 < s.length) {
  13901. emitError(context, 16 /* NESTED_COMMENT */);
  13902. }
  13903. prevIndex = nestedIndex + 1;
  13904. }
  13905. advanceBy(context, match.index + match[0].length - prevIndex + 1);
  13906. }
  13907. return {
  13908. type: 3 /* COMMENT */,
  13909. content,
  13910. loc: getSelection(context, start)
  13911. };
  13912. }
  13913. function parseBogusComment(context) {
  13914. const start = getCursor(context);
  13915. const contentStart = context.source[1] === '?' ? 1 : 2;
  13916. let content;
  13917. const closeIndex = context.source.indexOf('>');
  13918. if (closeIndex === -1) {
  13919. content = context.source.slice(contentStart);
  13920. advanceBy(context, context.source.length);
  13921. }
  13922. else {
  13923. content = context.source.slice(contentStart, closeIndex);
  13924. advanceBy(context, closeIndex + 1);
  13925. }
  13926. return {
  13927. type: 3 /* COMMENT */,
  13928. content,
  13929. loc: getSelection(context, start)
  13930. };
  13931. }
  13932. function parseElement(context, ancestors) {
  13933. // Start tag.
  13934. const wasInPre = context.inPre;
  13935. const wasInVPre = context.inVPre;
  13936. const parent = last(ancestors);
  13937. const element = parseTag(context, 0 /* Start */, parent);
  13938. const isPreBoundary = context.inPre && !wasInPre;
  13939. const isVPreBoundary = context.inVPre && !wasInVPre;
  13940. if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
  13941. // #4030 self-closing <pre> tag
  13942. if (isPreBoundary) {
  13943. context.inPre = false;
  13944. }
  13945. if (isVPreBoundary) {
  13946. context.inVPre = false;
  13947. }
  13948. return element;
  13949. }
  13950. // Children.
  13951. ancestors.push(element);
  13952. const mode = context.options.getTextMode(element, parent);
  13953. const children = parseChildren(context, mode, ancestors);
  13954. ancestors.pop();
  13955. element.children = children;
  13956. // End tag.
  13957. if (startsWithEndTagOpen(context.source, element.tag)) {
  13958. parseTag(context, 1 /* End */, parent);
  13959. }
  13960. else {
  13961. emitError(context, 24 /* X_MISSING_END_TAG */, 0, element.loc.start);
  13962. if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
  13963. const first = children[0];
  13964. if (first && startsWith(first.loc.source, '<!--')) {
  13965. emitError(context, 8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
  13966. }
  13967. }
  13968. }
  13969. element.loc = getSelection(context, element.loc.start);
  13970. if (isPreBoundary) {
  13971. context.inPre = false;
  13972. }
  13973. if (isVPreBoundary) {
  13974. context.inVPre = false;
  13975. }
  13976. return element;
  13977. }
  13978. const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
  13979. function parseTag(context, type, parent) {
  13980. // Tag open.
  13981. const start = getCursor(context);
  13982. const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
  13983. const tag = match[1];
  13984. const ns = context.options.getNamespace(tag, parent);
  13985. advanceBy(context, match[0].length);
  13986. advanceSpaces(context);
  13987. // save current state in case we need to re-parse attributes with v-pre
  13988. const cursor = getCursor(context);
  13989. const currentSource = context.source;
  13990. // check <pre> tag
  13991. if (context.options.isPreTag(tag)) {
  13992. context.inPre = true;
  13993. }
  13994. // Attributes.
  13995. let props = parseAttributes(context, type);
  13996. // check v-pre
  13997. if (type === 0 /* Start */ &&
  13998. !context.inVPre &&
  13999. props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'pre')) {
  14000. context.inVPre = true;
  14001. // reset context
  14002. extend(context, cursor);
  14003. context.source = currentSource;
  14004. // re-parse attrs and filter out v-pre itself
  14005. props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
  14006. }
  14007. // Tag close.
  14008. let isSelfClosing = false;
  14009. if (context.source.length === 0) {
  14010. emitError(context, 9 /* EOF_IN_TAG */);
  14011. }
  14012. else {
  14013. isSelfClosing = startsWith(context.source, '/>');
  14014. if (type === 1 /* End */ && isSelfClosing) {
  14015. emitError(context, 4 /* END_TAG_WITH_TRAILING_SOLIDUS */);
  14016. }
  14017. advanceBy(context, isSelfClosing ? 2 : 1);
  14018. }
  14019. if (type === 1 /* End */) {
  14020. return;
  14021. }
  14022. let tagType = 0 /* ELEMENT */;
  14023. if (!context.inVPre) {
  14024. if (tag === 'slot') {
  14025. tagType = 2 /* SLOT */;
  14026. }
  14027. else if (tag === 'template') {
  14028. if (props.some(p => p.type === 7 /* DIRECTIVE */ && isSpecialTemplateDirective(p.name))) {
  14029. tagType = 3 /* TEMPLATE */;
  14030. }
  14031. }
  14032. else if (isComponent(tag, props, context)) {
  14033. tagType = 1 /* COMPONENT */;
  14034. }
  14035. }
  14036. return {
  14037. type: 1 /* ELEMENT */,
  14038. ns,
  14039. tag,
  14040. tagType,
  14041. props,
  14042. isSelfClosing,
  14043. children: [],
  14044. loc: getSelection(context, start),
  14045. codegenNode: undefined // to be created during transform phase
  14046. };
  14047. }
  14048. function isComponent(tag, props, context) {
  14049. const options = context.options;
  14050. if (options.isCustomElement(tag)) {
  14051. return false;
  14052. }
  14053. if (tag === 'component' ||
  14054. /^[A-Z]/.test(tag) ||
  14055. isCoreComponent(tag) ||
  14056. (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
  14057. (options.isNativeTag && !options.isNativeTag(tag))) {
  14058. return true;
  14059. }
  14060. // at this point the tag should be a native tag, but check for potential "is"
  14061. // casting
  14062. for (let i = 0; i < props.length; i++) {
  14063. const p = props[i];
  14064. if (p.type === 6 /* ATTRIBUTE */) {
  14065. if (p.name === 'is' && p.value) {
  14066. if (p.value.content.startsWith('vue:')) {
  14067. return true;
  14068. }
  14069. }
  14070. }
  14071. else {
  14072. // directive
  14073. // v-is (TODO Deprecate)
  14074. if (p.name === 'is') {
  14075. return true;
  14076. }
  14077. else if (
  14078. // :is on plain element - only treat as component in compat mode
  14079. p.name === 'bind' &&
  14080. isStaticArgOf(p.arg, 'is') &&
  14081. false &&
  14082. checkCompatEnabled("COMPILER_IS_ON_ELEMENT" /* COMPILER_IS_ON_ELEMENT */, context, p.loc)) {
  14083. return true;
  14084. }
  14085. }
  14086. }
  14087. }
  14088. function parseAttributes(context, type) {
  14089. const props = [];
  14090. const attributeNames = new Set();
  14091. while (context.source.length > 0 &&
  14092. !startsWith(context.source, '>') &&
  14093. !startsWith(context.source, '/>')) {
  14094. if (startsWith(context.source, '/')) {
  14095. emitError(context, 22 /* UNEXPECTED_SOLIDUS_IN_TAG */);
  14096. advanceBy(context, 1);
  14097. advanceSpaces(context);
  14098. continue;
  14099. }
  14100. if (type === 1 /* End */) {
  14101. emitError(context, 3 /* END_TAG_WITH_ATTRIBUTES */);
  14102. }
  14103. const attr = parseAttribute(context, attributeNames);
  14104. // Trim whitespace between class
  14105. // https://github.com/vuejs/vue-next/issues/4251
  14106. if (attr.type === 6 /* ATTRIBUTE */ &&
  14107. attr.value &&
  14108. attr.name === 'class') {
  14109. attr.value.content = attr.value.content.replace(/\s+/g, ' ').trim();
  14110. }
  14111. if (type === 0 /* Start */) {
  14112. props.push(attr);
  14113. }
  14114. if (/^[^\t\r\n\f />]/.test(context.source)) {
  14115. emitError(context, 15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
  14116. }
  14117. advanceSpaces(context);
  14118. }
  14119. return props;
  14120. }
  14121. function parseAttribute(context, nameSet) {
  14122. // Name.
  14123. const start = getCursor(context);
  14124. const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
  14125. const name = match[0];
  14126. if (nameSet.has(name)) {
  14127. emitError(context, 2 /* DUPLICATE_ATTRIBUTE */);
  14128. }
  14129. nameSet.add(name);
  14130. if (name[0] === '=') {
  14131. emitError(context, 19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
  14132. }
  14133. {
  14134. const pattern = /["'<]/g;
  14135. let m;
  14136. while ((m = pattern.exec(name))) {
  14137. emitError(context, 17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
  14138. }
  14139. }
  14140. advanceBy(context, name.length);
  14141. // Value
  14142. let value = undefined;
  14143. if (/^[\t\r\n\f ]*=/.test(context.source)) {
  14144. advanceSpaces(context);
  14145. advanceBy(context, 1);
  14146. advanceSpaces(context);
  14147. value = parseAttributeValue(context);
  14148. if (!value) {
  14149. emitError(context, 13 /* MISSING_ATTRIBUTE_VALUE */);
  14150. }
  14151. }
  14152. const loc = getSelection(context, start);
  14153. if (!context.inVPre && /^(v-[A-Za-z0-9-]|:|\.|@|#)/.test(name)) {
  14154. const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^\.|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
  14155. let isPropShorthand = startsWith(name, '.');
  14156. let dirName = match[1] ||
  14157. (isPropShorthand || startsWith(name, ':')
  14158. ? 'bind'
  14159. : startsWith(name, '@')
  14160. ? 'on'
  14161. : 'slot');
  14162. let arg;
  14163. if (match[2]) {
  14164. const isSlot = dirName === 'slot';
  14165. const startOffset = name.lastIndexOf(match[2]);
  14166. const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
  14167. let content = match[2];
  14168. let isStatic = true;
  14169. if (content.startsWith('[')) {
  14170. isStatic = false;
  14171. if (!content.endsWith(']')) {
  14172. emitError(context, 27 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
  14173. content = content.slice(1);
  14174. }
  14175. else {
  14176. content = content.slice(1, content.length - 1);
  14177. }
  14178. }
  14179. else if (isSlot) {
  14180. // #1241 special case for v-slot: vuetify relies extensively on slot
  14181. // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
  14182. // supports such usage so we are keeping it consistent with 2.x.
  14183. content += match[3] || '';
  14184. }
  14185. arg = {
  14186. type: 4 /* SIMPLE_EXPRESSION */,
  14187. content,
  14188. isStatic,
  14189. constType: isStatic
  14190. ? 3 /* CAN_STRINGIFY */
  14191. : 0 /* NOT_CONSTANT */,
  14192. loc
  14193. };
  14194. }
  14195. if (value && value.isQuoted) {
  14196. const valueLoc = value.loc;
  14197. valueLoc.start.offset++;
  14198. valueLoc.start.column++;
  14199. valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
  14200. valueLoc.source = valueLoc.source.slice(1, -1);
  14201. }
  14202. const modifiers = match[3] ? match[3].slice(1).split('.') : [];
  14203. if (isPropShorthand)
  14204. modifiers.push('prop');
  14205. return {
  14206. type: 7 /* DIRECTIVE */,
  14207. name: dirName,
  14208. exp: value && {
  14209. type: 4 /* SIMPLE_EXPRESSION */,
  14210. content: value.content,
  14211. isStatic: false,
  14212. // Treat as non-constant by default. This can be potentially set to
  14213. // other values by `transformExpression` to make it eligible for hoisting.
  14214. constType: 0 /* NOT_CONSTANT */,
  14215. loc: value.loc
  14216. },
  14217. arg,
  14218. modifiers,
  14219. loc
  14220. };
  14221. }
  14222. // missing directive name or illegal directive name
  14223. if (!context.inVPre && startsWith(name, 'v-')) {
  14224. emitError(context, 26 /* X_MISSING_DIRECTIVE_NAME */);
  14225. }
  14226. return {
  14227. type: 6 /* ATTRIBUTE */,
  14228. name,
  14229. value: value && {
  14230. type: 2 /* TEXT */,
  14231. content: value.content,
  14232. loc: value.loc
  14233. },
  14234. loc
  14235. };
  14236. }
  14237. function parseAttributeValue(context) {
  14238. const start = getCursor(context);
  14239. let content;
  14240. const quote = context.source[0];
  14241. const isQuoted = quote === `"` || quote === `'`;
  14242. if (isQuoted) {
  14243. // Quoted value.
  14244. advanceBy(context, 1);
  14245. const endIndex = context.source.indexOf(quote);
  14246. if (endIndex === -1) {
  14247. content = parseTextData(context, context.source.length, 4 /* ATTRIBUTE_VALUE */);
  14248. }
  14249. else {
  14250. content = parseTextData(context, endIndex, 4 /* ATTRIBUTE_VALUE */);
  14251. advanceBy(context, 1);
  14252. }
  14253. }
  14254. else {
  14255. // Unquoted
  14256. const match = /^[^\t\r\n\f >]+/.exec(context.source);
  14257. if (!match) {
  14258. return undefined;
  14259. }
  14260. const unexpectedChars = /["'<=`]/g;
  14261. let m;
  14262. while ((m = unexpectedChars.exec(match[0]))) {
  14263. emitError(context, 18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
  14264. }
  14265. content = parseTextData(context, match[0].length, 4 /* ATTRIBUTE_VALUE */);
  14266. }
  14267. return { content, isQuoted, loc: getSelection(context, start) };
  14268. }
  14269. function parseInterpolation(context, mode) {
  14270. const [open, close] = context.options.delimiters;
  14271. const closeIndex = context.source.indexOf(close, open.length);
  14272. if (closeIndex === -1) {
  14273. emitError(context, 25 /* X_MISSING_INTERPOLATION_END */);
  14274. return undefined;
  14275. }
  14276. const start = getCursor(context);
  14277. advanceBy(context, open.length);
  14278. const innerStart = getCursor(context);
  14279. const innerEnd = getCursor(context);
  14280. const rawContentLength = closeIndex - open.length;
  14281. const rawContent = context.source.slice(0, rawContentLength);
  14282. const preTrimContent = parseTextData(context, rawContentLength, mode);
  14283. const content = preTrimContent.trim();
  14284. const startOffset = preTrimContent.indexOf(content);
  14285. if (startOffset > 0) {
  14286. advancePositionWithMutation(innerStart, rawContent, startOffset);
  14287. }
  14288. const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
  14289. advancePositionWithMutation(innerEnd, rawContent, endOffset);
  14290. advanceBy(context, close.length);
  14291. return {
  14292. type: 5 /* INTERPOLATION */,
  14293. content: {
  14294. type: 4 /* SIMPLE_EXPRESSION */,
  14295. isStatic: false,
  14296. // Set `isConstant` to false by default and will decide in transformExpression
  14297. constType: 0 /* NOT_CONSTANT */,
  14298. content,
  14299. loc: getSelection(context, innerStart, innerEnd)
  14300. },
  14301. loc: getSelection(context, start)
  14302. };
  14303. }
  14304. function parseText(context, mode) {
  14305. const endTokens = mode === 3 /* CDATA */ ? [']]>'] : ['<', context.options.delimiters[0]];
  14306. let endIndex = context.source.length;
  14307. for (let i = 0; i < endTokens.length; i++) {
  14308. const index = context.source.indexOf(endTokens[i], 1);
  14309. if (index !== -1 && endIndex > index) {
  14310. endIndex = index;
  14311. }
  14312. }
  14313. const start = getCursor(context);
  14314. const content = parseTextData(context, endIndex, mode);
  14315. return {
  14316. type: 2 /* TEXT */,
  14317. content,
  14318. loc: getSelection(context, start)
  14319. };
  14320. }
  14321. /**
  14322. * Get text data with a given length from the current location.
  14323. * This translates HTML entities in the text data.
  14324. */
  14325. function parseTextData(context, length, mode) {
  14326. const rawText = context.source.slice(0, length);
  14327. advanceBy(context, length);
  14328. if (mode === 2 /* RAWTEXT */ ||
  14329. mode === 3 /* CDATA */ ||
  14330. rawText.indexOf('&') === -1) {
  14331. return rawText;
  14332. }
  14333. else {
  14334. // DATA or RCDATA containing "&"". Entity decoding required.
  14335. return context.options.decodeEntities(rawText, mode === 4 /* ATTRIBUTE_VALUE */);
  14336. }
  14337. }
  14338. function getCursor(context) {
  14339. const { column, line, offset } = context;
  14340. return { column, line, offset };
  14341. }
  14342. function getSelection(context, start, end) {
  14343. end = end || getCursor(context);
  14344. return {
  14345. start,
  14346. end,
  14347. source: context.originalSource.slice(start.offset, end.offset)
  14348. };
  14349. }
  14350. function last(xs) {
  14351. return xs[xs.length - 1];
  14352. }
  14353. function startsWith(source, searchString) {
  14354. return source.startsWith(searchString);
  14355. }
  14356. function advanceBy(context, numberOfCharacters) {
  14357. const { source } = context;
  14358. advancePositionWithMutation(context, source, numberOfCharacters);
  14359. context.source = source.slice(numberOfCharacters);
  14360. }
  14361. function advanceSpaces(context) {
  14362. const match = /^[\t\r\n\f ]+/.exec(context.source);
  14363. if (match) {
  14364. advanceBy(context, match[0].length);
  14365. }
  14366. }
  14367. function getNewPosition(context, start, numberOfCharacters) {
  14368. return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
  14369. }
  14370. function emitError(context, code, offset, loc = getCursor(context)) {
  14371. if (offset) {
  14372. loc.offset += offset;
  14373. loc.column += offset;
  14374. }
  14375. context.options.onError(createCompilerError(code, {
  14376. start: loc,
  14377. end: loc,
  14378. source: ''
  14379. }));
  14380. }
  14381. function isEnd(context, mode, ancestors) {
  14382. const s = context.source;
  14383. switch (mode) {
  14384. case 0 /* DATA */:
  14385. if (startsWith(s, '</')) {
  14386. // TODO: probably bad performance
  14387. for (let i = ancestors.length - 1; i >= 0; --i) {
  14388. if (startsWithEndTagOpen(s, ancestors[i].tag)) {
  14389. return true;
  14390. }
  14391. }
  14392. }
  14393. break;
  14394. case 1 /* RCDATA */:
  14395. case 2 /* RAWTEXT */: {
  14396. const parent = last(ancestors);
  14397. if (parent && startsWithEndTagOpen(s, parent.tag)) {
  14398. return true;
  14399. }
  14400. break;
  14401. }
  14402. case 3 /* CDATA */:
  14403. if (startsWith(s, ']]>')) {
  14404. return true;
  14405. }
  14406. break;
  14407. }
  14408. return !s;
  14409. }
  14410. function startsWithEndTagOpen(source, tag) {
  14411. return (startsWith(source, '</') &&
  14412. source.slice(2, 2 + tag.length).toLowerCase() === tag.toLowerCase() &&
  14413. /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
  14414. }
  14415. function hoistStatic(root, context) {
  14416. walk(root, context,
  14417. // Root node is unfortunately non-hoistable due to potential parent
  14418. // fallthrough attributes.
  14419. isSingleElementRoot(root, root.children[0]));
  14420. }
  14421. function isSingleElementRoot(root, child) {
  14422. const { children } = root;
  14423. return (children.length === 1 &&
  14424. child.type === 1 /* ELEMENT */ &&
  14425. !isSlotOutlet(child));
  14426. }
  14427. function walk(node, context, doNotHoistNode = false) {
  14428. const { children } = node;
  14429. const originalCount = children.length;
  14430. let hoistedCount = 0;
  14431. for (let i = 0; i < children.length; i++) {
  14432. const child = children[i];
  14433. // only plain elements & text calls are eligible for hoisting.
  14434. if (child.type === 1 /* ELEMENT */ &&
  14435. child.tagType === 0 /* ELEMENT */) {
  14436. const constantType = doNotHoistNode
  14437. ? 0 /* NOT_CONSTANT */
  14438. : getConstantType(child, context);
  14439. if (constantType > 0 /* NOT_CONSTANT */) {
  14440. if (constantType >= 2 /* CAN_HOIST */) {
  14441. child.codegenNode.patchFlag =
  14442. -1 /* HOISTED */ + (` /* HOISTED */` );
  14443. child.codegenNode = context.hoist(child.codegenNode);
  14444. hoistedCount++;
  14445. continue;
  14446. }
  14447. }
  14448. else {
  14449. // node may contain dynamic children, but its props may be eligible for
  14450. // hoisting.
  14451. const codegenNode = child.codegenNode;
  14452. if (codegenNode.type === 13 /* VNODE_CALL */) {
  14453. const flag = getPatchFlag(codegenNode);
  14454. if ((!flag ||
  14455. flag === 512 /* NEED_PATCH */ ||
  14456. flag === 1 /* TEXT */) &&
  14457. getGeneratedPropsConstantType(child, context) >=
  14458. 2 /* CAN_HOIST */) {
  14459. const props = getNodeProps(child);
  14460. if (props) {
  14461. codegenNode.props = context.hoist(props);
  14462. }
  14463. }
  14464. if (codegenNode.dynamicProps) {
  14465. codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps);
  14466. }
  14467. }
  14468. }
  14469. }
  14470. else if (child.type === 12 /* TEXT_CALL */ &&
  14471. getConstantType(child.content, context) >= 2 /* CAN_HOIST */) {
  14472. child.codegenNode = context.hoist(child.codegenNode);
  14473. hoistedCount++;
  14474. }
  14475. // walk further
  14476. if (child.type === 1 /* ELEMENT */) {
  14477. const isComponent = child.tagType === 1 /* COMPONENT */;
  14478. if (isComponent) {
  14479. context.scopes.vSlot++;
  14480. }
  14481. walk(child, context);
  14482. if (isComponent) {
  14483. context.scopes.vSlot--;
  14484. }
  14485. }
  14486. else if (child.type === 11 /* FOR */) {
  14487. // Do not hoist v-for single child because it has to be a block
  14488. walk(child, context, child.children.length === 1);
  14489. }
  14490. else if (child.type === 9 /* IF */) {
  14491. for (let i = 0; i < child.branches.length; i++) {
  14492. // Do not hoist v-if single child because it has to be a block
  14493. walk(child.branches[i], context, child.branches[i].children.length === 1);
  14494. }
  14495. }
  14496. }
  14497. if (hoistedCount && context.transformHoist) {
  14498. context.transformHoist(children, context, node);
  14499. }
  14500. // all children were hoisted - the entire children array is hoistable.
  14501. if (hoistedCount &&
  14502. hoistedCount === originalCount &&
  14503. node.type === 1 /* ELEMENT */ &&
  14504. node.tagType === 0 /* ELEMENT */ &&
  14505. node.codegenNode &&
  14506. node.codegenNode.type === 13 /* VNODE_CALL */ &&
  14507. isArray(node.codegenNode.children)) {
  14508. node.codegenNode.children = context.hoist(createArrayExpression(node.codegenNode.children));
  14509. }
  14510. }
  14511. function getConstantType(node, context) {
  14512. const { constantCache } = context;
  14513. switch (node.type) {
  14514. case 1 /* ELEMENT */:
  14515. if (node.tagType !== 0 /* ELEMENT */) {
  14516. return 0 /* NOT_CONSTANT */;
  14517. }
  14518. const cached = constantCache.get(node);
  14519. if (cached !== undefined) {
  14520. return cached;
  14521. }
  14522. const codegenNode = node.codegenNode;
  14523. if (codegenNode.type !== 13 /* VNODE_CALL */) {
  14524. return 0 /* NOT_CONSTANT */;
  14525. }
  14526. if (codegenNode.isBlock &&
  14527. node.tag !== 'svg' &&
  14528. node.tag !== 'foreignObject') {
  14529. return 0 /* NOT_CONSTANT */;
  14530. }
  14531. const flag = getPatchFlag(codegenNode);
  14532. if (!flag) {
  14533. let returnType = 3 /* CAN_STRINGIFY */;
  14534. // Element itself has no patch flag. However we still need to check:
  14535. // 1. Even for a node with no patch flag, it is possible for it to contain
  14536. // non-hoistable expressions that refers to scope variables, e.g. compiler
  14537. // injected keys or cached event handlers. Therefore we need to always
  14538. // check the codegenNode's props to be sure.
  14539. const generatedPropsType = getGeneratedPropsConstantType(node, context);
  14540. if (generatedPropsType === 0 /* NOT_CONSTANT */) {
  14541. constantCache.set(node, 0 /* NOT_CONSTANT */);
  14542. return 0 /* NOT_CONSTANT */;
  14543. }
  14544. if (generatedPropsType < returnType) {
  14545. returnType = generatedPropsType;
  14546. }
  14547. // 2. its children.
  14548. for (let i = 0; i < node.children.length; i++) {
  14549. const childType = getConstantType(node.children[i], context);
  14550. if (childType === 0 /* NOT_CONSTANT */) {
  14551. constantCache.set(node, 0 /* NOT_CONSTANT */);
  14552. return 0 /* NOT_CONSTANT */;
  14553. }
  14554. if (childType < returnType) {
  14555. returnType = childType;
  14556. }
  14557. }
  14558. // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
  14559. // type, check if any of the props can cause the type to be lowered
  14560. // we can skip can_patch because it's guaranteed by the absence of a
  14561. // patchFlag.
  14562. if (returnType > 1 /* CAN_SKIP_PATCH */) {
  14563. for (let i = 0; i < node.props.length; i++) {
  14564. const p = node.props[i];
  14565. if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind' && p.exp) {
  14566. const expType = getConstantType(p.exp, context);
  14567. if (expType === 0 /* NOT_CONSTANT */) {
  14568. constantCache.set(node, 0 /* NOT_CONSTANT */);
  14569. return 0 /* NOT_CONSTANT */;
  14570. }
  14571. if (expType < returnType) {
  14572. returnType = expType;
  14573. }
  14574. }
  14575. }
  14576. }
  14577. // only svg/foreignObject could be block here, however if they are
  14578. // static then they don't need to be blocks since there will be no
  14579. // nested updates.
  14580. if (codegenNode.isBlock) {
  14581. context.removeHelper(OPEN_BLOCK);
  14582. context.removeHelper(getVNodeBlockHelper(context.inSSR, codegenNode.isComponent));
  14583. codegenNode.isBlock = false;
  14584. context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent));
  14585. }
  14586. constantCache.set(node, returnType);
  14587. return returnType;
  14588. }
  14589. else {
  14590. constantCache.set(node, 0 /* NOT_CONSTANT */);
  14591. return 0 /* NOT_CONSTANT */;
  14592. }
  14593. case 2 /* TEXT */:
  14594. case 3 /* COMMENT */:
  14595. return 3 /* CAN_STRINGIFY */;
  14596. case 9 /* IF */:
  14597. case 11 /* FOR */:
  14598. case 10 /* IF_BRANCH */:
  14599. return 0 /* NOT_CONSTANT */;
  14600. case 5 /* INTERPOLATION */:
  14601. case 12 /* TEXT_CALL */:
  14602. return getConstantType(node.content, context);
  14603. case 4 /* SIMPLE_EXPRESSION */:
  14604. return node.constType;
  14605. case 8 /* COMPOUND_EXPRESSION */:
  14606. let returnType = 3 /* CAN_STRINGIFY */;
  14607. for (let i = 0; i < node.children.length; i++) {
  14608. const child = node.children[i];
  14609. if (isString(child) || isSymbol(child)) {
  14610. continue;
  14611. }
  14612. const childType = getConstantType(child, context);
  14613. if (childType === 0 /* NOT_CONSTANT */) {
  14614. return 0 /* NOT_CONSTANT */;
  14615. }
  14616. else if (childType < returnType) {
  14617. returnType = childType;
  14618. }
  14619. }
  14620. return returnType;
  14621. default:
  14622. return 0 /* NOT_CONSTANT */;
  14623. }
  14624. }
  14625. const allowHoistedHelperSet = new Set([
  14626. NORMALIZE_CLASS,
  14627. NORMALIZE_STYLE,
  14628. NORMALIZE_PROPS,
  14629. GUARD_REACTIVE_PROPS
  14630. ]);
  14631. function getConstantTypeOfHelperCall(value, context) {
  14632. if (value.type === 14 /* JS_CALL_EXPRESSION */ &&
  14633. !isString(value.callee) &&
  14634. allowHoistedHelperSet.has(value.callee)) {
  14635. const arg = value.arguments[0];
  14636. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  14637. return getConstantType(arg, context);
  14638. }
  14639. else if (arg.type === 14 /* JS_CALL_EXPRESSION */) {
  14640. // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(exp))`
  14641. return getConstantTypeOfHelperCall(arg, context);
  14642. }
  14643. }
  14644. return 0 /* NOT_CONSTANT */;
  14645. }
  14646. function getGeneratedPropsConstantType(node, context) {
  14647. let returnType = 3 /* CAN_STRINGIFY */;
  14648. const props = getNodeProps(node);
  14649. if (props && props.type === 15 /* JS_OBJECT_EXPRESSION */) {
  14650. const { properties } = props;
  14651. for (let i = 0; i < properties.length; i++) {
  14652. const { key, value } = properties[i];
  14653. const keyType = getConstantType(key, context);
  14654. if (keyType === 0 /* NOT_CONSTANT */) {
  14655. return keyType;
  14656. }
  14657. if (keyType < returnType) {
  14658. returnType = keyType;
  14659. }
  14660. let valueType;
  14661. if (value.type === 4 /* SIMPLE_EXPRESSION */) {
  14662. valueType = getConstantType(value, context);
  14663. }
  14664. else if (value.type === 14 /* JS_CALL_EXPRESSION */) {
  14665. // some helper calls can be hoisted,
  14666. // such as the `normalizeProps` generated by the compiler for pre-normalize class,
  14667. // in this case we need to respect the ConstantType of the helper's arguments
  14668. valueType = getConstantTypeOfHelperCall(value, context);
  14669. }
  14670. else {
  14671. valueType = 0 /* NOT_CONSTANT */;
  14672. }
  14673. if (valueType === 0 /* NOT_CONSTANT */) {
  14674. return valueType;
  14675. }
  14676. if (valueType < returnType) {
  14677. returnType = valueType;
  14678. }
  14679. }
  14680. }
  14681. return returnType;
  14682. }
  14683. function getNodeProps(node) {
  14684. const codegenNode = node.codegenNode;
  14685. if (codegenNode.type === 13 /* VNODE_CALL */) {
  14686. return codegenNode.props;
  14687. }
  14688. }
  14689. function getPatchFlag(node) {
  14690. const flag = node.patchFlag;
  14691. return flag ? parseInt(flag, 10) : undefined;
  14692. }
  14693. 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 }) {
  14694. const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
  14695. const context = {
  14696. // options
  14697. selfName: nameMatch && capitalize(camelize(nameMatch[1])),
  14698. prefixIdentifiers,
  14699. hoistStatic,
  14700. cacheHandlers,
  14701. nodeTransforms,
  14702. directiveTransforms,
  14703. transformHoist,
  14704. isBuiltInComponent,
  14705. isCustomElement,
  14706. expressionPlugins,
  14707. scopeId,
  14708. slotted,
  14709. ssr,
  14710. inSSR,
  14711. ssrCssVars,
  14712. bindingMetadata,
  14713. inline,
  14714. isTS,
  14715. onError,
  14716. onWarn,
  14717. compatConfig,
  14718. // state
  14719. root,
  14720. helpers: new Map(),
  14721. components: new Set(),
  14722. directives: new Set(),
  14723. hoists: [],
  14724. imports: [],
  14725. constantCache: new Map(),
  14726. temps: 0,
  14727. cached: 0,
  14728. identifiers: Object.create(null),
  14729. scopes: {
  14730. vFor: 0,
  14731. vSlot: 0,
  14732. vPre: 0,
  14733. vOnce: 0
  14734. },
  14735. parent: null,
  14736. currentNode: root,
  14737. childIndex: 0,
  14738. inVOnce: false,
  14739. // methods
  14740. helper(name) {
  14741. const count = context.helpers.get(name) || 0;
  14742. context.helpers.set(name, count + 1);
  14743. return name;
  14744. },
  14745. removeHelper(name) {
  14746. const count = context.helpers.get(name);
  14747. if (count) {
  14748. const currentCount = count - 1;
  14749. if (!currentCount) {
  14750. context.helpers.delete(name);
  14751. }
  14752. else {
  14753. context.helpers.set(name, currentCount);
  14754. }
  14755. }
  14756. },
  14757. helperString(name) {
  14758. return `_${helperNameMap[context.helper(name)]}`;
  14759. },
  14760. replaceNode(node) {
  14761. /* istanbul ignore if */
  14762. {
  14763. if (!context.currentNode) {
  14764. throw new Error(`Node being replaced is already removed.`);
  14765. }
  14766. if (!context.parent) {
  14767. throw new Error(`Cannot replace root node.`);
  14768. }
  14769. }
  14770. context.parent.children[context.childIndex] = context.currentNode = node;
  14771. },
  14772. removeNode(node) {
  14773. if (!context.parent) {
  14774. throw new Error(`Cannot remove root node.`);
  14775. }
  14776. const list = context.parent.children;
  14777. const removalIndex = node
  14778. ? list.indexOf(node)
  14779. : context.currentNode
  14780. ? context.childIndex
  14781. : -1;
  14782. /* istanbul ignore if */
  14783. if (removalIndex < 0) {
  14784. throw new Error(`node being removed is not a child of current parent`);
  14785. }
  14786. if (!node || node === context.currentNode) {
  14787. // current node removed
  14788. context.currentNode = null;
  14789. context.onNodeRemoved();
  14790. }
  14791. else {
  14792. // sibling node removed
  14793. if (context.childIndex > removalIndex) {
  14794. context.childIndex--;
  14795. context.onNodeRemoved();
  14796. }
  14797. }
  14798. context.parent.children.splice(removalIndex, 1);
  14799. },
  14800. onNodeRemoved: () => { },
  14801. addIdentifiers(exp) {
  14802. // identifier tracking only happens in non-browser builds.
  14803. {
  14804. if (isString(exp)) {
  14805. addId(exp);
  14806. }
  14807. else if (exp.identifiers) {
  14808. exp.identifiers.forEach(addId);
  14809. }
  14810. else if (exp.type === 4 /* SIMPLE_EXPRESSION */) {
  14811. addId(exp.content);
  14812. }
  14813. }
  14814. },
  14815. removeIdentifiers(exp) {
  14816. {
  14817. if (isString(exp)) {
  14818. removeId(exp);
  14819. }
  14820. else if (exp.identifiers) {
  14821. exp.identifiers.forEach(removeId);
  14822. }
  14823. else if (exp.type === 4 /* SIMPLE_EXPRESSION */) {
  14824. removeId(exp.content);
  14825. }
  14826. }
  14827. },
  14828. hoist(exp) {
  14829. if (isString(exp))
  14830. exp = createSimpleExpression(exp);
  14831. context.hoists.push(exp);
  14832. const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* CAN_HOIST */);
  14833. identifier.hoisted = exp;
  14834. return identifier;
  14835. },
  14836. cache(exp, isVNode = false) {
  14837. return createCacheExpression(context.cached++, exp, isVNode);
  14838. }
  14839. };
  14840. function addId(id) {
  14841. const { identifiers } = context;
  14842. if (identifiers[id] === undefined) {
  14843. identifiers[id] = 0;
  14844. }
  14845. identifiers[id]++;
  14846. }
  14847. function removeId(id) {
  14848. context.identifiers[id]--;
  14849. }
  14850. return context;
  14851. }
  14852. function transform(root, options) {
  14853. const context = createTransformContext(root, options);
  14854. traverseNode(root, context);
  14855. if (options.hoistStatic) {
  14856. hoistStatic(root, context);
  14857. }
  14858. if (!options.ssr) {
  14859. createRootCodegen(root, context);
  14860. }
  14861. // finalize meta information
  14862. root.helpers = [...context.helpers.keys()];
  14863. root.components = [...context.components];
  14864. root.directives = [...context.directives];
  14865. root.imports = context.imports;
  14866. root.hoists = context.hoists;
  14867. root.temps = context.temps;
  14868. root.cached = context.cached;
  14869. }
  14870. function createRootCodegen(root, context) {
  14871. const { helper } = context;
  14872. const { children } = root;
  14873. if (children.length === 1) {
  14874. const child = children[0];
  14875. // if the single child is an element, turn it into a block.
  14876. if (isSingleElementRoot(root, child) && child.codegenNode) {
  14877. // single element root is never hoisted so codegenNode will never be
  14878. // SimpleExpressionNode
  14879. const codegenNode = child.codegenNode;
  14880. if (codegenNode.type === 13 /* VNODE_CALL */) {
  14881. makeBlock(codegenNode, context);
  14882. }
  14883. root.codegenNode = codegenNode;
  14884. }
  14885. else {
  14886. // - single <slot/>, IfNode, ForNode: already blocks.
  14887. // - single text node: always patched.
  14888. // root codegen falls through via genNode()
  14889. root.codegenNode = child;
  14890. }
  14891. }
  14892. else if (children.length > 1) {
  14893. // root has multiple nodes - return a fragment block.
  14894. let patchFlag = 64 /* STABLE_FRAGMENT */;
  14895. let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
  14896. // check if the fragment actually contains a single valid child with
  14897. // the rest being comments
  14898. if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
  14899. patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
  14900. patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
  14901. }
  14902. root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, undefined, false /* isComponent */);
  14903. }
  14904. else ;
  14905. }
  14906. function traverseChildren(parent, context) {
  14907. let i = 0;
  14908. const nodeRemoved = () => {
  14909. i--;
  14910. };
  14911. for (; i < parent.children.length; i++) {
  14912. const child = parent.children[i];
  14913. if (isString(child))
  14914. continue;
  14915. context.parent = parent;
  14916. context.childIndex = i;
  14917. context.onNodeRemoved = nodeRemoved;
  14918. traverseNode(child, context);
  14919. }
  14920. }
  14921. function traverseNode(node, context) {
  14922. context.currentNode = node;
  14923. // apply transform plugins
  14924. const { nodeTransforms } = context;
  14925. const exitFns = [];
  14926. for (let i = 0; i < nodeTransforms.length; i++) {
  14927. const onExit = nodeTransforms[i](node, context);
  14928. if (onExit) {
  14929. if (isArray(onExit)) {
  14930. exitFns.push(...onExit);
  14931. }
  14932. else {
  14933. exitFns.push(onExit);
  14934. }
  14935. }
  14936. if (!context.currentNode) {
  14937. // node was removed
  14938. return;
  14939. }
  14940. else {
  14941. // node may have been replaced
  14942. node = context.currentNode;
  14943. }
  14944. }
  14945. switch (node.type) {
  14946. case 3 /* COMMENT */:
  14947. if (!context.ssr) {
  14948. // inject import for the Comment symbol, which is needed for creating
  14949. // comment nodes with `createVNode`
  14950. context.helper(CREATE_COMMENT);
  14951. }
  14952. break;
  14953. case 5 /* INTERPOLATION */:
  14954. // no need to traverse, but we need to inject toString helper
  14955. if (!context.ssr) {
  14956. context.helper(TO_DISPLAY_STRING);
  14957. }
  14958. break;
  14959. // for container types, further traverse downwards
  14960. case 9 /* IF */:
  14961. for (let i = 0; i < node.branches.length; i++) {
  14962. traverseNode(node.branches[i], context);
  14963. }
  14964. break;
  14965. case 10 /* IF_BRANCH */:
  14966. case 11 /* FOR */:
  14967. case 1 /* ELEMENT */:
  14968. case 0 /* ROOT */:
  14969. traverseChildren(node, context);
  14970. break;
  14971. }
  14972. // exit transforms
  14973. context.currentNode = node;
  14974. let i = exitFns.length;
  14975. while (i--) {
  14976. exitFns[i]();
  14977. }
  14978. }
  14979. function createStructuralDirectiveTransform(name, fn) {
  14980. const matches = isString(name)
  14981. ? (n) => n === name
  14982. : (n) => name.test(n);
  14983. return (node, context) => {
  14984. if (node.type === 1 /* ELEMENT */) {
  14985. const { props } = node;
  14986. // structural directive transforms are not concerned with slots
  14987. // as they are handled separately in vSlot.ts
  14988. if (node.tagType === 3 /* TEMPLATE */ && props.some(isVSlot)) {
  14989. return;
  14990. }
  14991. const exitFns = [];
  14992. for (let i = 0; i < props.length; i++) {
  14993. const prop = props[i];
  14994. if (prop.type === 7 /* DIRECTIVE */ && matches(prop.name)) {
  14995. // structural directives are removed to avoid infinite recursion
  14996. // also we remove them *before* applying so that it can further
  14997. // traverse itself in case it moves the node around
  14998. props.splice(i, 1);
  14999. i--;
  15000. const onExit = fn(node, prop, context);
  15001. if (onExit)
  15002. exitFns.push(onExit);
  15003. }
  15004. }
  15005. return exitFns;
  15006. }
  15007. };
  15008. }
  15009. /* -*- Mode: js; js-indent-level: 2; -*- */
  15010. /*
  15011. * Copyright 2011 Mozilla Foundation and contributors
  15012. * Licensed under the New BSD license. See LICENSE or:
  15013. * http://opensource.org/licenses/BSD-3-Clause
  15014. */
  15015. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  15016. /**
  15017. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  15018. */
  15019. var encode = function (number) {
  15020. if (0 <= number && number < intToCharMap.length) {
  15021. return intToCharMap[number];
  15022. }
  15023. throw new TypeError("Must be between 0 and 63: " + number);
  15024. };
  15025. /**
  15026. * Decode a single base 64 character code digit to an integer. Returns -1 on
  15027. * failure.
  15028. */
  15029. var decode = function (charCode) {
  15030. var bigA = 65; // 'A'
  15031. var bigZ = 90; // 'Z'
  15032. var littleA = 97; // 'a'
  15033. var littleZ = 122; // 'z'
  15034. var zero = 48; // '0'
  15035. var nine = 57; // '9'
  15036. var plus = 43; // '+'
  15037. var slash = 47; // '/'
  15038. var littleOffset = 26;
  15039. var numberOffset = 52;
  15040. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  15041. if (bigA <= charCode && charCode <= bigZ) {
  15042. return (charCode - bigA);
  15043. }
  15044. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  15045. if (littleA <= charCode && charCode <= littleZ) {
  15046. return (charCode - littleA + littleOffset);
  15047. }
  15048. // 52 - 61: 0123456789
  15049. if (zero <= charCode && charCode <= nine) {
  15050. return (charCode - zero + numberOffset);
  15051. }
  15052. // 62: +
  15053. if (charCode == plus) {
  15054. return 62;
  15055. }
  15056. // 63: /
  15057. if (charCode == slash) {
  15058. return 63;
  15059. }
  15060. // Invalid base64 digit.
  15061. return -1;
  15062. };
  15063. var base64 = {
  15064. encode: encode,
  15065. decode: decode
  15066. };
  15067. /* -*- Mode: js; js-indent-level: 2; -*- */
  15068. /*
  15069. * Copyright 2011 Mozilla Foundation and contributors
  15070. * Licensed under the New BSD license. See LICENSE or:
  15071. * http://opensource.org/licenses/BSD-3-Clause
  15072. *
  15073. * Based on the Base 64 VLQ implementation in Closure Compiler:
  15074. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  15075. *
  15076. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  15077. * Redistribution and use in source and binary forms, with or without
  15078. * modification, are permitted provided that the following conditions are
  15079. * met:
  15080. *
  15081. * * Redistributions of source code must retain the above copyright
  15082. * notice, this list of conditions and the following disclaimer.
  15083. * * Redistributions in binary form must reproduce the above
  15084. * copyright notice, this list of conditions and the following
  15085. * disclaimer in the documentation and/or other materials provided
  15086. * with the distribution.
  15087. * * Neither the name of Google Inc. nor the names of its
  15088. * contributors may be used to endorse or promote products derived
  15089. * from this software without specific prior written permission.
  15090. *
  15091. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  15092. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  15093. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  15094. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  15095. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  15096. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  15097. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  15098. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  15099. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  15100. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  15101. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  15102. */
  15103. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  15104. // length quantities we use in the source map spec, the first bit is the sign,
  15105. // the next four bits are the actual value, and the 6th bit is the
  15106. // continuation bit. The continuation bit tells us whether there are more
  15107. // digits in this value following this digit.
  15108. //
  15109. // Continuation
  15110. // | Sign
  15111. // | |
  15112. // V V
  15113. // 101011
  15114. var VLQ_BASE_SHIFT = 5;
  15115. // binary: 100000
  15116. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  15117. // binary: 011111
  15118. var VLQ_BASE_MASK = VLQ_BASE - 1;
  15119. // binary: 100000
  15120. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  15121. /**
  15122. * Converts from a two-complement value to a value where the sign bit is
  15123. * placed in the least significant bit. For example, as decimals:
  15124. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  15125. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  15126. */
  15127. function toVLQSigned(aValue) {
  15128. return aValue < 0
  15129. ? ((-aValue) << 1) + 1
  15130. : (aValue << 1) + 0;
  15131. }
  15132. /**
  15133. * Converts to a two-complement value from a value where the sign bit is
  15134. * placed in the least significant bit. For example, as decimals:
  15135. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  15136. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  15137. */
  15138. function fromVLQSigned(aValue) {
  15139. var isNegative = (aValue & 1) === 1;
  15140. var shifted = aValue >> 1;
  15141. return isNegative
  15142. ? -shifted
  15143. : shifted;
  15144. }
  15145. /**
  15146. * Returns the base 64 VLQ encoded value.
  15147. */
  15148. var encode$1 = function base64VLQ_encode(aValue) {
  15149. var encoded = "";
  15150. var digit;
  15151. var vlq = toVLQSigned(aValue);
  15152. do {
  15153. digit = vlq & VLQ_BASE_MASK;
  15154. vlq >>>= VLQ_BASE_SHIFT;
  15155. if (vlq > 0) {
  15156. // There are still more digits in this value, so we must make sure the
  15157. // continuation bit is marked.
  15158. digit |= VLQ_CONTINUATION_BIT;
  15159. }
  15160. encoded += base64.encode(digit);
  15161. } while (vlq > 0);
  15162. return encoded;
  15163. };
  15164. /**
  15165. * Decodes the next base 64 VLQ value from the given string and returns the
  15166. * value and the rest of the string via the out parameter.
  15167. */
  15168. var decode$1 = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  15169. var strLen = aStr.length;
  15170. var result = 0;
  15171. var shift = 0;
  15172. var continuation, digit;
  15173. do {
  15174. if (aIndex >= strLen) {
  15175. throw new Error("Expected more digits in base 64 VLQ value.");
  15176. }
  15177. digit = base64.decode(aStr.charCodeAt(aIndex++));
  15178. if (digit === -1) {
  15179. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  15180. }
  15181. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  15182. digit &= VLQ_BASE_MASK;
  15183. result = result + (digit << shift);
  15184. shift += VLQ_BASE_SHIFT;
  15185. } while (continuation);
  15186. aOutParam.value = fromVLQSigned(result);
  15187. aOutParam.rest = aIndex;
  15188. };
  15189. var base64Vlq = {
  15190. encode: encode$1,
  15191. decode: decode$1
  15192. };
  15193. function getDefaultExportFromCjs (x) {
  15194. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  15195. }
  15196. function getAugmentedNamespace(n) {
  15197. if (n.__esModule) return n;
  15198. var a = Object.defineProperty({}, '__esModule', {value: true});
  15199. Object.keys(n).forEach(function (k) {
  15200. var d = Object.getOwnPropertyDescriptor(n, k);
  15201. Object.defineProperty(a, k, d.get ? d : {
  15202. enumerable: true,
  15203. get: function () {
  15204. return n[k];
  15205. }
  15206. });
  15207. });
  15208. return a;
  15209. }
  15210. function createCommonjsModule(fn) {
  15211. var module = { exports: {} };
  15212. return fn(module, module.exports), module.exports;
  15213. }
  15214. /* -*- Mode: js; js-indent-level: 2; -*- */
  15215. var util = createCommonjsModule(function (module, exports) {
  15216. /*
  15217. * Copyright 2011 Mozilla Foundation and contributors
  15218. * Licensed under the New BSD license. See LICENSE or:
  15219. * http://opensource.org/licenses/BSD-3-Clause
  15220. */
  15221. /**
  15222. * This is a helper function for getting values from parameter/options
  15223. * objects.
  15224. *
  15225. * @param args The object we are extracting values from
  15226. * @param name The name of the property we are getting.
  15227. * @param defaultValue An optional value to return if the property is missing
  15228. * from the object. If this is not specified and the property is missing, an
  15229. * error will be thrown.
  15230. */
  15231. function getArg(aArgs, aName, aDefaultValue) {
  15232. if (aName in aArgs) {
  15233. return aArgs[aName];
  15234. } else if (arguments.length === 3) {
  15235. return aDefaultValue;
  15236. } else {
  15237. throw new Error('"' + aName + '" is a required argument.');
  15238. }
  15239. }
  15240. exports.getArg = getArg;
  15241. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  15242. var dataUrlRegexp = /^data:.+\,.+$/;
  15243. function urlParse(aUrl) {
  15244. var match = aUrl.match(urlRegexp);
  15245. if (!match) {
  15246. return null;
  15247. }
  15248. return {
  15249. scheme: match[1],
  15250. auth: match[2],
  15251. host: match[3],
  15252. port: match[4],
  15253. path: match[5]
  15254. };
  15255. }
  15256. exports.urlParse = urlParse;
  15257. function urlGenerate(aParsedUrl) {
  15258. var url = '';
  15259. if (aParsedUrl.scheme) {
  15260. url += aParsedUrl.scheme + ':';
  15261. }
  15262. url += '//';
  15263. if (aParsedUrl.auth) {
  15264. url += aParsedUrl.auth + '@';
  15265. }
  15266. if (aParsedUrl.host) {
  15267. url += aParsedUrl.host;
  15268. }
  15269. if (aParsedUrl.port) {
  15270. url += ":" + aParsedUrl.port;
  15271. }
  15272. if (aParsedUrl.path) {
  15273. url += aParsedUrl.path;
  15274. }
  15275. return url;
  15276. }
  15277. exports.urlGenerate = urlGenerate;
  15278. /**
  15279. * Normalizes a path, or the path portion of a URL:
  15280. *
  15281. * - Replaces consecutive slashes with one slash.
  15282. * - Removes unnecessary '.' parts.
  15283. * - Removes unnecessary '<dir>/..' parts.
  15284. *
  15285. * Based on code in the Node.js 'path' core module.
  15286. *
  15287. * @param aPath The path or url to normalize.
  15288. */
  15289. function normalize(aPath) {
  15290. var path = aPath;
  15291. var url = urlParse(aPath);
  15292. if (url) {
  15293. if (!url.path) {
  15294. return aPath;
  15295. }
  15296. path = url.path;
  15297. }
  15298. var isAbsolute = exports.isAbsolute(path);
  15299. var parts = path.split(/\/+/);
  15300. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  15301. part = parts[i];
  15302. if (part === '.') {
  15303. parts.splice(i, 1);
  15304. } else if (part === '..') {
  15305. up++;
  15306. } else if (up > 0) {
  15307. if (part === '') {
  15308. // The first part is blank if the path is absolute. Trying to go
  15309. // above the root is a no-op. Therefore we can remove all '..' parts
  15310. // directly after the root.
  15311. parts.splice(i + 1, up);
  15312. up = 0;
  15313. } else {
  15314. parts.splice(i, 2);
  15315. up--;
  15316. }
  15317. }
  15318. }
  15319. path = parts.join('/');
  15320. if (path === '') {
  15321. path = isAbsolute ? '/' : '.';
  15322. }
  15323. if (url) {
  15324. url.path = path;
  15325. return urlGenerate(url);
  15326. }
  15327. return path;
  15328. }
  15329. exports.normalize = normalize;
  15330. /**
  15331. * Joins two paths/URLs.
  15332. *
  15333. * @param aRoot The root path or URL.
  15334. * @param aPath The path or URL to be joined with the root.
  15335. *
  15336. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  15337. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  15338. * first.
  15339. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  15340. * is updated with the result and aRoot is returned. Otherwise the result
  15341. * is returned.
  15342. * - If aPath is absolute, the result is aPath.
  15343. * - Otherwise the two paths are joined with a slash.
  15344. * - Joining for example 'http://' and 'www.example.com' is also supported.
  15345. */
  15346. function join(aRoot, aPath) {
  15347. if (aRoot === "") {
  15348. aRoot = ".";
  15349. }
  15350. if (aPath === "") {
  15351. aPath = ".";
  15352. }
  15353. var aPathUrl = urlParse(aPath);
  15354. var aRootUrl = urlParse(aRoot);
  15355. if (aRootUrl) {
  15356. aRoot = aRootUrl.path || '/';
  15357. }
  15358. // `join(foo, '//www.example.org')`
  15359. if (aPathUrl && !aPathUrl.scheme) {
  15360. if (aRootUrl) {
  15361. aPathUrl.scheme = aRootUrl.scheme;
  15362. }
  15363. return urlGenerate(aPathUrl);
  15364. }
  15365. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  15366. return aPath;
  15367. }
  15368. // `join('http://', 'www.example.com')`
  15369. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  15370. aRootUrl.host = aPath;
  15371. return urlGenerate(aRootUrl);
  15372. }
  15373. var joined = aPath.charAt(0) === '/'
  15374. ? aPath
  15375. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  15376. if (aRootUrl) {
  15377. aRootUrl.path = joined;
  15378. return urlGenerate(aRootUrl);
  15379. }
  15380. return joined;
  15381. }
  15382. exports.join = join;
  15383. exports.isAbsolute = function (aPath) {
  15384. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  15385. };
  15386. /**
  15387. * Make a path relative to a URL or another path.
  15388. *
  15389. * @param aRoot The root path or URL.
  15390. * @param aPath The path or URL to be made relative to aRoot.
  15391. */
  15392. function relative(aRoot, aPath) {
  15393. if (aRoot === "") {
  15394. aRoot = ".";
  15395. }
  15396. aRoot = aRoot.replace(/\/$/, '');
  15397. // It is possible for the path to be above the root. In this case, simply
  15398. // checking whether the root is a prefix of the path won't work. Instead, we
  15399. // need to remove components from the root one by one, until either we find
  15400. // a prefix that fits, or we run out of components to remove.
  15401. var level = 0;
  15402. while (aPath.indexOf(aRoot + '/') !== 0) {
  15403. var index = aRoot.lastIndexOf("/");
  15404. if (index < 0) {
  15405. return aPath;
  15406. }
  15407. // If the only part of the root that is left is the scheme (i.e. http://,
  15408. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  15409. // have exhausted all components, so the path is not relative to the root.
  15410. aRoot = aRoot.slice(0, index);
  15411. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  15412. return aPath;
  15413. }
  15414. ++level;
  15415. }
  15416. // Make sure we add a "../" for each component we removed from the root.
  15417. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  15418. }
  15419. exports.relative = relative;
  15420. var supportsNullProto = (function () {
  15421. var obj = Object.create(null);
  15422. return !('__proto__' in obj);
  15423. }());
  15424. function identity (s) {
  15425. return s;
  15426. }
  15427. /**
  15428. * Because behavior goes wacky when you set `__proto__` on objects, we
  15429. * have to prefix all the strings in our set with an arbitrary character.
  15430. *
  15431. * See https://github.com/mozilla/source-map/pull/31 and
  15432. * https://github.com/mozilla/source-map/issues/30
  15433. *
  15434. * @param String aStr
  15435. */
  15436. function toSetString(aStr) {
  15437. if (isProtoString(aStr)) {
  15438. return '$' + aStr;
  15439. }
  15440. return aStr;
  15441. }
  15442. exports.toSetString = supportsNullProto ? identity : toSetString;
  15443. function fromSetString(aStr) {
  15444. if (isProtoString(aStr)) {
  15445. return aStr.slice(1);
  15446. }
  15447. return aStr;
  15448. }
  15449. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  15450. function isProtoString(s) {
  15451. if (!s) {
  15452. return false;
  15453. }
  15454. var length = s.length;
  15455. if (length < 9 /* "__proto__".length */) {
  15456. return false;
  15457. }
  15458. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  15459. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  15460. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  15461. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  15462. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  15463. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  15464. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  15465. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  15466. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  15467. return false;
  15468. }
  15469. for (var i = length - 10; i >= 0; i--) {
  15470. if (s.charCodeAt(i) !== 36 /* '$' */) {
  15471. return false;
  15472. }
  15473. }
  15474. return true;
  15475. }
  15476. /**
  15477. * Comparator between two mappings where the original positions are compared.
  15478. *
  15479. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  15480. * mappings with the same original source/line/column, but different generated
  15481. * line and column the same. Useful when searching for a mapping with a
  15482. * stubbed out mapping.
  15483. */
  15484. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  15485. var cmp = strcmp(mappingA.source, mappingB.source);
  15486. if (cmp !== 0) {
  15487. return cmp;
  15488. }
  15489. cmp = mappingA.originalLine - mappingB.originalLine;
  15490. if (cmp !== 0) {
  15491. return cmp;
  15492. }
  15493. cmp = mappingA.originalColumn - mappingB.originalColumn;
  15494. if (cmp !== 0 || onlyCompareOriginal) {
  15495. return cmp;
  15496. }
  15497. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  15498. if (cmp !== 0) {
  15499. return cmp;
  15500. }
  15501. cmp = mappingA.generatedLine - mappingB.generatedLine;
  15502. if (cmp !== 0) {
  15503. return cmp;
  15504. }
  15505. return strcmp(mappingA.name, mappingB.name);
  15506. }
  15507. exports.compareByOriginalPositions = compareByOriginalPositions;
  15508. /**
  15509. * Comparator between two mappings with deflated source and name indices where
  15510. * the generated positions are compared.
  15511. *
  15512. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  15513. * mappings with the same generated line and column, but different
  15514. * source/name/original line and column the same. Useful when searching for a
  15515. * mapping with a stubbed out mapping.
  15516. */
  15517. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  15518. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  15519. if (cmp !== 0) {
  15520. return cmp;
  15521. }
  15522. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  15523. if (cmp !== 0 || onlyCompareGenerated) {
  15524. return cmp;
  15525. }
  15526. cmp = strcmp(mappingA.source, mappingB.source);
  15527. if (cmp !== 0) {
  15528. return cmp;
  15529. }
  15530. cmp = mappingA.originalLine - mappingB.originalLine;
  15531. if (cmp !== 0) {
  15532. return cmp;
  15533. }
  15534. cmp = mappingA.originalColumn - mappingB.originalColumn;
  15535. if (cmp !== 0) {
  15536. return cmp;
  15537. }
  15538. return strcmp(mappingA.name, mappingB.name);
  15539. }
  15540. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  15541. function strcmp(aStr1, aStr2) {
  15542. if (aStr1 === aStr2) {
  15543. return 0;
  15544. }
  15545. if (aStr1 === null) {
  15546. return 1; // aStr2 !== null
  15547. }
  15548. if (aStr2 === null) {
  15549. return -1; // aStr1 !== null
  15550. }
  15551. if (aStr1 > aStr2) {
  15552. return 1;
  15553. }
  15554. return -1;
  15555. }
  15556. /**
  15557. * Comparator between two mappings with inflated source and name strings where
  15558. * the generated positions are compared.
  15559. */
  15560. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  15561. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  15562. if (cmp !== 0) {
  15563. return cmp;
  15564. }
  15565. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  15566. if (cmp !== 0) {
  15567. return cmp;
  15568. }
  15569. cmp = strcmp(mappingA.source, mappingB.source);
  15570. if (cmp !== 0) {
  15571. return cmp;
  15572. }
  15573. cmp = mappingA.originalLine - mappingB.originalLine;
  15574. if (cmp !== 0) {
  15575. return cmp;
  15576. }
  15577. cmp = mappingA.originalColumn - mappingB.originalColumn;
  15578. if (cmp !== 0) {
  15579. return cmp;
  15580. }
  15581. return strcmp(mappingA.name, mappingB.name);
  15582. }
  15583. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  15584. /**
  15585. * Strip any JSON XSSI avoidance prefix from the string (as documented
  15586. * in the source maps specification), and then parse the string as
  15587. * JSON.
  15588. */
  15589. function parseSourceMapInput(str) {
  15590. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  15591. }
  15592. exports.parseSourceMapInput = parseSourceMapInput;
  15593. /**
  15594. * Compute the URL of a source given the the source root, the source's
  15595. * URL, and the source map's URL.
  15596. */
  15597. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  15598. sourceURL = sourceURL || '';
  15599. if (sourceRoot) {
  15600. // This follows what Chrome does.
  15601. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  15602. sourceRoot += '/';
  15603. }
  15604. // The spec says:
  15605. // Line 4: An optional source root, useful for relocating source
  15606. // files on a server or removing repeated values in the
  15607. // “sources” entry. This value is prepended to the individual
  15608. // entries in the “source” field.
  15609. sourceURL = sourceRoot + sourceURL;
  15610. }
  15611. // Historically, SourceMapConsumer did not take the sourceMapURL as
  15612. // a parameter. This mode is still somewhat supported, which is why
  15613. // this code block is conditional. However, it's preferable to pass
  15614. // the source map URL to SourceMapConsumer, so that this function
  15615. // can implement the source URL resolution algorithm as outlined in
  15616. // the spec. This block is basically the equivalent of:
  15617. // new URL(sourceURL, sourceMapURL).toString()
  15618. // ... except it avoids using URL, which wasn't available in the
  15619. // older releases of node still supported by this library.
  15620. //
  15621. // The spec says:
  15622. // If the sources are not absolute URLs after prepending of the
  15623. // “sourceRoot”, the sources are resolved relative to the
  15624. // SourceMap (like resolving script src in a html document).
  15625. if (sourceMapURL) {
  15626. var parsed = urlParse(sourceMapURL);
  15627. if (!parsed) {
  15628. throw new Error("sourceMapURL could not be parsed");
  15629. }
  15630. if (parsed.path) {
  15631. // Strip the last path component, but keep the "/".
  15632. var index = parsed.path.lastIndexOf('/');
  15633. if (index >= 0) {
  15634. parsed.path = parsed.path.substring(0, index + 1);
  15635. }
  15636. }
  15637. sourceURL = join(urlGenerate(parsed), sourceURL);
  15638. }
  15639. return normalize(sourceURL);
  15640. }
  15641. exports.computeSourceURL = computeSourceURL;
  15642. });
  15643. /* -*- Mode: js; js-indent-level: 2; -*- */
  15644. /*
  15645. * Copyright 2011 Mozilla Foundation and contributors
  15646. * Licensed under the New BSD license. See LICENSE or:
  15647. * http://opensource.org/licenses/BSD-3-Clause
  15648. */
  15649. var has = Object.prototype.hasOwnProperty;
  15650. var hasNativeMap = typeof Map !== "undefined";
  15651. /**
  15652. * A data structure which is a combination of an array and a set. Adding a new
  15653. * member is O(1), testing for membership is O(1), and finding the index of an
  15654. * element is O(1). Removing elements from the set is not supported. Only
  15655. * strings are supported for membership.
  15656. */
  15657. function ArraySet() {
  15658. this._array = [];
  15659. this._set = hasNativeMap ? new Map() : Object.create(null);
  15660. }
  15661. /**
  15662. * Static method for creating ArraySet instances from an existing array.
  15663. */
  15664. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  15665. var set = new ArraySet();
  15666. for (var i = 0, len = aArray.length; i < len; i++) {
  15667. set.add(aArray[i], aAllowDuplicates);
  15668. }
  15669. return set;
  15670. };
  15671. /**
  15672. * Return how many unique items are in this ArraySet. If duplicates have been
  15673. * added, than those do not count towards the size.
  15674. *
  15675. * @returns Number
  15676. */
  15677. ArraySet.prototype.size = function ArraySet_size() {
  15678. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  15679. };
  15680. /**
  15681. * Add the given string to this set.
  15682. *
  15683. * @param String aStr
  15684. */
  15685. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  15686. var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
  15687. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  15688. var idx = this._array.length;
  15689. if (!isDuplicate || aAllowDuplicates) {
  15690. this._array.push(aStr);
  15691. }
  15692. if (!isDuplicate) {
  15693. if (hasNativeMap) {
  15694. this._set.set(aStr, idx);
  15695. } else {
  15696. this._set[sStr] = idx;
  15697. }
  15698. }
  15699. };
  15700. /**
  15701. * Is the given string a member of this set?
  15702. *
  15703. * @param String aStr
  15704. */
  15705. ArraySet.prototype.has = function ArraySet_has(aStr) {
  15706. if (hasNativeMap) {
  15707. return this._set.has(aStr);
  15708. } else {
  15709. var sStr = util.toSetString(aStr);
  15710. return has.call(this._set, sStr);
  15711. }
  15712. };
  15713. /**
  15714. * What is the index of the given string in the array?
  15715. *
  15716. * @param String aStr
  15717. */
  15718. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  15719. if (hasNativeMap) {
  15720. var idx = this._set.get(aStr);
  15721. if (idx >= 0) {
  15722. return idx;
  15723. }
  15724. } else {
  15725. var sStr = util.toSetString(aStr);
  15726. if (has.call(this._set, sStr)) {
  15727. return this._set[sStr];
  15728. }
  15729. }
  15730. throw new Error('"' + aStr + '" is not in the set.');
  15731. };
  15732. /**
  15733. * What is the element at the given index?
  15734. *
  15735. * @param Number aIdx
  15736. */
  15737. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  15738. if (aIdx >= 0 && aIdx < this._array.length) {
  15739. return this._array[aIdx];
  15740. }
  15741. throw new Error('No element indexed by ' + aIdx);
  15742. };
  15743. /**
  15744. * Returns the array representation of this set (which has the proper indices
  15745. * indicated by indexOf). Note that this is a copy of the internal array used
  15746. * for storing the members so that no one can mess with internal state.
  15747. */
  15748. ArraySet.prototype.toArray = function ArraySet_toArray() {
  15749. return this._array.slice();
  15750. };
  15751. var ArraySet_1 = ArraySet;
  15752. var arraySet = {
  15753. ArraySet: ArraySet_1
  15754. };
  15755. /* -*- Mode: js; js-indent-level: 2; -*- */
  15756. /*
  15757. * Copyright 2014 Mozilla Foundation and contributors
  15758. * Licensed under the New BSD license. See LICENSE or:
  15759. * http://opensource.org/licenses/BSD-3-Clause
  15760. */
  15761. /**
  15762. * Determine whether mappingB is after mappingA with respect to generated
  15763. * position.
  15764. */
  15765. function generatedPositionAfter(mappingA, mappingB) {
  15766. // Optimized for most common case
  15767. var lineA = mappingA.generatedLine;
  15768. var lineB = mappingB.generatedLine;
  15769. var columnA = mappingA.generatedColumn;
  15770. var columnB = mappingB.generatedColumn;
  15771. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  15772. util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  15773. }
  15774. /**
  15775. * A data structure to provide a sorted view of accumulated mappings in a
  15776. * performance conscious manner. It trades a neglibable overhead in general
  15777. * case for a large speedup in case of mappings being added in order.
  15778. */
  15779. function MappingList() {
  15780. this._array = [];
  15781. this._sorted = true;
  15782. // Serves as infimum
  15783. this._last = {generatedLine: -1, generatedColumn: 0};
  15784. }
  15785. /**
  15786. * Iterate through internal items. This method takes the same arguments that
  15787. * `Array.prototype.forEach` takes.
  15788. *
  15789. * NOTE: The order of the mappings is NOT guaranteed.
  15790. */
  15791. MappingList.prototype.unsortedForEach =
  15792. function MappingList_forEach(aCallback, aThisArg) {
  15793. this._array.forEach(aCallback, aThisArg);
  15794. };
  15795. /**
  15796. * Add the given source mapping.
  15797. *
  15798. * @param Object aMapping
  15799. */
  15800. MappingList.prototype.add = function MappingList_add(aMapping) {
  15801. if (generatedPositionAfter(this._last, aMapping)) {
  15802. this._last = aMapping;
  15803. this._array.push(aMapping);
  15804. } else {
  15805. this._sorted = false;
  15806. this._array.push(aMapping);
  15807. }
  15808. };
  15809. /**
  15810. * Returns the flat, sorted array of mappings. The mappings are sorted by
  15811. * generated position.
  15812. *
  15813. * WARNING: This method returns internal data without copying, for
  15814. * performance. The return value must NOT be mutated, and should be treated as
  15815. * an immutable borrow. If you want to take ownership, you must make your own
  15816. * copy.
  15817. */
  15818. MappingList.prototype.toArray = function MappingList_toArray() {
  15819. if (!this._sorted) {
  15820. this._array.sort(util.compareByGeneratedPositionsInflated);
  15821. this._sorted = true;
  15822. }
  15823. return this._array;
  15824. };
  15825. var MappingList_1 = MappingList;
  15826. var mappingList = {
  15827. MappingList: MappingList_1
  15828. };
  15829. /* -*- Mode: js; js-indent-level: 2; -*- */
  15830. /*
  15831. * Copyright 2011 Mozilla Foundation and contributors
  15832. * Licensed under the New BSD license. See LICENSE or:
  15833. * http://opensource.org/licenses/BSD-3-Clause
  15834. */
  15835. var ArraySet$1 = arraySet.ArraySet;
  15836. var MappingList$1 = mappingList.MappingList;
  15837. /**
  15838. * An instance of the SourceMapGenerator represents a source map which is
  15839. * being built incrementally. You may pass an object with the following
  15840. * properties:
  15841. *
  15842. * - file: The filename of the generated source.
  15843. * - sourceRoot: A root for all relative URLs in this source map.
  15844. */
  15845. function SourceMapGenerator(aArgs) {
  15846. if (!aArgs) {
  15847. aArgs = {};
  15848. }
  15849. this._file = util.getArg(aArgs, 'file', null);
  15850. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  15851. this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  15852. this._sources = new ArraySet$1();
  15853. this._names = new ArraySet$1();
  15854. this._mappings = new MappingList$1();
  15855. this._sourcesContents = null;
  15856. }
  15857. SourceMapGenerator.prototype._version = 3;
  15858. /**
  15859. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  15860. *
  15861. * @param aSourceMapConsumer The SourceMap.
  15862. */
  15863. SourceMapGenerator.fromSourceMap =
  15864. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  15865. var sourceRoot = aSourceMapConsumer.sourceRoot;
  15866. var generator = new SourceMapGenerator({
  15867. file: aSourceMapConsumer.file,
  15868. sourceRoot: sourceRoot
  15869. });
  15870. aSourceMapConsumer.eachMapping(function (mapping) {
  15871. var newMapping = {
  15872. generated: {
  15873. line: mapping.generatedLine,
  15874. column: mapping.generatedColumn
  15875. }
  15876. };
  15877. if (mapping.source != null) {
  15878. newMapping.source = mapping.source;
  15879. if (sourceRoot != null) {
  15880. newMapping.source = util.relative(sourceRoot, newMapping.source);
  15881. }
  15882. newMapping.original = {
  15883. line: mapping.originalLine,
  15884. column: mapping.originalColumn
  15885. };
  15886. if (mapping.name != null) {
  15887. newMapping.name = mapping.name;
  15888. }
  15889. }
  15890. generator.addMapping(newMapping);
  15891. });
  15892. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  15893. var sourceRelative = sourceFile;
  15894. if (sourceRoot !== null) {
  15895. sourceRelative = util.relative(sourceRoot, sourceFile);
  15896. }
  15897. if (!generator._sources.has(sourceRelative)) {
  15898. generator._sources.add(sourceRelative);
  15899. }
  15900. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  15901. if (content != null) {
  15902. generator.setSourceContent(sourceFile, content);
  15903. }
  15904. });
  15905. return generator;
  15906. };
  15907. /**
  15908. * Add a single mapping from original source line and column to the generated
  15909. * source's line and column for this source map being created. The mapping
  15910. * object should have the following properties:
  15911. *
  15912. * - generated: An object with the generated line and column positions.
  15913. * - original: An object with the original line and column positions.
  15914. * - source: The original source file (relative to the sourceRoot).
  15915. * - name: An optional original token name for this mapping.
  15916. */
  15917. SourceMapGenerator.prototype.addMapping =
  15918. function SourceMapGenerator_addMapping(aArgs) {
  15919. var generated = util.getArg(aArgs, 'generated');
  15920. var original = util.getArg(aArgs, 'original', null);
  15921. var source = util.getArg(aArgs, 'source', null);
  15922. var name = util.getArg(aArgs, 'name', null);
  15923. if (!this._skipValidation) {
  15924. this._validateMapping(generated, original, source, name);
  15925. }
  15926. if (source != null) {
  15927. source = String(source);
  15928. if (!this._sources.has(source)) {
  15929. this._sources.add(source);
  15930. }
  15931. }
  15932. if (name != null) {
  15933. name = String(name);
  15934. if (!this._names.has(name)) {
  15935. this._names.add(name);
  15936. }
  15937. }
  15938. this._mappings.add({
  15939. generatedLine: generated.line,
  15940. generatedColumn: generated.column,
  15941. originalLine: original != null && original.line,
  15942. originalColumn: original != null && original.column,
  15943. source: source,
  15944. name: name
  15945. });
  15946. };
  15947. /**
  15948. * Set the source content for a source file.
  15949. */
  15950. SourceMapGenerator.prototype.setSourceContent =
  15951. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  15952. var source = aSourceFile;
  15953. if (this._sourceRoot != null) {
  15954. source = util.relative(this._sourceRoot, source);
  15955. }
  15956. if (aSourceContent != null) {
  15957. // Add the source content to the _sourcesContents map.
  15958. // Create a new _sourcesContents map if the property is null.
  15959. if (!this._sourcesContents) {
  15960. this._sourcesContents = Object.create(null);
  15961. }
  15962. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  15963. } else if (this._sourcesContents) {
  15964. // Remove the source file from the _sourcesContents map.
  15965. // If the _sourcesContents map is empty, set the property to null.
  15966. delete this._sourcesContents[util.toSetString(source)];
  15967. if (Object.keys(this._sourcesContents).length === 0) {
  15968. this._sourcesContents = null;
  15969. }
  15970. }
  15971. };
  15972. /**
  15973. * Applies the mappings of a sub-source-map for a specific source file to the
  15974. * source map being generated. Each mapping to the supplied source file is
  15975. * rewritten using the supplied source map. Note: The resolution for the
  15976. * resulting mappings is the minimium of this map and the supplied map.
  15977. *
  15978. * @param aSourceMapConsumer The source map to be applied.
  15979. * @param aSourceFile Optional. The filename of the source file.
  15980. * If omitted, SourceMapConsumer's file property will be used.
  15981. * @param aSourceMapPath Optional. The dirname of the path to the source map
  15982. * to be applied. If relative, it is relative to the SourceMapConsumer.
  15983. * This parameter is needed when the two source maps aren't in the same
  15984. * directory, and the source map to be applied contains relative source
  15985. * paths. If so, those relative source paths need to be rewritten
  15986. * relative to the SourceMapGenerator.
  15987. */
  15988. SourceMapGenerator.prototype.applySourceMap =
  15989. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  15990. var sourceFile = aSourceFile;
  15991. // If aSourceFile is omitted, we will use the file property of the SourceMap
  15992. if (aSourceFile == null) {
  15993. if (aSourceMapConsumer.file == null) {
  15994. throw new Error(
  15995. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  15996. 'or the source map\'s "file" property. Both were omitted.'
  15997. );
  15998. }
  15999. sourceFile = aSourceMapConsumer.file;
  16000. }
  16001. var sourceRoot = this._sourceRoot;
  16002. // Make "sourceFile" relative if an absolute Url is passed.
  16003. if (sourceRoot != null) {
  16004. sourceFile = util.relative(sourceRoot, sourceFile);
  16005. }
  16006. // Applying the SourceMap can add and remove items from the sources and
  16007. // the names array.
  16008. var newSources = new ArraySet$1();
  16009. var newNames = new ArraySet$1();
  16010. // Find mappings for the "sourceFile"
  16011. this._mappings.unsortedForEach(function (mapping) {
  16012. if (mapping.source === sourceFile && mapping.originalLine != null) {
  16013. // Check if it can be mapped by the source map, then update the mapping.
  16014. var original = aSourceMapConsumer.originalPositionFor({
  16015. line: mapping.originalLine,
  16016. column: mapping.originalColumn
  16017. });
  16018. if (original.source != null) {
  16019. // Copy mapping
  16020. mapping.source = original.source;
  16021. if (aSourceMapPath != null) {
  16022. mapping.source = util.join(aSourceMapPath, mapping.source);
  16023. }
  16024. if (sourceRoot != null) {
  16025. mapping.source = util.relative(sourceRoot, mapping.source);
  16026. }
  16027. mapping.originalLine = original.line;
  16028. mapping.originalColumn = original.column;
  16029. if (original.name != null) {
  16030. mapping.name = original.name;
  16031. }
  16032. }
  16033. }
  16034. var source = mapping.source;
  16035. if (source != null && !newSources.has(source)) {
  16036. newSources.add(source);
  16037. }
  16038. var name = mapping.name;
  16039. if (name != null && !newNames.has(name)) {
  16040. newNames.add(name);
  16041. }
  16042. }, this);
  16043. this._sources = newSources;
  16044. this._names = newNames;
  16045. // Copy sourcesContents of applied map.
  16046. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  16047. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  16048. if (content != null) {
  16049. if (aSourceMapPath != null) {
  16050. sourceFile = util.join(aSourceMapPath, sourceFile);
  16051. }
  16052. if (sourceRoot != null) {
  16053. sourceFile = util.relative(sourceRoot, sourceFile);
  16054. }
  16055. this.setSourceContent(sourceFile, content);
  16056. }
  16057. }, this);
  16058. };
  16059. /**
  16060. * A mapping can have one of the three levels of data:
  16061. *
  16062. * 1. Just the generated position.
  16063. * 2. The Generated position, original position, and original source.
  16064. * 3. Generated and original position, original source, as well as a name
  16065. * token.
  16066. *
  16067. * To maintain consistency, we validate that any new mapping being added falls
  16068. * in to one of these categories.
  16069. */
  16070. SourceMapGenerator.prototype._validateMapping =
  16071. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  16072. aName) {
  16073. // When aOriginal is truthy but has empty values for .line and .column,
  16074. // it is most likely a programmer error. In this case we throw a very
  16075. // specific error message to try to guide them the right way.
  16076. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  16077. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  16078. throw new Error(
  16079. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  16080. 'the original mapping entirely and only map the generated position. If so, pass ' +
  16081. 'null for the original mapping instead of an object with empty or null values.'
  16082. );
  16083. }
  16084. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  16085. && aGenerated.line > 0 && aGenerated.column >= 0
  16086. && !aOriginal && !aSource && !aName) {
  16087. // Case 1.
  16088. return;
  16089. }
  16090. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  16091. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  16092. && aGenerated.line > 0 && aGenerated.column >= 0
  16093. && aOriginal.line > 0 && aOriginal.column >= 0
  16094. && aSource) {
  16095. // Cases 2 and 3.
  16096. return;
  16097. }
  16098. else {
  16099. throw new Error('Invalid mapping: ' + JSON.stringify({
  16100. generated: aGenerated,
  16101. source: aSource,
  16102. original: aOriginal,
  16103. name: aName
  16104. }));
  16105. }
  16106. };
  16107. /**
  16108. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  16109. * specified by the source map format.
  16110. */
  16111. SourceMapGenerator.prototype._serializeMappings =
  16112. function SourceMapGenerator_serializeMappings() {
  16113. var previousGeneratedColumn = 0;
  16114. var previousGeneratedLine = 1;
  16115. var previousOriginalColumn = 0;
  16116. var previousOriginalLine = 0;
  16117. var previousName = 0;
  16118. var previousSource = 0;
  16119. var result = '';
  16120. var next;
  16121. var mapping;
  16122. var nameIdx;
  16123. var sourceIdx;
  16124. var mappings = this._mappings.toArray();
  16125. for (var i = 0, len = mappings.length; i < len; i++) {
  16126. mapping = mappings[i];
  16127. next = '';
  16128. if (mapping.generatedLine !== previousGeneratedLine) {
  16129. previousGeneratedColumn = 0;
  16130. while (mapping.generatedLine !== previousGeneratedLine) {
  16131. next += ';';
  16132. previousGeneratedLine++;
  16133. }
  16134. }
  16135. else {
  16136. if (i > 0) {
  16137. if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  16138. continue;
  16139. }
  16140. next += ',';
  16141. }
  16142. }
  16143. next += base64Vlq.encode(mapping.generatedColumn
  16144. - previousGeneratedColumn);
  16145. previousGeneratedColumn = mapping.generatedColumn;
  16146. if (mapping.source != null) {
  16147. sourceIdx = this._sources.indexOf(mapping.source);
  16148. next += base64Vlq.encode(sourceIdx - previousSource);
  16149. previousSource = sourceIdx;
  16150. // lines are stored 0-based in SourceMap spec version 3
  16151. next += base64Vlq.encode(mapping.originalLine - 1
  16152. - previousOriginalLine);
  16153. previousOriginalLine = mapping.originalLine - 1;
  16154. next += base64Vlq.encode(mapping.originalColumn
  16155. - previousOriginalColumn);
  16156. previousOriginalColumn = mapping.originalColumn;
  16157. if (mapping.name != null) {
  16158. nameIdx = this._names.indexOf(mapping.name);
  16159. next += base64Vlq.encode(nameIdx - previousName);
  16160. previousName = nameIdx;
  16161. }
  16162. }
  16163. result += next;
  16164. }
  16165. return result;
  16166. };
  16167. SourceMapGenerator.prototype._generateSourcesContent =
  16168. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  16169. return aSources.map(function (source) {
  16170. if (!this._sourcesContents) {
  16171. return null;
  16172. }
  16173. if (aSourceRoot != null) {
  16174. source = util.relative(aSourceRoot, source);
  16175. }
  16176. var key = util.toSetString(source);
  16177. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  16178. ? this._sourcesContents[key]
  16179. : null;
  16180. }, this);
  16181. };
  16182. /**
  16183. * Externalize the source map.
  16184. */
  16185. SourceMapGenerator.prototype.toJSON =
  16186. function SourceMapGenerator_toJSON() {
  16187. var map = {
  16188. version: this._version,
  16189. sources: this._sources.toArray(),
  16190. names: this._names.toArray(),
  16191. mappings: this._serializeMappings()
  16192. };
  16193. if (this._file != null) {
  16194. map.file = this._file;
  16195. }
  16196. if (this._sourceRoot != null) {
  16197. map.sourceRoot = this._sourceRoot;
  16198. }
  16199. if (this._sourcesContents) {
  16200. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  16201. }
  16202. return map;
  16203. };
  16204. /**
  16205. * Render the source map being generated to a string.
  16206. */
  16207. SourceMapGenerator.prototype.toString =
  16208. function SourceMapGenerator_toString() {
  16209. return JSON.stringify(this.toJSON());
  16210. };
  16211. var SourceMapGenerator_1 = SourceMapGenerator;
  16212. var sourceMapGenerator = {
  16213. SourceMapGenerator: SourceMapGenerator_1
  16214. };
  16215. /* -*- Mode: js; js-indent-level: 2; -*- */
  16216. var binarySearch = createCommonjsModule(function (module, exports) {
  16217. /*
  16218. * Copyright 2011 Mozilla Foundation and contributors
  16219. * Licensed under the New BSD license. See LICENSE or:
  16220. * http://opensource.org/licenses/BSD-3-Clause
  16221. */
  16222. exports.GREATEST_LOWER_BOUND = 1;
  16223. exports.LEAST_UPPER_BOUND = 2;
  16224. /**
  16225. * Recursive implementation of binary search.
  16226. *
  16227. * @param aLow Indices here and lower do not contain the needle.
  16228. * @param aHigh Indices here and higher do not contain the needle.
  16229. * @param aNeedle The element being searched for.
  16230. * @param aHaystack The non-empty array being searched.
  16231. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  16232. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  16233. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  16234. * closest element that is smaller than or greater than the one we are
  16235. * searching for, respectively, if the exact element cannot be found.
  16236. */
  16237. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  16238. // This function terminates when one of the following is true:
  16239. //
  16240. // 1. We find the exact element we are looking for.
  16241. //
  16242. // 2. We did not find the exact element, but we can return the index of
  16243. // the next-closest element.
  16244. //
  16245. // 3. We did not find the exact element, and there is no next-closest
  16246. // element than the one we are searching for, so we return -1.
  16247. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  16248. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  16249. if (cmp === 0) {
  16250. // Found the element we are looking for.
  16251. return mid;
  16252. }
  16253. else if (cmp > 0) {
  16254. // Our needle is greater than aHaystack[mid].
  16255. if (aHigh - mid > 1) {
  16256. // The element is in the upper half.
  16257. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  16258. }
  16259. // The exact needle element was not found in this haystack. Determine if
  16260. // we are in termination case (3) or (2) and return the appropriate thing.
  16261. if (aBias == exports.LEAST_UPPER_BOUND) {
  16262. return aHigh < aHaystack.length ? aHigh : -1;
  16263. } else {
  16264. return mid;
  16265. }
  16266. }
  16267. else {
  16268. // Our needle is less than aHaystack[mid].
  16269. if (mid - aLow > 1) {
  16270. // The element is in the lower half.
  16271. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  16272. }
  16273. // we are in termination case (3) or (2) and return the appropriate thing.
  16274. if (aBias == exports.LEAST_UPPER_BOUND) {
  16275. return mid;
  16276. } else {
  16277. return aLow < 0 ? -1 : aLow;
  16278. }
  16279. }
  16280. }
  16281. /**
  16282. * This is an implementation of binary search which will always try and return
  16283. * the index of the closest element if there is no exact hit. This is because
  16284. * mappings between original and generated line/col pairs are single points,
  16285. * and there is an implicit region between each of them, so a miss just means
  16286. * that you aren't on the very start of a region.
  16287. *
  16288. * @param aNeedle The element you are looking for.
  16289. * @param aHaystack The array that is being searched.
  16290. * @param aCompare A function which takes the needle and an element in the
  16291. * array and returns -1, 0, or 1 depending on whether the needle is less
  16292. * than, equal to, or greater than the element, respectively.
  16293. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  16294. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  16295. * closest element that is smaller than or greater than the one we are
  16296. * searching for, respectively, if the exact element cannot be found.
  16297. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  16298. */
  16299. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  16300. if (aHaystack.length === 0) {
  16301. return -1;
  16302. }
  16303. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  16304. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  16305. if (index < 0) {
  16306. return -1;
  16307. }
  16308. // We have found either the exact element, or the next-closest element than
  16309. // the one we are searching for. However, there may be more than one such
  16310. // element. Make sure we always return the smallest of these.
  16311. while (index - 1 >= 0) {
  16312. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  16313. break;
  16314. }
  16315. --index;
  16316. }
  16317. return index;
  16318. };
  16319. });
  16320. /* -*- Mode: js; js-indent-level: 2; -*- */
  16321. /*
  16322. * Copyright 2011 Mozilla Foundation and contributors
  16323. * Licensed under the New BSD license. See LICENSE or:
  16324. * http://opensource.org/licenses/BSD-3-Clause
  16325. */
  16326. // It turns out that some (most?) JavaScript engines don't self-host
  16327. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  16328. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  16329. // custom comparator function, calling back and forth between the VM's C++ and
  16330. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  16331. // worse generated code for the comparator function than would be optimal. In
  16332. // fact, when sorting with a comparator, these costs outweigh the benefits of
  16333. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  16334. // a ~3500ms mean speed-up in `bench/bench.html`.
  16335. /**
  16336. * Swap the elements indexed by `x` and `y` in the array `ary`.
  16337. *
  16338. * @param {Array} ary
  16339. * The array.
  16340. * @param {Number} x
  16341. * The index of the first item.
  16342. * @param {Number} y
  16343. * The index of the second item.
  16344. */
  16345. function swap(ary, x, y) {
  16346. var temp = ary[x];
  16347. ary[x] = ary[y];
  16348. ary[y] = temp;
  16349. }
  16350. /**
  16351. * Returns a random integer within the range `low .. high` inclusive.
  16352. *
  16353. * @param {Number} low
  16354. * The lower bound on the range.
  16355. * @param {Number} high
  16356. * The upper bound on the range.
  16357. */
  16358. function randomIntInRange(low, high) {
  16359. return Math.round(low + (Math.random() * (high - low)));
  16360. }
  16361. /**
  16362. * The Quick Sort algorithm.
  16363. *
  16364. * @param {Array} ary
  16365. * An array to sort.
  16366. * @param {function} comparator
  16367. * Function to use to compare two items.
  16368. * @param {Number} p
  16369. * Start index of the array
  16370. * @param {Number} r
  16371. * End index of the array
  16372. */
  16373. function doQuickSort(ary, comparator, p, r) {
  16374. // If our lower bound is less than our upper bound, we (1) partition the
  16375. // array into two pieces and (2) recurse on each half. If it is not, this is
  16376. // the empty array and our base case.
  16377. if (p < r) {
  16378. // (1) Partitioning.
  16379. //
  16380. // The partitioning chooses a pivot between `p` and `r` and moves all
  16381. // elements that are less than or equal to the pivot to the before it, and
  16382. // all the elements that are greater than it after it. The effect is that
  16383. // once partition is done, the pivot is in the exact place it will be when
  16384. // the array is put in sorted order, and it will not need to be moved
  16385. // again. This runs in O(n) time.
  16386. // Always choose a random pivot so that an input array which is reverse
  16387. // sorted does not cause O(n^2) running time.
  16388. var pivotIndex = randomIntInRange(p, r);
  16389. var i = p - 1;
  16390. swap(ary, pivotIndex, r);
  16391. var pivot = ary[r];
  16392. // Immediately after `j` is incremented in this loop, the following hold
  16393. // true:
  16394. //
  16395. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  16396. //
  16397. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  16398. for (var j = p; j < r; j++) {
  16399. if (comparator(ary[j], pivot) <= 0) {
  16400. i += 1;
  16401. swap(ary, i, j);
  16402. }
  16403. }
  16404. swap(ary, i + 1, j);
  16405. var q = i + 1;
  16406. // (2) Recurse on each half.
  16407. doQuickSort(ary, comparator, p, q - 1);
  16408. doQuickSort(ary, comparator, q + 1, r);
  16409. }
  16410. }
  16411. /**
  16412. * Sort the given array in-place with the given comparator function.
  16413. *
  16414. * @param {Array} ary
  16415. * An array to sort.
  16416. * @param {function} comparator
  16417. * Function to use to compare two items.
  16418. */
  16419. var quickSort_1 = function (ary, comparator) {
  16420. doQuickSort(ary, comparator, 0, ary.length - 1);
  16421. };
  16422. var quickSort = {
  16423. quickSort: quickSort_1
  16424. };
  16425. /* -*- Mode: js; js-indent-level: 2; -*- */
  16426. /*
  16427. * Copyright 2011 Mozilla Foundation and contributors
  16428. * Licensed under the New BSD license. See LICENSE or:
  16429. * http://opensource.org/licenses/BSD-3-Clause
  16430. */
  16431. var ArraySet$2 = arraySet.ArraySet;
  16432. var quickSort$1 = quickSort.quickSort;
  16433. function SourceMapConsumer(aSourceMap, aSourceMapURL) {
  16434. var sourceMap = aSourceMap;
  16435. if (typeof aSourceMap === 'string') {
  16436. sourceMap = util.parseSourceMapInput(aSourceMap);
  16437. }
  16438. return sourceMap.sections != null
  16439. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  16440. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  16441. }
  16442. SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  16443. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  16444. };
  16445. /**
  16446. * The version of the source mapping spec that we are consuming.
  16447. */
  16448. SourceMapConsumer.prototype._version = 3;
  16449. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  16450. // parsed mapping coordinates from the source map's "mappings" attribute. They
  16451. // are lazily instantiated, accessed via the `_generatedMappings` and
  16452. // `_originalMappings` getters respectively, and we only parse the mappings
  16453. // and create these arrays once queried for a source location. We jump through
  16454. // these hoops because there can be many thousands of mappings, and parsing
  16455. // them is expensive, so we only want to do it if we must.
  16456. //
  16457. // Each object in the arrays is of the form:
  16458. //
  16459. // {
  16460. // generatedLine: The line number in the generated code,
  16461. // generatedColumn: The column number in the generated code,
  16462. // source: The path to the original source file that generated this
  16463. // chunk of code,
  16464. // originalLine: The line number in the original source that
  16465. // corresponds to this chunk of generated code,
  16466. // originalColumn: The column number in the original source that
  16467. // corresponds to this chunk of generated code,
  16468. // name: The name of the original symbol which generated this chunk of
  16469. // code.
  16470. // }
  16471. //
  16472. // All properties except for `generatedLine` and `generatedColumn` can be
  16473. // `null`.
  16474. //
  16475. // `_generatedMappings` is ordered by the generated positions.
  16476. //
  16477. // `_originalMappings` is ordered by the original positions.
  16478. SourceMapConsumer.prototype.__generatedMappings = null;
  16479. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  16480. configurable: true,
  16481. enumerable: true,
  16482. get: function () {
  16483. if (!this.__generatedMappings) {
  16484. this._parseMappings(this._mappings, this.sourceRoot);
  16485. }
  16486. return this.__generatedMappings;
  16487. }
  16488. });
  16489. SourceMapConsumer.prototype.__originalMappings = null;
  16490. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  16491. configurable: true,
  16492. enumerable: true,
  16493. get: function () {
  16494. if (!this.__originalMappings) {
  16495. this._parseMappings(this._mappings, this.sourceRoot);
  16496. }
  16497. return this.__originalMappings;
  16498. }
  16499. });
  16500. SourceMapConsumer.prototype._charIsMappingSeparator =
  16501. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  16502. var c = aStr.charAt(index);
  16503. return c === ";" || c === ",";
  16504. };
  16505. /**
  16506. * Parse the mappings in a string in to a data structure which we can easily
  16507. * query (the ordered arrays in the `this.__generatedMappings` and
  16508. * `this.__originalMappings` properties).
  16509. */
  16510. SourceMapConsumer.prototype._parseMappings =
  16511. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  16512. throw new Error("Subclasses must implement _parseMappings");
  16513. };
  16514. SourceMapConsumer.GENERATED_ORDER = 1;
  16515. SourceMapConsumer.ORIGINAL_ORDER = 2;
  16516. SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
  16517. SourceMapConsumer.LEAST_UPPER_BOUND = 2;
  16518. /**
  16519. * Iterate over each mapping between an original source/line/column and a
  16520. * generated line/column in this source map.
  16521. *
  16522. * @param Function aCallback
  16523. * The function that is called with each mapping.
  16524. * @param Object aContext
  16525. * Optional. If specified, this object will be the value of `this` every
  16526. * time that `aCallback` is called.
  16527. * @param aOrder
  16528. * Either `SourceMapConsumer.GENERATED_ORDER` or
  16529. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  16530. * iterate over the mappings sorted by the generated file's line/column
  16531. * order or the original's source/line/column order, respectively. Defaults to
  16532. * `SourceMapConsumer.GENERATED_ORDER`.
  16533. */
  16534. SourceMapConsumer.prototype.eachMapping =
  16535. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  16536. var context = aContext || null;
  16537. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  16538. var mappings;
  16539. switch (order) {
  16540. case SourceMapConsumer.GENERATED_ORDER:
  16541. mappings = this._generatedMappings;
  16542. break;
  16543. case SourceMapConsumer.ORIGINAL_ORDER:
  16544. mappings = this._originalMappings;
  16545. break;
  16546. default:
  16547. throw new Error("Unknown order of iteration.");
  16548. }
  16549. var sourceRoot = this.sourceRoot;
  16550. mappings.map(function (mapping) {
  16551. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  16552. source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);
  16553. return {
  16554. source: source,
  16555. generatedLine: mapping.generatedLine,
  16556. generatedColumn: mapping.generatedColumn,
  16557. originalLine: mapping.originalLine,
  16558. originalColumn: mapping.originalColumn,
  16559. name: mapping.name === null ? null : this._names.at(mapping.name)
  16560. };
  16561. }, this).forEach(aCallback, context);
  16562. };
  16563. /**
  16564. * Returns all generated line and column information for the original source,
  16565. * line, and column provided. If no column is provided, returns all mappings
  16566. * corresponding to a either the line we are searching for or the next
  16567. * closest line that has any mappings. Otherwise, returns all mappings
  16568. * corresponding to the given line and either the column we are searching for
  16569. * or the next closest column that has any offsets.
  16570. *
  16571. * The only argument is an object with the following properties:
  16572. *
  16573. * - source: The filename of the original source.
  16574. * - line: The line number in the original source. The line number is 1-based.
  16575. * - column: Optional. the column number in the original source.
  16576. * The column number is 0-based.
  16577. *
  16578. * and an array of objects is returned, each with the following properties:
  16579. *
  16580. * - line: The line number in the generated source, or null. The
  16581. * line number is 1-based.
  16582. * - column: The column number in the generated source, or null.
  16583. * The column number is 0-based.
  16584. */
  16585. SourceMapConsumer.prototype.allGeneratedPositionsFor =
  16586. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  16587. var line = util.getArg(aArgs, 'line');
  16588. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  16589. // returns the index of the closest mapping less than the needle. By
  16590. // setting needle.originalColumn to 0, we thus find the last mapping for
  16591. // the given line, provided such a mapping exists.
  16592. var needle = {
  16593. source: util.getArg(aArgs, 'source'),
  16594. originalLine: line,
  16595. originalColumn: util.getArg(aArgs, 'column', 0)
  16596. };
  16597. needle.source = this._findSourceIndex(needle.source);
  16598. if (needle.source < 0) {
  16599. return [];
  16600. }
  16601. var mappings = [];
  16602. var index = this._findMapping(needle,
  16603. this._originalMappings,
  16604. "originalLine",
  16605. "originalColumn",
  16606. util.compareByOriginalPositions,
  16607. binarySearch.LEAST_UPPER_BOUND);
  16608. if (index >= 0) {
  16609. var mapping = this._originalMappings[index];
  16610. if (aArgs.column === undefined) {
  16611. var originalLine = mapping.originalLine;
  16612. // Iterate until either we run out of mappings, or we run into
  16613. // a mapping for a different line than the one we found. Since
  16614. // mappings are sorted, this is guaranteed to find all mappings for
  16615. // the line we found.
  16616. while (mapping && mapping.originalLine === originalLine) {
  16617. mappings.push({
  16618. line: util.getArg(mapping, 'generatedLine', null),
  16619. column: util.getArg(mapping, 'generatedColumn', null),
  16620. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  16621. });
  16622. mapping = this._originalMappings[++index];
  16623. }
  16624. } else {
  16625. var originalColumn = mapping.originalColumn;
  16626. // Iterate until either we run out of mappings, or we run into
  16627. // a mapping for a different line than the one we were searching for.
  16628. // Since mappings are sorted, this is guaranteed to find all mappings for
  16629. // the line we are searching for.
  16630. while (mapping &&
  16631. mapping.originalLine === line &&
  16632. mapping.originalColumn == originalColumn) {
  16633. mappings.push({
  16634. line: util.getArg(mapping, 'generatedLine', null),
  16635. column: util.getArg(mapping, 'generatedColumn', null),
  16636. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  16637. });
  16638. mapping = this._originalMappings[++index];
  16639. }
  16640. }
  16641. }
  16642. return mappings;
  16643. };
  16644. var SourceMapConsumer_1 = SourceMapConsumer;
  16645. /**
  16646. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  16647. * query for information about the original file positions by giving it a file
  16648. * position in the generated source.
  16649. *
  16650. * The first parameter is the raw source map (either as a JSON string, or
  16651. * already parsed to an object). According to the spec, source maps have the
  16652. * following attributes:
  16653. *
  16654. * - version: Which version of the source map spec this map is following.
  16655. * - sources: An array of URLs to the original source files.
  16656. * - names: An array of identifiers which can be referrenced by individual mappings.
  16657. * - sourceRoot: Optional. The URL root from which all sources are relative.
  16658. * - sourcesContent: Optional. An array of contents of the original source files.
  16659. * - mappings: A string of base64 VLQs which contain the actual mappings.
  16660. * - file: Optional. The generated file this source map is associated with.
  16661. *
  16662. * Here is an example source map, taken from the source map spec[0]:
  16663. *
  16664. * {
  16665. * version : 3,
  16666. * file: "out.js",
  16667. * sourceRoot : "",
  16668. * sources: ["foo.js", "bar.js"],
  16669. * names: ["src", "maps", "are", "fun"],
  16670. * mappings: "AA,AB;;ABCDE;"
  16671. * }
  16672. *
  16673. * The second parameter, if given, is a string whose value is the URL
  16674. * at which the source map was found. This URL is used to compute the
  16675. * sources array.
  16676. *
  16677. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  16678. */
  16679. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  16680. var sourceMap = aSourceMap;
  16681. if (typeof aSourceMap === 'string') {
  16682. sourceMap = util.parseSourceMapInput(aSourceMap);
  16683. }
  16684. var version = util.getArg(sourceMap, 'version');
  16685. var sources = util.getArg(sourceMap, 'sources');
  16686. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  16687. // requires the array) to play nice here.
  16688. var names = util.getArg(sourceMap, 'names', []);
  16689. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  16690. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  16691. var mappings = util.getArg(sourceMap, 'mappings');
  16692. var file = util.getArg(sourceMap, 'file', null);
  16693. // Once again, Sass deviates from the spec and supplies the version as a
  16694. // string rather than a number, so we use loose equality checking here.
  16695. if (version != this._version) {
  16696. throw new Error('Unsupported version: ' + version);
  16697. }
  16698. if (sourceRoot) {
  16699. sourceRoot = util.normalize(sourceRoot);
  16700. }
  16701. sources = sources
  16702. .map(String)
  16703. // Some source maps produce relative source paths like "./foo.js" instead of
  16704. // "foo.js". Normalize these first so that future comparisons will succeed.
  16705. // See bugzil.la/1090768.
  16706. .map(util.normalize)
  16707. // Always ensure that absolute sources are internally stored relative to
  16708. // the source root, if the source root is absolute. Not doing this would
  16709. // be particularly problematic when the source root is a prefix of the
  16710. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  16711. .map(function (source) {
  16712. return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
  16713. ? util.relative(sourceRoot, source)
  16714. : source;
  16715. });
  16716. // Pass `true` below to allow duplicate names and sources. While source maps
  16717. // are intended to be compressed and deduplicated, the TypeScript compiler
  16718. // sometimes generates source maps with duplicates in them. See Github issue
  16719. // #72 and bugzil.la/889492.
  16720. this._names = ArraySet$2.fromArray(names.map(String), true);
  16721. this._sources = ArraySet$2.fromArray(sources, true);
  16722. this._absoluteSources = this._sources.toArray().map(function (s) {
  16723. return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
  16724. });
  16725. this.sourceRoot = sourceRoot;
  16726. this.sourcesContent = sourcesContent;
  16727. this._mappings = mappings;
  16728. this._sourceMapURL = aSourceMapURL;
  16729. this.file = file;
  16730. }
  16731. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  16732. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
  16733. /**
  16734. * Utility function to find the index of a source. Returns -1 if not
  16735. * found.
  16736. */
  16737. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  16738. var relativeSource = aSource;
  16739. if (this.sourceRoot != null) {
  16740. relativeSource = util.relative(this.sourceRoot, relativeSource);
  16741. }
  16742. if (this._sources.has(relativeSource)) {
  16743. return this._sources.indexOf(relativeSource);
  16744. }
  16745. // Maybe aSource is an absolute URL as returned by |sources|. In
  16746. // this case we can't simply undo the transform.
  16747. var i;
  16748. for (i = 0; i < this._absoluteSources.length; ++i) {
  16749. if (this._absoluteSources[i] == aSource) {
  16750. return i;
  16751. }
  16752. }
  16753. return -1;
  16754. };
  16755. /**
  16756. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  16757. *
  16758. * @param SourceMapGenerator aSourceMap
  16759. * The source map that will be consumed.
  16760. * @param String aSourceMapURL
  16761. * The URL at which the source map can be found (optional)
  16762. * @returns BasicSourceMapConsumer
  16763. */
  16764. BasicSourceMapConsumer.fromSourceMap =
  16765. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  16766. var smc = Object.create(BasicSourceMapConsumer.prototype);
  16767. var names = smc._names = ArraySet$2.fromArray(aSourceMap._names.toArray(), true);
  16768. var sources = smc._sources = ArraySet$2.fromArray(aSourceMap._sources.toArray(), true);
  16769. smc.sourceRoot = aSourceMap._sourceRoot;
  16770. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  16771. smc.sourceRoot);
  16772. smc.file = aSourceMap._file;
  16773. smc._sourceMapURL = aSourceMapURL;
  16774. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  16775. return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  16776. });
  16777. // Because we are modifying the entries (by converting string sources and
  16778. // names to indices into the sources and names ArraySets), we have to make
  16779. // a copy of the entry or else bad things happen. Shared mutable state
  16780. // strikes again! See github issue #191.
  16781. var generatedMappings = aSourceMap._mappings.toArray().slice();
  16782. var destGeneratedMappings = smc.__generatedMappings = [];
  16783. var destOriginalMappings = smc.__originalMappings = [];
  16784. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  16785. var srcMapping = generatedMappings[i];
  16786. var destMapping = new Mapping;
  16787. destMapping.generatedLine = srcMapping.generatedLine;
  16788. destMapping.generatedColumn = srcMapping.generatedColumn;
  16789. if (srcMapping.source) {
  16790. destMapping.source = sources.indexOf(srcMapping.source);
  16791. destMapping.originalLine = srcMapping.originalLine;
  16792. destMapping.originalColumn = srcMapping.originalColumn;
  16793. if (srcMapping.name) {
  16794. destMapping.name = names.indexOf(srcMapping.name);
  16795. }
  16796. destOriginalMappings.push(destMapping);
  16797. }
  16798. destGeneratedMappings.push(destMapping);
  16799. }
  16800. quickSort$1(smc.__originalMappings, util.compareByOriginalPositions);
  16801. return smc;
  16802. };
  16803. /**
  16804. * The version of the source mapping spec that we are consuming.
  16805. */
  16806. BasicSourceMapConsumer.prototype._version = 3;
  16807. /**
  16808. * The list of original sources.
  16809. */
  16810. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  16811. get: function () {
  16812. return this._absoluteSources.slice();
  16813. }
  16814. });
  16815. /**
  16816. * Provide the JIT with a nice shape / hidden class.
  16817. */
  16818. function Mapping() {
  16819. this.generatedLine = 0;
  16820. this.generatedColumn = 0;
  16821. this.source = null;
  16822. this.originalLine = null;
  16823. this.originalColumn = null;
  16824. this.name = null;
  16825. }
  16826. /**
  16827. * Parse the mappings in a string in to a data structure which we can easily
  16828. * query (the ordered arrays in the `this.__generatedMappings` and
  16829. * `this.__originalMappings` properties).
  16830. */
  16831. BasicSourceMapConsumer.prototype._parseMappings =
  16832. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  16833. var generatedLine = 1;
  16834. var previousGeneratedColumn = 0;
  16835. var previousOriginalLine = 0;
  16836. var previousOriginalColumn = 0;
  16837. var previousSource = 0;
  16838. var previousName = 0;
  16839. var length = aStr.length;
  16840. var index = 0;
  16841. var cachedSegments = {};
  16842. var temp = {};
  16843. var originalMappings = [];
  16844. var generatedMappings = [];
  16845. var mapping, str, segment, end, value;
  16846. while (index < length) {
  16847. if (aStr.charAt(index) === ';') {
  16848. generatedLine++;
  16849. index++;
  16850. previousGeneratedColumn = 0;
  16851. }
  16852. else if (aStr.charAt(index) === ',') {
  16853. index++;
  16854. }
  16855. else {
  16856. mapping = new Mapping();
  16857. mapping.generatedLine = generatedLine;
  16858. // Because each offset is encoded relative to the previous one,
  16859. // many segments often have the same encoding. We can exploit this
  16860. // fact by caching the parsed variable length fields of each segment,
  16861. // allowing us to avoid a second parse if we encounter the same
  16862. // segment again.
  16863. for (end = index; end < length; end++) {
  16864. if (this._charIsMappingSeparator(aStr, end)) {
  16865. break;
  16866. }
  16867. }
  16868. str = aStr.slice(index, end);
  16869. segment = cachedSegments[str];
  16870. if (segment) {
  16871. index += str.length;
  16872. } else {
  16873. segment = [];
  16874. while (index < end) {
  16875. base64Vlq.decode(aStr, index, temp);
  16876. value = temp.value;
  16877. index = temp.rest;
  16878. segment.push(value);
  16879. }
  16880. if (segment.length === 2) {
  16881. throw new Error('Found a source, but no line and column');
  16882. }
  16883. if (segment.length === 3) {
  16884. throw new Error('Found a source and line, but no column');
  16885. }
  16886. cachedSegments[str] = segment;
  16887. }
  16888. // Generated column.
  16889. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  16890. previousGeneratedColumn = mapping.generatedColumn;
  16891. if (segment.length > 1) {
  16892. // Original source.
  16893. mapping.source = previousSource + segment[1];
  16894. previousSource += segment[1];
  16895. // Original line.
  16896. mapping.originalLine = previousOriginalLine + segment[2];
  16897. previousOriginalLine = mapping.originalLine;
  16898. // Lines are stored 0-based
  16899. mapping.originalLine += 1;
  16900. // Original column.
  16901. mapping.originalColumn = previousOriginalColumn + segment[3];
  16902. previousOriginalColumn = mapping.originalColumn;
  16903. if (segment.length > 4) {
  16904. // Original name.
  16905. mapping.name = previousName + segment[4];
  16906. previousName += segment[4];
  16907. }
  16908. }
  16909. generatedMappings.push(mapping);
  16910. if (typeof mapping.originalLine === 'number') {
  16911. originalMappings.push(mapping);
  16912. }
  16913. }
  16914. }
  16915. quickSort$1(generatedMappings, util.compareByGeneratedPositionsDeflated);
  16916. this.__generatedMappings = generatedMappings;
  16917. quickSort$1(originalMappings, util.compareByOriginalPositions);
  16918. this.__originalMappings = originalMappings;
  16919. };
  16920. /**
  16921. * Find the mapping that best matches the hypothetical "needle" mapping that
  16922. * we are searching for in the given "haystack" of mappings.
  16923. */
  16924. BasicSourceMapConsumer.prototype._findMapping =
  16925. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  16926. aColumnName, aComparator, aBias) {
  16927. // To return the position we are searching for, we must first find the
  16928. // mapping for the given position and then return the opposite position it
  16929. // points to. Because the mappings are sorted, we can use binary search to
  16930. // find the best mapping.
  16931. if (aNeedle[aLineName] <= 0) {
  16932. throw new TypeError('Line must be greater than or equal to 1, got '
  16933. + aNeedle[aLineName]);
  16934. }
  16935. if (aNeedle[aColumnName] < 0) {
  16936. throw new TypeError('Column must be greater than or equal to 0, got '
  16937. + aNeedle[aColumnName]);
  16938. }
  16939. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  16940. };
  16941. /**
  16942. * Compute the last column for each generated mapping. The last column is
  16943. * inclusive.
  16944. */
  16945. BasicSourceMapConsumer.prototype.computeColumnSpans =
  16946. function SourceMapConsumer_computeColumnSpans() {
  16947. for (var index = 0; index < this._generatedMappings.length; ++index) {
  16948. var mapping = this._generatedMappings[index];
  16949. // Mappings do not contain a field for the last generated columnt. We
  16950. // can come up with an optimistic estimate, however, by assuming that
  16951. // mappings are contiguous (i.e. given two consecutive mappings, the
  16952. // first mapping ends where the second one starts).
  16953. if (index + 1 < this._generatedMappings.length) {
  16954. var nextMapping = this._generatedMappings[index + 1];
  16955. if (mapping.generatedLine === nextMapping.generatedLine) {
  16956. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  16957. continue;
  16958. }
  16959. }
  16960. // The last mapping for each line spans the entire line.
  16961. mapping.lastGeneratedColumn = Infinity;
  16962. }
  16963. };
  16964. /**
  16965. * Returns the original source, line, and column information for the generated
  16966. * source's line and column positions provided. The only argument is an object
  16967. * with the following properties:
  16968. *
  16969. * - line: The line number in the generated source. The line number
  16970. * is 1-based.
  16971. * - column: The column number in the generated source. The column
  16972. * number is 0-based.
  16973. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  16974. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  16975. * closest element that is smaller than or greater than the one we are
  16976. * searching for, respectively, if the exact element cannot be found.
  16977. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  16978. *
  16979. * and an object is returned with the following properties:
  16980. *
  16981. * - source: The original source file, or null.
  16982. * - line: The line number in the original source, or null. The
  16983. * line number is 1-based.
  16984. * - column: The column number in the original source, or null. The
  16985. * column number is 0-based.
  16986. * - name: The original identifier, or null.
  16987. */
  16988. BasicSourceMapConsumer.prototype.originalPositionFor =
  16989. function SourceMapConsumer_originalPositionFor(aArgs) {
  16990. var needle = {
  16991. generatedLine: util.getArg(aArgs, 'line'),
  16992. generatedColumn: util.getArg(aArgs, 'column')
  16993. };
  16994. var index = this._findMapping(
  16995. needle,
  16996. this._generatedMappings,
  16997. "generatedLine",
  16998. "generatedColumn",
  16999. util.compareByGeneratedPositionsDeflated,
  17000. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  17001. );
  17002. if (index >= 0) {
  17003. var mapping = this._generatedMappings[index];
  17004. if (mapping.generatedLine === needle.generatedLine) {
  17005. var source = util.getArg(mapping, 'source', null);
  17006. if (source !== null) {
  17007. source = this._sources.at(source);
  17008. source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  17009. }
  17010. var name = util.getArg(mapping, 'name', null);
  17011. if (name !== null) {
  17012. name = this._names.at(name);
  17013. }
  17014. return {
  17015. source: source,
  17016. line: util.getArg(mapping, 'originalLine', null),
  17017. column: util.getArg(mapping, 'originalColumn', null),
  17018. name: name
  17019. };
  17020. }
  17021. }
  17022. return {
  17023. source: null,
  17024. line: null,
  17025. column: null,
  17026. name: null
  17027. };
  17028. };
  17029. /**
  17030. * Return true if we have the source content for every source in the source
  17031. * map, false otherwise.
  17032. */
  17033. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  17034. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  17035. if (!this.sourcesContent) {
  17036. return false;
  17037. }
  17038. return this.sourcesContent.length >= this._sources.size() &&
  17039. !this.sourcesContent.some(function (sc) { return sc == null; });
  17040. };
  17041. /**
  17042. * Returns the original source content. The only argument is the url of the
  17043. * original source file. Returns null if no original source content is
  17044. * available.
  17045. */
  17046. BasicSourceMapConsumer.prototype.sourceContentFor =
  17047. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  17048. if (!this.sourcesContent) {
  17049. return null;
  17050. }
  17051. var index = this._findSourceIndex(aSource);
  17052. if (index >= 0) {
  17053. return this.sourcesContent[index];
  17054. }
  17055. var relativeSource = aSource;
  17056. if (this.sourceRoot != null) {
  17057. relativeSource = util.relative(this.sourceRoot, relativeSource);
  17058. }
  17059. var url;
  17060. if (this.sourceRoot != null
  17061. && (url = util.urlParse(this.sourceRoot))) {
  17062. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  17063. // many users. We can help them out when they expect file:// URIs to
  17064. // behave like it would if they were running a local HTTP server. See
  17065. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  17066. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  17067. if (url.scheme == "file"
  17068. && this._sources.has(fileUriAbsPath)) {
  17069. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  17070. }
  17071. if ((!url.path || url.path == "/")
  17072. && this._sources.has("/" + relativeSource)) {
  17073. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  17074. }
  17075. }
  17076. // This function is used recursively from
  17077. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  17078. // don't want to throw if we can't find the source - we just want to
  17079. // return null, so we provide a flag to exit gracefully.
  17080. if (nullOnMissing) {
  17081. return null;
  17082. }
  17083. else {
  17084. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  17085. }
  17086. };
  17087. /**
  17088. * Returns the generated line and column information for the original source,
  17089. * line, and column positions provided. The only argument is an object with
  17090. * the following properties:
  17091. *
  17092. * - source: The filename of the original source.
  17093. * - line: The line number in the original source. The line number
  17094. * is 1-based.
  17095. * - column: The column number in the original source. The column
  17096. * number is 0-based.
  17097. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  17098. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  17099. * closest element that is smaller than or greater than the one we are
  17100. * searching for, respectively, if the exact element cannot be found.
  17101. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  17102. *
  17103. * and an object is returned with the following properties:
  17104. *
  17105. * - line: The line number in the generated source, or null. The
  17106. * line number is 1-based.
  17107. * - column: The column number in the generated source, or null.
  17108. * The column number is 0-based.
  17109. */
  17110. BasicSourceMapConsumer.prototype.generatedPositionFor =
  17111. function SourceMapConsumer_generatedPositionFor(aArgs) {
  17112. var source = util.getArg(aArgs, 'source');
  17113. source = this._findSourceIndex(source);
  17114. if (source < 0) {
  17115. return {
  17116. line: null,
  17117. column: null,
  17118. lastColumn: null
  17119. };
  17120. }
  17121. var needle = {
  17122. source: source,
  17123. originalLine: util.getArg(aArgs, 'line'),
  17124. originalColumn: util.getArg(aArgs, 'column')
  17125. };
  17126. var index = this._findMapping(
  17127. needle,
  17128. this._originalMappings,
  17129. "originalLine",
  17130. "originalColumn",
  17131. util.compareByOriginalPositions,
  17132. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  17133. );
  17134. if (index >= 0) {
  17135. var mapping = this._originalMappings[index];
  17136. if (mapping.source === needle.source) {
  17137. return {
  17138. line: util.getArg(mapping, 'generatedLine', null),
  17139. column: util.getArg(mapping, 'generatedColumn', null),
  17140. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  17141. };
  17142. }
  17143. }
  17144. return {
  17145. line: null,
  17146. column: null,
  17147. lastColumn: null
  17148. };
  17149. };
  17150. var BasicSourceMapConsumer_1 = BasicSourceMapConsumer;
  17151. /**
  17152. * An IndexedSourceMapConsumer instance represents a parsed source map which
  17153. * we can query for information. It differs from BasicSourceMapConsumer in
  17154. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  17155. * input.
  17156. *
  17157. * The first parameter is a raw source map (either as a JSON string, or already
  17158. * parsed to an object). According to the spec for indexed source maps, they
  17159. * have the following attributes:
  17160. *
  17161. * - version: Which version of the source map spec this map is following.
  17162. * - file: Optional. The generated file this source map is associated with.
  17163. * - sections: A list of section definitions.
  17164. *
  17165. * Each value under the "sections" field has two fields:
  17166. * - offset: The offset into the original specified at which this section
  17167. * begins to apply, defined as an object with a "line" and "column"
  17168. * field.
  17169. * - map: A source map definition. This source map could also be indexed,
  17170. * but doesn't have to be.
  17171. *
  17172. * Instead of the "map" field, it's also possible to have a "url" field
  17173. * specifying a URL to retrieve a source map from, but that's currently
  17174. * unsupported.
  17175. *
  17176. * Here's an example source map, taken from the source map spec[0], but
  17177. * modified to omit a section which uses the "url" field.
  17178. *
  17179. * {
  17180. * version : 3,
  17181. * file: "app.js",
  17182. * sections: [{
  17183. * offset: {line:100, column:10},
  17184. * map: {
  17185. * version : 3,
  17186. * file: "section.js",
  17187. * sources: ["foo.js", "bar.js"],
  17188. * names: ["src", "maps", "are", "fun"],
  17189. * mappings: "AAAA,E;;ABCDE;"
  17190. * }
  17191. * }],
  17192. * }
  17193. *
  17194. * The second parameter, if given, is a string whose value is the URL
  17195. * at which the source map was found. This URL is used to compute the
  17196. * sources array.
  17197. *
  17198. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  17199. */
  17200. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  17201. var sourceMap = aSourceMap;
  17202. if (typeof aSourceMap === 'string') {
  17203. sourceMap = util.parseSourceMapInput(aSourceMap);
  17204. }
  17205. var version = util.getArg(sourceMap, 'version');
  17206. var sections = util.getArg(sourceMap, 'sections');
  17207. if (version != this._version) {
  17208. throw new Error('Unsupported version: ' + version);
  17209. }
  17210. this._sources = new ArraySet$2();
  17211. this._names = new ArraySet$2();
  17212. var lastOffset = {
  17213. line: -1,
  17214. column: 0
  17215. };
  17216. this._sections = sections.map(function (s) {
  17217. if (s.url) {
  17218. // The url field will require support for asynchronicity.
  17219. // See https://github.com/mozilla/source-map/issues/16
  17220. throw new Error('Support for url field in sections not implemented.');
  17221. }
  17222. var offset = util.getArg(s, 'offset');
  17223. var offsetLine = util.getArg(offset, 'line');
  17224. var offsetColumn = util.getArg(offset, 'column');
  17225. if (offsetLine < lastOffset.line ||
  17226. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  17227. throw new Error('Section offsets must be ordered and non-overlapping.');
  17228. }
  17229. lastOffset = offset;
  17230. return {
  17231. generatedOffset: {
  17232. // The offset fields are 0-based, but we use 1-based indices when
  17233. // encoding/decoding from VLQ.
  17234. generatedLine: offsetLine + 1,
  17235. generatedColumn: offsetColumn + 1
  17236. },
  17237. consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
  17238. }
  17239. });
  17240. }
  17241. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  17242. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
  17243. /**
  17244. * The version of the source mapping spec that we are consuming.
  17245. */
  17246. IndexedSourceMapConsumer.prototype._version = 3;
  17247. /**
  17248. * The list of original sources.
  17249. */
  17250. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  17251. get: function () {
  17252. var sources = [];
  17253. for (var i = 0; i < this._sections.length; i++) {
  17254. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  17255. sources.push(this._sections[i].consumer.sources[j]);
  17256. }
  17257. }
  17258. return sources;
  17259. }
  17260. });
  17261. /**
  17262. * Returns the original source, line, and column information for the generated
  17263. * source's line and column positions provided. The only argument is an object
  17264. * with the following properties:
  17265. *
  17266. * - line: The line number in the generated source. The line number
  17267. * is 1-based.
  17268. * - column: The column number in the generated source. The column
  17269. * number is 0-based.
  17270. *
  17271. * and an object is returned with the following properties:
  17272. *
  17273. * - source: The original source file, or null.
  17274. * - line: The line number in the original source, or null. The
  17275. * line number is 1-based.
  17276. * - column: The column number in the original source, or null. The
  17277. * column number is 0-based.
  17278. * - name: The original identifier, or null.
  17279. */
  17280. IndexedSourceMapConsumer.prototype.originalPositionFor =
  17281. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  17282. var needle = {
  17283. generatedLine: util.getArg(aArgs, 'line'),
  17284. generatedColumn: util.getArg(aArgs, 'column')
  17285. };
  17286. // Find the section containing the generated position we're trying to map
  17287. // to an original position.
  17288. var sectionIndex = binarySearch.search(needle, this._sections,
  17289. function(needle, section) {
  17290. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  17291. if (cmp) {
  17292. return cmp;
  17293. }
  17294. return (needle.generatedColumn -
  17295. section.generatedOffset.generatedColumn);
  17296. });
  17297. var section = this._sections[sectionIndex];
  17298. if (!section) {
  17299. return {
  17300. source: null,
  17301. line: null,
  17302. column: null,
  17303. name: null
  17304. };
  17305. }
  17306. return section.consumer.originalPositionFor({
  17307. line: needle.generatedLine -
  17308. (section.generatedOffset.generatedLine - 1),
  17309. column: needle.generatedColumn -
  17310. (section.generatedOffset.generatedLine === needle.generatedLine
  17311. ? section.generatedOffset.generatedColumn - 1
  17312. : 0),
  17313. bias: aArgs.bias
  17314. });
  17315. };
  17316. /**
  17317. * Return true if we have the source content for every source in the source
  17318. * map, false otherwise.
  17319. */
  17320. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  17321. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  17322. return this._sections.every(function (s) {
  17323. return s.consumer.hasContentsOfAllSources();
  17324. });
  17325. };
  17326. /**
  17327. * Returns the original source content. The only argument is the url of the
  17328. * original source file. Returns null if no original source content is
  17329. * available.
  17330. */
  17331. IndexedSourceMapConsumer.prototype.sourceContentFor =
  17332. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  17333. for (var i = 0; i < this._sections.length; i++) {
  17334. var section = this._sections[i];
  17335. var content = section.consumer.sourceContentFor(aSource, true);
  17336. if (content) {
  17337. return content;
  17338. }
  17339. }
  17340. if (nullOnMissing) {
  17341. return null;
  17342. }
  17343. else {
  17344. throw new Error('"' + aSource + '" is not in the SourceMap.');
  17345. }
  17346. };
  17347. /**
  17348. * Returns the generated line and column information for the original source,
  17349. * line, and column positions provided. The only argument is an object with
  17350. * the following properties:
  17351. *
  17352. * - source: The filename of the original source.
  17353. * - line: The line number in the original source. The line number
  17354. * is 1-based.
  17355. * - column: The column number in the original source. The column
  17356. * number is 0-based.
  17357. *
  17358. * and an object is returned with the following properties:
  17359. *
  17360. * - line: The line number in the generated source, or null. The
  17361. * line number is 1-based.
  17362. * - column: The column number in the generated source, or null.
  17363. * The column number is 0-based.
  17364. */
  17365. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  17366. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  17367. for (var i = 0; i < this._sections.length; i++) {
  17368. var section = this._sections[i];
  17369. // Only consider this section if the requested source is in the list of
  17370. // sources of the consumer.
  17371. if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
  17372. continue;
  17373. }
  17374. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  17375. if (generatedPosition) {
  17376. var ret = {
  17377. line: generatedPosition.line +
  17378. (section.generatedOffset.generatedLine - 1),
  17379. column: generatedPosition.column +
  17380. (section.generatedOffset.generatedLine === generatedPosition.line
  17381. ? section.generatedOffset.generatedColumn - 1
  17382. : 0)
  17383. };
  17384. return ret;
  17385. }
  17386. }
  17387. return {
  17388. line: null,
  17389. column: null
  17390. };
  17391. };
  17392. /**
  17393. * Parse the mappings in a string in to a data structure which we can easily
  17394. * query (the ordered arrays in the `this.__generatedMappings` and
  17395. * `this.__originalMappings` properties).
  17396. */
  17397. IndexedSourceMapConsumer.prototype._parseMappings =
  17398. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  17399. this.__generatedMappings = [];
  17400. this.__originalMappings = [];
  17401. for (var i = 0; i < this._sections.length; i++) {
  17402. var section = this._sections[i];
  17403. var sectionMappings = section.consumer._generatedMappings;
  17404. for (var j = 0; j < sectionMappings.length; j++) {
  17405. var mapping = sectionMappings[j];
  17406. var source = section.consumer._sources.at(mapping.source);
  17407. source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  17408. this._sources.add(source);
  17409. source = this._sources.indexOf(source);
  17410. var name = null;
  17411. if (mapping.name) {
  17412. name = section.consumer._names.at(mapping.name);
  17413. this._names.add(name);
  17414. name = this._names.indexOf(name);
  17415. }
  17416. // The mappings coming from the consumer for the section have
  17417. // generated positions relative to the start of the section, so we
  17418. // need to offset them to be relative to the start of the concatenated
  17419. // generated file.
  17420. var adjustedMapping = {
  17421. source: source,
  17422. generatedLine: mapping.generatedLine +
  17423. (section.generatedOffset.generatedLine - 1),
  17424. generatedColumn: mapping.generatedColumn +
  17425. (section.generatedOffset.generatedLine === mapping.generatedLine
  17426. ? section.generatedOffset.generatedColumn - 1
  17427. : 0),
  17428. originalLine: mapping.originalLine,
  17429. originalColumn: mapping.originalColumn,
  17430. name: name
  17431. };
  17432. this.__generatedMappings.push(adjustedMapping);
  17433. if (typeof adjustedMapping.originalLine === 'number') {
  17434. this.__originalMappings.push(adjustedMapping);
  17435. }
  17436. }
  17437. }
  17438. quickSort$1(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
  17439. quickSort$1(this.__originalMappings, util.compareByOriginalPositions);
  17440. };
  17441. var IndexedSourceMapConsumer_1 = IndexedSourceMapConsumer;
  17442. var sourceMapConsumer = {
  17443. SourceMapConsumer: SourceMapConsumer_1,
  17444. BasicSourceMapConsumer: BasicSourceMapConsumer_1,
  17445. IndexedSourceMapConsumer: IndexedSourceMapConsumer_1
  17446. };
  17447. /* -*- Mode: js; js-indent-level: 2; -*- */
  17448. /*
  17449. * Copyright 2011 Mozilla Foundation and contributors
  17450. * Licensed under the New BSD license. See LICENSE or:
  17451. * http://opensource.org/licenses/BSD-3-Clause
  17452. */
  17453. var SourceMapGenerator$1 = sourceMapGenerator.SourceMapGenerator;
  17454. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  17455. // operating systems these days (capturing the result).
  17456. var REGEX_NEWLINE = /(\r?\n)/;
  17457. // Newline character code for charCodeAt() comparisons
  17458. var NEWLINE_CODE = 10;
  17459. // Private symbol for identifying `SourceNode`s when multiple versions of
  17460. // the source-map library are loaded. This MUST NOT CHANGE across
  17461. // versions!
  17462. var isSourceNode = "$$$isSourceNode$$$";
  17463. /**
  17464. * SourceNodes provide a way to abstract over interpolating/concatenating
  17465. * snippets of generated JavaScript source code while maintaining the line and
  17466. * column information associated with the original source code.
  17467. *
  17468. * @param aLine The original line number.
  17469. * @param aColumn The original column number.
  17470. * @param aSource The original source's filename.
  17471. * @param aChunks Optional. An array of strings which are snippets of
  17472. * generated JS, or other SourceNodes.
  17473. * @param aName The original identifier.
  17474. */
  17475. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  17476. this.children = [];
  17477. this.sourceContents = {};
  17478. this.line = aLine == null ? null : aLine;
  17479. this.column = aColumn == null ? null : aColumn;
  17480. this.source = aSource == null ? null : aSource;
  17481. this.name = aName == null ? null : aName;
  17482. this[isSourceNode] = true;
  17483. if (aChunks != null) this.add(aChunks);
  17484. }
  17485. /**
  17486. * Creates a SourceNode from generated code and a SourceMapConsumer.
  17487. *
  17488. * @param aGeneratedCode The generated code
  17489. * @param aSourceMapConsumer The SourceMap for the generated code
  17490. * @param aRelativePath Optional. The path that relative sources in the
  17491. * SourceMapConsumer should be relative to.
  17492. */
  17493. SourceNode.fromStringWithSourceMap =
  17494. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  17495. // The SourceNode we want to fill with the generated code
  17496. // and the SourceMap
  17497. var node = new SourceNode();
  17498. // All even indices of this array are one line of the generated code,
  17499. // while all odd indices are the newlines between two adjacent lines
  17500. // (since `REGEX_NEWLINE` captures its match).
  17501. // Processed fragments are accessed by calling `shiftNextLine`.
  17502. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  17503. var remainingLinesIndex = 0;
  17504. var shiftNextLine = function() {
  17505. var lineContents = getNextLine();
  17506. // The last line of a file might not have a newline.
  17507. var newLine = getNextLine() || "";
  17508. return lineContents + newLine;
  17509. function getNextLine() {
  17510. return remainingLinesIndex < remainingLines.length ?
  17511. remainingLines[remainingLinesIndex++] : undefined;
  17512. }
  17513. };
  17514. // We need to remember the position of "remainingLines"
  17515. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  17516. // The generate SourceNodes we need a code range.
  17517. // To extract it current and last mapping is used.
  17518. // Here we store the last mapping.
  17519. var lastMapping = null;
  17520. aSourceMapConsumer.eachMapping(function (mapping) {
  17521. if (lastMapping !== null) {
  17522. // We add the code from "lastMapping" to "mapping":
  17523. // First check if there is a new line in between.
  17524. if (lastGeneratedLine < mapping.generatedLine) {
  17525. // Associate first line with "lastMapping"
  17526. addMappingWithCode(lastMapping, shiftNextLine());
  17527. lastGeneratedLine++;
  17528. lastGeneratedColumn = 0;
  17529. // The remaining code is added without mapping
  17530. } else {
  17531. // There is no new line in between.
  17532. // Associate the code between "lastGeneratedColumn" and
  17533. // "mapping.generatedColumn" with "lastMapping"
  17534. var nextLine = remainingLines[remainingLinesIndex] || '';
  17535. var code = nextLine.substr(0, mapping.generatedColumn -
  17536. lastGeneratedColumn);
  17537. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  17538. lastGeneratedColumn);
  17539. lastGeneratedColumn = mapping.generatedColumn;
  17540. addMappingWithCode(lastMapping, code);
  17541. // No more remaining code, continue
  17542. lastMapping = mapping;
  17543. return;
  17544. }
  17545. }
  17546. // We add the generated code until the first mapping
  17547. // to the SourceNode without any mapping.
  17548. // Each line is added as separate string.
  17549. while (lastGeneratedLine < mapping.generatedLine) {
  17550. node.add(shiftNextLine());
  17551. lastGeneratedLine++;
  17552. }
  17553. if (lastGeneratedColumn < mapping.generatedColumn) {
  17554. var nextLine = remainingLines[remainingLinesIndex] || '';
  17555. node.add(nextLine.substr(0, mapping.generatedColumn));
  17556. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  17557. lastGeneratedColumn = mapping.generatedColumn;
  17558. }
  17559. lastMapping = mapping;
  17560. }, this);
  17561. // We have processed all mappings.
  17562. if (remainingLinesIndex < remainingLines.length) {
  17563. if (lastMapping) {
  17564. // Associate the remaining code in the current line with "lastMapping"
  17565. addMappingWithCode(lastMapping, shiftNextLine());
  17566. }
  17567. // and add the remaining lines without any mapping
  17568. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  17569. }
  17570. // Copy sourcesContent into SourceNode
  17571. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  17572. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  17573. if (content != null) {
  17574. if (aRelativePath != null) {
  17575. sourceFile = util.join(aRelativePath, sourceFile);
  17576. }
  17577. node.setSourceContent(sourceFile, content);
  17578. }
  17579. });
  17580. return node;
  17581. function addMappingWithCode(mapping, code) {
  17582. if (mapping === null || mapping.source === undefined) {
  17583. node.add(code);
  17584. } else {
  17585. var source = aRelativePath
  17586. ? util.join(aRelativePath, mapping.source)
  17587. : mapping.source;
  17588. node.add(new SourceNode(mapping.originalLine,
  17589. mapping.originalColumn,
  17590. source,
  17591. code,
  17592. mapping.name));
  17593. }
  17594. }
  17595. };
  17596. /**
  17597. * Add a chunk of generated JS to this source node.
  17598. *
  17599. * @param aChunk A string snippet of generated JS code, another instance of
  17600. * SourceNode, or an array where each member is one of those things.
  17601. */
  17602. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  17603. if (Array.isArray(aChunk)) {
  17604. aChunk.forEach(function (chunk) {
  17605. this.add(chunk);
  17606. }, this);
  17607. }
  17608. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  17609. if (aChunk) {
  17610. this.children.push(aChunk);
  17611. }
  17612. }
  17613. else {
  17614. throw new TypeError(
  17615. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  17616. );
  17617. }
  17618. return this;
  17619. };
  17620. /**
  17621. * Add a chunk of generated JS to the beginning of this source node.
  17622. *
  17623. * @param aChunk A string snippet of generated JS code, another instance of
  17624. * SourceNode, or an array where each member is one of those things.
  17625. */
  17626. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  17627. if (Array.isArray(aChunk)) {
  17628. for (var i = aChunk.length-1; i >= 0; i--) {
  17629. this.prepend(aChunk[i]);
  17630. }
  17631. }
  17632. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  17633. this.children.unshift(aChunk);
  17634. }
  17635. else {
  17636. throw new TypeError(
  17637. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  17638. );
  17639. }
  17640. return this;
  17641. };
  17642. /**
  17643. * Walk over the tree of JS snippets in this node and its children. The
  17644. * walking function is called once for each snippet of JS and is passed that
  17645. * snippet and the its original associated source's line/column location.
  17646. *
  17647. * @param aFn The traversal function.
  17648. */
  17649. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  17650. var chunk;
  17651. for (var i = 0, len = this.children.length; i < len; i++) {
  17652. chunk = this.children[i];
  17653. if (chunk[isSourceNode]) {
  17654. chunk.walk(aFn);
  17655. }
  17656. else {
  17657. if (chunk !== '') {
  17658. aFn(chunk, { source: this.source,
  17659. line: this.line,
  17660. column: this.column,
  17661. name: this.name });
  17662. }
  17663. }
  17664. }
  17665. };
  17666. /**
  17667. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  17668. * each of `this.children`.
  17669. *
  17670. * @param aSep The separator.
  17671. */
  17672. SourceNode.prototype.join = function SourceNode_join(aSep) {
  17673. var newChildren;
  17674. var i;
  17675. var len = this.children.length;
  17676. if (len > 0) {
  17677. newChildren = [];
  17678. for (i = 0; i < len-1; i++) {
  17679. newChildren.push(this.children[i]);
  17680. newChildren.push(aSep);
  17681. }
  17682. newChildren.push(this.children[i]);
  17683. this.children = newChildren;
  17684. }
  17685. return this;
  17686. };
  17687. /**
  17688. * Call String.prototype.replace on the very right-most source snippet. Useful
  17689. * for trimming whitespace from the end of a source node, etc.
  17690. *
  17691. * @param aPattern The pattern to replace.
  17692. * @param aReplacement The thing to replace the pattern with.
  17693. */
  17694. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  17695. var lastChild = this.children[this.children.length - 1];
  17696. if (lastChild[isSourceNode]) {
  17697. lastChild.replaceRight(aPattern, aReplacement);
  17698. }
  17699. else if (typeof lastChild === 'string') {
  17700. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  17701. }
  17702. else {
  17703. this.children.push(''.replace(aPattern, aReplacement));
  17704. }
  17705. return this;
  17706. };
  17707. /**
  17708. * Set the source content for a source file. This will be added to the SourceMapGenerator
  17709. * in the sourcesContent field.
  17710. *
  17711. * @param aSourceFile The filename of the source file
  17712. * @param aSourceContent The content of the source file
  17713. */
  17714. SourceNode.prototype.setSourceContent =
  17715. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  17716. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  17717. };
  17718. /**
  17719. * Walk over the tree of SourceNodes. The walking function is called for each
  17720. * source file content and is passed the filename and source content.
  17721. *
  17722. * @param aFn The traversal function.
  17723. */
  17724. SourceNode.prototype.walkSourceContents =
  17725. function SourceNode_walkSourceContents(aFn) {
  17726. for (var i = 0, len = this.children.length; i < len; i++) {
  17727. if (this.children[i][isSourceNode]) {
  17728. this.children[i].walkSourceContents(aFn);
  17729. }
  17730. }
  17731. var sources = Object.keys(this.sourceContents);
  17732. for (var i = 0, len = sources.length; i < len; i++) {
  17733. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  17734. }
  17735. };
  17736. /**
  17737. * Return the string representation of this source node. Walks over the tree
  17738. * and concatenates all the various snippets together to one string.
  17739. */
  17740. SourceNode.prototype.toString = function SourceNode_toString() {
  17741. var str = "";
  17742. this.walk(function (chunk) {
  17743. str += chunk;
  17744. });
  17745. return str;
  17746. };
  17747. /**
  17748. * Returns the string representation of this source node along with a source
  17749. * map.
  17750. */
  17751. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  17752. var generated = {
  17753. code: "",
  17754. line: 1,
  17755. column: 0
  17756. };
  17757. var map = new SourceMapGenerator$1(aArgs);
  17758. var sourceMappingActive = false;
  17759. var lastOriginalSource = null;
  17760. var lastOriginalLine = null;
  17761. var lastOriginalColumn = null;
  17762. var lastOriginalName = null;
  17763. this.walk(function (chunk, original) {
  17764. generated.code += chunk;
  17765. if (original.source !== null
  17766. && original.line !== null
  17767. && original.column !== null) {
  17768. if(lastOriginalSource !== original.source
  17769. || lastOriginalLine !== original.line
  17770. || lastOriginalColumn !== original.column
  17771. || lastOriginalName !== original.name) {
  17772. map.addMapping({
  17773. source: original.source,
  17774. original: {
  17775. line: original.line,
  17776. column: original.column
  17777. },
  17778. generated: {
  17779. line: generated.line,
  17780. column: generated.column
  17781. },
  17782. name: original.name
  17783. });
  17784. }
  17785. lastOriginalSource = original.source;
  17786. lastOriginalLine = original.line;
  17787. lastOriginalColumn = original.column;
  17788. lastOriginalName = original.name;
  17789. sourceMappingActive = true;
  17790. } else if (sourceMappingActive) {
  17791. map.addMapping({
  17792. generated: {
  17793. line: generated.line,
  17794. column: generated.column
  17795. }
  17796. });
  17797. lastOriginalSource = null;
  17798. sourceMappingActive = false;
  17799. }
  17800. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  17801. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  17802. generated.line++;
  17803. generated.column = 0;
  17804. // Mappings end at eol
  17805. if (idx + 1 === length) {
  17806. lastOriginalSource = null;
  17807. sourceMappingActive = false;
  17808. } else if (sourceMappingActive) {
  17809. map.addMapping({
  17810. source: original.source,
  17811. original: {
  17812. line: original.line,
  17813. column: original.column
  17814. },
  17815. generated: {
  17816. line: generated.line,
  17817. column: generated.column
  17818. },
  17819. name: original.name
  17820. });
  17821. }
  17822. } else {
  17823. generated.column++;
  17824. }
  17825. }
  17826. });
  17827. this.walkSourceContents(function (sourceFile, sourceContent) {
  17828. map.setSourceContent(sourceFile, sourceContent);
  17829. });
  17830. return { code: generated.code, map: map };
  17831. };
  17832. var SourceNode_1 = SourceNode;
  17833. var sourceNode = {
  17834. SourceNode: SourceNode_1
  17835. };
  17836. /*
  17837. * Copyright 2009-2011 Mozilla Foundation and contributors
  17838. * Licensed under the New BSD license. See LICENSE.txt or:
  17839. * http://opensource.org/licenses/BSD-3-Clause
  17840. */
  17841. var SourceMapGenerator$2 = sourceMapGenerator.SourceMapGenerator;
  17842. var SourceMapConsumer$1 = sourceMapConsumer.SourceMapConsumer;
  17843. var SourceNode$1 = sourceNode.SourceNode;
  17844. var sourceMap = {
  17845. SourceMapGenerator: SourceMapGenerator$2,
  17846. SourceMapConsumer: SourceMapConsumer$1,
  17847. SourceNode: SourceNode$1
  17848. };
  17849. const PURE_ANNOTATION = `/*#__PURE__*/`;
  17850. 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 }) {
  17851. const context = {
  17852. mode,
  17853. prefixIdentifiers,
  17854. sourceMap,
  17855. filename,
  17856. scopeId,
  17857. optimizeImports,
  17858. runtimeGlobalName,
  17859. runtimeModuleName,
  17860. ssrRuntimeModuleName,
  17861. ssr,
  17862. isTS,
  17863. inSSR,
  17864. source: ast.loc.source,
  17865. code: ``,
  17866. column: 1,
  17867. line: 1,
  17868. offset: 0,
  17869. indentLevel: 0,
  17870. pure: false,
  17871. map: undefined,
  17872. helper(key) {
  17873. return `_${helperNameMap[key]}`;
  17874. },
  17875. push(code, node) {
  17876. context.code += code;
  17877. if (context.map) {
  17878. if (node) {
  17879. let name;
  17880. if (node.type === 4 /* SIMPLE_EXPRESSION */ && !node.isStatic) {
  17881. const content = node.content.replace(/^_ctx\./, '');
  17882. if (content !== node.content && isSimpleIdentifier(content)) {
  17883. name = content;
  17884. }
  17885. }
  17886. addMapping(node.loc.start, name);
  17887. }
  17888. advancePositionWithMutation(context, code);
  17889. if (node && node.loc !== locStub) {
  17890. addMapping(node.loc.end);
  17891. }
  17892. }
  17893. },
  17894. indent() {
  17895. newline(++context.indentLevel);
  17896. },
  17897. deindent(withoutNewLine = false) {
  17898. if (withoutNewLine) {
  17899. --context.indentLevel;
  17900. }
  17901. else {
  17902. newline(--context.indentLevel);
  17903. }
  17904. },
  17905. newline() {
  17906. newline(context.indentLevel);
  17907. }
  17908. };
  17909. function newline(n) {
  17910. context.push('\n' + ` `.repeat(n));
  17911. }
  17912. function addMapping(loc, name) {
  17913. context.map.addMapping({
  17914. name,
  17915. source: context.filename,
  17916. original: {
  17917. line: loc.line,
  17918. column: loc.column - 1 // source-map column is 0 based
  17919. },
  17920. generated: {
  17921. line: context.line,
  17922. column: context.column - 1
  17923. }
  17924. });
  17925. }
  17926. if (sourceMap) {
  17927. // lazy require source-map implementation, only in non-browser builds
  17928. context.map = new SourceMapGenerator$2();
  17929. context.map.setSourceContent(filename, context.source);
  17930. }
  17931. return context;
  17932. }
  17933. function generate(ast, options = {}) {
  17934. const context = createCodegenContext(ast, options);
  17935. if (options.onContextCreated)
  17936. options.onContextCreated(context);
  17937. const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
  17938. const hasHelpers = ast.helpers.length > 0;
  17939. const useWithBlock = !prefixIdentifiers && mode !== 'module';
  17940. const genScopeId = scopeId != null && mode === 'module';
  17941. const isSetupInlined = !!options.inline;
  17942. // preambles
  17943. // in setup() inline mode, the preamble is generated in a sub context
  17944. // and returned separately.
  17945. const preambleContext = isSetupInlined
  17946. ? createCodegenContext(ast, options)
  17947. : context;
  17948. if (mode === 'module') {
  17949. genModulePreamble(ast, preambleContext, genScopeId, isSetupInlined);
  17950. }
  17951. else {
  17952. genFunctionPreamble(ast, preambleContext);
  17953. }
  17954. // enter render function
  17955. const functionName = ssr ? `ssrRender` : `render`;
  17956. const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
  17957. if (options.bindingMetadata && !options.inline) {
  17958. // binding optimization args
  17959. args.push('$props', '$setup', '$data', '$options');
  17960. }
  17961. const signature = options.isTS
  17962. ? args.map(arg => `${arg}: any`).join(',')
  17963. : args.join(', ');
  17964. if (isSetupInlined) {
  17965. push(`(${signature}) => {`);
  17966. }
  17967. else {
  17968. push(`function ${functionName}(${signature}) {`);
  17969. }
  17970. indent();
  17971. if (useWithBlock) {
  17972. push(`with (_ctx) {`);
  17973. indent();
  17974. // function mode const declarations should be inside with block
  17975. // also they should be renamed to avoid collision with user properties
  17976. if (hasHelpers) {
  17977. push(`const { ${ast.helpers
  17978. .map(s => `${helperNameMap[s]}: _${helperNameMap[s]}`)
  17979. .join(', ')} } = _Vue`);
  17980. push(`\n`);
  17981. newline();
  17982. }
  17983. }
  17984. // generate asset resolution statements
  17985. if (ast.components.length) {
  17986. genAssets(ast.components, 'component', context);
  17987. if (ast.directives.length || ast.temps > 0) {
  17988. newline();
  17989. }
  17990. }
  17991. if (ast.directives.length) {
  17992. genAssets(ast.directives, 'directive', context);
  17993. if (ast.temps > 0) {
  17994. newline();
  17995. }
  17996. }
  17997. if (ast.temps > 0) {
  17998. push(`let `);
  17999. for (let i = 0; i < ast.temps; i++) {
  18000. push(`${i > 0 ? `, ` : ``}_temp${i}`);
  18001. }
  18002. }
  18003. if (ast.components.length || ast.directives.length || ast.temps) {
  18004. push(`\n`);
  18005. newline();
  18006. }
  18007. // generate the VNode tree expression
  18008. if (!ssr) {
  18009. push(`return `);
  18010. }
  18011. if (ast.codegenNode) {
  18012. genNode(ast.codegenNode, context);
  18013. }
  18014. else {
  18015. push(`null`);
  18016. }
  18017. if (useWithBlock) {
  18018. deindent();
  18019. push(`}`);
  18020. }
  18021. deindent();
  18022. push(`}`);
  18023. return {
  18024. ast,
  18025. code: context.code,
  18026. preamble: isSetupInlined ? preambleContext.code : ``,
  18027. // SourceMapGenerator does have toJSON() method but it's not in the types
  18028. map: context.map ? context.map.toJSON() : undefined
  18029. };
  18030. }
  18031. function genFunctionPreamble(ast, context) {
  18032. const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName, ssrRuntimeModuleName } = context;
  18033. const VueBinding = ssr
  18034. ? `require(${JSON.stringify(runtimeModuleName)})`
  18035. : runtimeGlobalName;
  18036. const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
  18037. // Generate const declaration for helpers
  18038. // In prefix mode, we place the const declaration at top so it's done
  18039. // only once; But if we not prefixing, we place the declaration inside the
  18040. // with block so it doesn't incur the `in` check cost for every helper access.
  18041. if (ast.helpers.length > 0) {
  18042. if (prefixIdentifiers) {
  18043. push(`const { ${ast.helpers.map(aliasHelper).join(', ')} } = ${VueBinding}\n`);
  18044. }
  18045. else {
  18046. // "with" mode.
  18047. // save Vue in a separate variable to avoid collision
  18048. push(`const _Vue = ${VueBinding}\n`);
  18049. // in "with" mode, helpers are declared inside the with block to avoid
  18050. // has check cost, but hoists are lifted out of the function - we need
  18051. // to provide the helper here.
  18052. if (ast.hoists.length) {
  18053. const staticHelpers = [
  18054. CREATE_VNODE,
  18055. CREATE_ELEMENT_VNODE,
  18056. CREATE_COMMENT,
  18057. CREATE_TEXT,
  18058. CREATE_STATIC
  18059. ]
  18060. .filter(helper => ast.helpers.includes(helper))
  18061. .map(aliasHelper)
  18062. .join(', ');
  18063. push(`const { ${staticHelpers} } = _Vue\n`);
  18064. }
  18065. }
  18066. }
  18067. // generate variables for ssr helpers
  18068. if (ast.ssrHelpers && ast.ssrHelpers.length) {
  18069. // ssr guarantees prefixIdentifier: true
  18070. push(`const { ${ast.ssrHelpers
  18071. .map(aliasHelper)
  18072. .join(', ')} } = require("${ssrRuntimeModuleName}")\n`);
  18073. }
  18074. genHoists(ast.hoists, context);
  18075. newline();
  18076. push(`return `);
  18077. }
  18078. function genModulePreamble(ast, context, genScopeId, inline) {
  18079. const { push, newline, optimizeImports, runtimeModuleName, ssrRuntimeModuleName } = context;
  18080. if (genScopeId && ast.hoists.length) {
  18081. ast.helpers.push(PUSH_SCOPE_ID, POP_SCOPE_ID);
  18082. }
  18083. // generate import statements for helpers
  18084. if (ast.helpers.length) {
  18085. if (optimizeImports) {
  18086. // when bundled with webpack with code-split, calling an import binding
  18087. // as a function leads to it being wrapped with `Object(a.b)` or `(0,a.b)`,
  18088. // incurring both payload size increase and potential perf overhead.
  18089. // therefore we assign the imports to variables (which is a constant ~50b
  18090. // cost per-component instead of scaling with template size)
  18091. push(`import { ${ast.helpers
  18092. .map(s => helperNameMap[s])
  18093. .join(', ')} } from ${JSON.stringify(runtimeModuleName)}\n`);
  18094. push(`\n// Binding optimization for webpack code-split\nconst ${ast.helpers
  18095. .map(s => `_${helperNameMap[s]} = ${helperNameMap[s]}`)
  18096. .join(', ')}\n`);
  18097. }
  18098. else {
  18099. push(`import { ${ast.helpers
  18100. .map(s => `${helperNameMap[s]} as _${helperNameMap[s]}`)
  18101. .join(', ')} } from ${JSON.stringify(runtimeModuleName)}\n`);
  18102. }
  18103. }
  18104. if (ast.ssrHelpers && ast.ssrHelpers.length) {
  18105. push(`import { ${ast.ssrHelpers
  18106. .map(s => `${helperNameMap[s]} as _${helperNameMap[s]}`)
  18107. .join(', ')} } from "${ssrRuntimeModuleName}"\n`);
  18108. }
  18109. if (ast.imports.length) {
  18110. genImports(ast.imports, context);
  18111. newline();
  18112. }
  18113. genHoists(ast.hoists, context);
  18114. newline();
  18115. if (!inline) {
  18116. push(`export `);
  18117. }
  18118. }
  18119. function genAssets(assets, type, { helper, push, newline, isTS }) {
  18120. const resolver = helper(type === 'component'
  18121. ? RESOLVE_COMPONENT
  18122. : RESOLVE_DIRECTIVE);
  18123. for (let i = 0; i < assets.length; i++) {
  18124. let id = assets[i];
  18125. // potential component implicit self-reference inferred from SFC filename
  18126. const maybeSelfReference = id.endsWith('__self');
  18127. if (maybeSelfReference) {
  18128. id = id.slice(0, -6);
  18129. }
  18130. push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}`);
  18131. if (i < assets.length - 1) {
  18132. newline();
  18133. }
  18134. }
  18135. }
  18136. function genHoists(hoists, context) {
  18137. if (!hoists.length) {
  18138. return;
  18139. }
  18140. context.pure = true;
  18141. const { push, newline, helper, scopeId, mode } = context;
  18142. const genScopeId = scopeId != null && mode !== 'function';
  18143. newline();
  18144. // generate inlined withScopeId helper
  18145. if (genScopeId) {
  18146. push(`const _withScopeId = n => (${helper(PUSH_SCOPE_ID)}("${scopeId}"),n=n(),${helper(POP_SCOPE_ID)}(),n)`);
  18147. newline();
  18148. }
  18149. for (let i = 0; i < hoists.length; i++) {
  18150. const exp = hoists[i];
  18151. if (exp) {
  18152. const needScopeIdWrapper = genScopeId && exp.type === 13 /* VNODE_CALL */;
  18153. push(`const _hoisted_${i + 1} = ${needScopeIdWrapper ? `${PURE_ANNOTATION} _withScopeId(() => ` : ``}`);
  18154. genNode(exp, context);
  18155. if (needScopeIdWrapper) {
  18156. push(`)`);
  18157. }
  18158. newline();
  18159. }
  18160. }
  18161. context.pure = false;
  18162. }
  18163. function genImports(importsOptions, context) {
  18164. if (!importsOptions.length) {
  18165. return;
  18166. }
  18167. importsOptions.forEach(imports => {
  18168. context.push(`import `);
  18169. genNode(imports.exp, context);
  18170. context.push(` from '${imports.path}'`);
  18171. context.newline();
  18172. });
  18173. }
  18174. function isText$1(n) {
  18175. return (isString(n) ||
  18176. n.type === 4 /* SIMPLE_EXPRESSION */ ||
  18177. n.type === 2 /* TEXT */ ||
  18178. n.type === 5 /* INTERPOLATION */ ||
  18179. n.type === 8 /* COMPOUND_EXPRESSION */);
  18180. }
  18181. function genNodeListAsArray(nodes, context) {
  18182. const multilines = nodes.length > 3 ||
  18183. (nodes.some(n => isArray(n) || !isText$1(n)));
  18184. context.push(`[`);
  18185. multilines && context.indent();
  18186. genNodeList(nodes, context, multilines);
  18187. multilines && context.deindent();
  18188. context.push(`]`);
  18189. }
  18190. function genNodeList(nodes, context, multilines = false, comma = true) {
  18191. const { push, newline } = context;
  18192. for (let i = 0; i < nodes.length; i++) {
  18193. const node = nodes[i];
  18194. if (isString(node)) {
  18195. push(node);
  18196. }
  18197. else if (isArray(node)) {
  18198. genNodeListAsArray(node, context);
  18199. }
  18200. else {
  18201. genNode(node, context);
  18202. }
  18203. if (i < nodes.length - 1) {
  18204. if (multilines) {
  18205. comma && push(',');
  18206. newline();
  18207. }
  18208. else {
  18209. comma && push(', ');
  18210. }
  18211. }
  18212. }
  18213. }
  18214. function genNode(node, context) {
  18215. if (isString(node)) {
  18216. context.push(node);
  18217. return;
  18218. }
  18219. if (isSymbol(node)) {
  18220. context.push(context.helper(node));
  18221. return;
  18222. }
  18223. switch (node.type) {
  18224. case 1 /* ELEMENT */:
  18225. case 9 /* IF */:
  18226. case 11 /* FOR */:
  18227. assert$1(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
  18228. `Apply appropriate transforms first.`);
  18229. genNode(node.codegenNode, context);
  18230. break;
  18231. case 2 /* TEXT */:
  18232. genText(node, context);
  18233. break;
  18234. case 4 /* SIMPLE_EXPRESSION */:
  18235. genExpression(node, context);
  18236. break;
  18237. case 5 /* INTERPOLATION */:
  18238. genInterpolation(node, context);
  18239. break;
  18240. case 12 /* TEXT_CALL */:
  18241. genNode(node.codegenNode, context);
  18242. break;
  18243. case 8 /* COMPOUND_EXPRESSION */:
  18244. genCompoundExpression(node, context);
  18245. break;
  18246. case 3 /* COMMENT */:
  18247. genComment(node, context);
  18248. break;
  18249. case 13 /* VNODE_CALL */:
  18250. genVNodeCall(node, context);
  18251. break;
  18252. case 14 /* JS_CALL_EXPRESSION */:
  18253. genCallExpression(node, context);
  18254. break;
  18255. case 15 /* JS_OBJECT_EXPRESSION */:
  18256. genObjectExpression(node, context);
  18257. break;
  18258. case 17 /* JS_ARRAY_EXPRESSION */:
  18259. genArrayExpression(node, context);
  18260. break;
  18261. case 18 /* JS_FUNCTION_EXPRESSION */:
  18262. genFunctionExpression(node, context);
  18263. break;
  18264. case 19 /* JS_CONDITIONAL_EXPRESSION */:
  18265. genConditionalExpression(node, context);
  18266. break;
  18267. case 20 /* JS_CACHE_EXPRESSION */:
  18268. genCacheExpression(node, context);
  18269. break;
  18270. case 21 /* JS_BLOCK_STATEMENT */:
  18271. genNodeList(node.body, context, true, false);
  18272. break;
  18273. // SSR only types
  18274. case 22 /* JS_TEMPLATE_LITERAL */:
  18275. genTemplateLiteral(node, context);
  18276. break;
  18277. case 23 /* JS_IF_STATEMENT */:
  18278. genIfStatement(node, context);
  18279. break;
  18280. case 24 /* JS_ASSIGNMENT_EXPRESSION */:
  18281. genAssignmentExpression(node, context);
  18282. break;
  18283. case 25 /* JS_SEQUENCE_EXPRESSION */:
  18284. genSequenceExpression(node, context);
  18285. break;
  18286. case 26 /* JS_RETURN_STATEMENT */:
  18287. genReturnStatement(node, context);
  18288. break;
  18289. /* istanbul ignore next */
  18290. case 10 /* IF_BRANCH */:
  18291. // noop
  18292. break;
  18293. default:
  18294. {
  18295. assert$1(false, `unhandled codegen node type: ${node.type}`);
  18296. // make sure we exhaust all possible types
  18297. const exhaustiveCheck = node;
  18298. return exhaustiveCheck;
  18299. }
  18300. }
  18301. }
  18302. function genText(node, context) {
  18303. context.push(JSON.stringify(node.content), node);
  18304. }
  18305. function genExpression(node, context) {
  18306. const { content, isStatic } = node;
  18307. context.push(isStatic ? JSON.stringify(content) : content, node);
  18308. }
  18309. function genInterpolation(node, context) {
  18310. const { push, helper, pure } = context;
  18311. if (pure)
  18312. push(PURE_ANNOTATION);
  18313. push(`${helper(TO_DISPLAY_STRING)}(`);
  18314. genNode(node.content, context);
  18315. push(`)`);
  18316. }
  18317. function genCompoundExpression(node, context) {
  18318. for (let i = 0; i < node.children.length; i++) {
  18319. const child = node.children[i];
  18320. if (isString(child)) {
  18321. context.push(child);
  18322. }
  18323. else {
  18324. genNode(child, context);
  18325. }
  18326. }
  18327. }
  18328. function genExpressionAsPropertyKey(node, context) {
  18329. const { push } = context;
  18330. if (node.type === 8 /* COMPOUND_EXPRESSION */) {
  18331. push(`[`);
  18332. genCompoundExpression(node, context);
  18333. push(`]`);
  18334. }
  18335. else if (node.isStatic) {
  18336. // only quote keys if necessary
  18337. const text = isSimpleIdentifier(node.content)
  18338. ? node.content
  18339. : JSON.stringify(node.content);
  18340. push(text, node);
  18341. }
  18342. else {
  18343. push(`[${node.content}]`, node);
  18344. }
  18345. }
  18346. function genComment(node, context) {
  18347. const { push, helper, pure } = context;
  18348. if (pure) {
  18349. push(PURE_ANNOTATION);
  18350. }
  18351. push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
  18352. }
  18353. function genVNodeCall(node, context) {
  18354. const { push, helper, pure } = context;
  18355. const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking, isComponent } = node;
  18356. if (directives) {
  18357. push(helper(WITH_DIRECTIVES) + `(`);
  18358. }
  18359. if (isBlock) {
  18360. push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
  18361. }
  18362. if (pure) {
  18363. push(PURE_ANNOTATION);
  18364. }
  18365. const callHelper = isBlock
  18366. ? getVNodeBlockHelper(context.inSSR, isComponent)
  18367. : getVNodeHelper(context.inSSR, isComponent);
  18368. push(helper(callHelper) + `(`, node);
  18369. genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
  18370. push(`)`);
  18371. if (isBlock) {
  18372. push(`)`);
  18373. }
  18374. if (directives) {
  18375. push(`, `);
  18376. genNode(directives, context);
  18377. push(`)`);
  18378. }
  18379. }
  18380. function genNullableArgs(args) {
  18381. let i = args.length;
  18382. while (i--) {
  18383. if (args[i] != null)
  18384. break;
  18385. }
  18386. return args.slice(0, i + 1).map(arg => arg || `null`);
  18387. }
  18388. // JavaScript
  18389. function genCallExpression(node, context) {
  18390. const { push, helper, pure } = context;
  18391. const callee = isString(node.callee) ? node.callee : helper(node.callee);
  18392. if (pure) {
  18393. push(PURE_ANNOTATION);
  18394. }
  18395. push(callee + `(`, node);
  18396. genNodeList(node.arguments, context);
  18397. push(`)`);
  18398. }
  18399. function genObjectExpression(node, context) {
  18400. const { push, indent, deindent, newline } = context;
  18401. const { properties } = node;
  18402. if (!properties.length) {
  18403. push(`{}`, node);
  18404. return;
  18405. }
  18406. const multilines = properties.length > 1 ||
  18407. (properties.some(p => p.value.type !== 4 /* SIMPLE_EXPRESSION */));
  18408. push(multilines ? `{` : `{ `);
  18409. multilines && indent();
  18410. for (let i = 0; i < properties.length; i++) {
  18411. const { key, value } = properties[i];
  18412. // key
  18413. genExpressionAsPropertyKey(key, context);
  18414. push(`: `);
  18415. // value
  18416. genNode(value, context);
  18417. if (i < properties.length - 1) {
  18418. // will only reach this if it's multilines
  18419. push(`,`);
  18420. newline();
  18421. }
  18422. }
  18423. multilines && deindent();
  18424. push(multilines ? `}` : ` }`);
  18425. }
  18426. function genArrayExpression(node, context) {
  18427. genNodeListAsArray(node.elements, context);
  18428. }
  18429. function genFunctionExpression(node, context) {
  18430. const { push, indent, deindent } = context;
  18431. const { params, returns, body, newline, isSlot } = node;
  18432. if (isSlot) {
  18433. // wrap slot functions with owner context
  18434. push(`_${helperNameMap[WITH_CTX]}(`);
  18435. }
  18436. push(`(`, node);
  18437. if (isArray(params)) {
  18438. genNodeList(params, context);
  18439. }
  18440. else if (params) {
  18441. genNode(params, context);
  18442. }
  18443. push(`) => `);
  18444. if (newline || body) {
  18445. push(`{`);
  18446. indent();
  18447. }
  18448. if (returns) {
  18449. if (newline) {
  18450. push(`return `);
  18451. }
  18452. if (isArray(returns)) {
  18453. genNodeListAsArray(returns, context);
  18454. }
  18455. else {
  18456. genNode(returns, context);
  18457. }
  18458. }
  18459. else if (body) {
  18460. genNode(body, context);
  18461. }
  18462. if (newline || body) {
  18463. deindent();
  18464. push(`}`);
  18465. }
  18466. if (isSlot) {
  18467. push(`)`);
  18468. }
  18469. }
  18470. function genConditionalExpression(node, context) {
  18471. const { test, consequent, alternate, newline: needNewline } = node;
  18472. const { push, indent, deindent, newline } = context;
  18473. if (test.type === 4 /* SIMPLE_EXPRESSION */) {
  18474. const needsParens = !isSimpleIdentifier(test.content);
  18475. needsParens && push(`(`);
  18476. genExpression(test, context);
  18477. needsParens && push(`)`);
  18478. }
  18479. else {
  18480. push(`(`);
  18481. genNode(test, context);
  18482. push(`)`);
  18483. }
  18484. needNewline && indent();
  18485. context.indentLevel++;
  18486. needNewline || push(` `);
  18487. push(`? `);
  18488. genNode(consequent, context);
  18489. context.indentLevel--;
  18490. needNewline && newline();
  18491. needNewline || push(` `);
  18492. push(`: `);
  18493. const isNested = alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */;
  18494. if (!isNested) {
  18495. context.indentLevel++;
  18496. }
  18497. genNode(alternate, context);
  18498. if (!isNested) {
  18499. context.indentLevel--;
  18500. }
  18501. needNewline && deindent(true /* without newline */);
  18502. }
  18503. function genCacheExpression(node, context) {
  18504. const { push, helper, indent, deindent, newline } = context;
  18505. push(`_cache[${node.index}] || (`);
  18506. if (node.isVNode) {
  18507. indent();
  18508. push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
  18509. newline();
  18510. }
  18511. push(`_cache[${node.index}] = `);
  18512. genNode(node.value, context);
  18513. if (node.isVNode) {
  18514. push(`,`);
  18515. newline();
  18516. push(`${helper(SET_BLOCK_TRACKING)}(1),`);
  18517. newline();
  18518. push(`_cache[${node.index}]`);
  18519. deindent();
  18520. }
  18521. push(`)`);
  18522. }
  18523. function genTemplateLiteral(node, context) {
  18524. const { push, indent, deindent } = context;
  18525. push('`');
  18526. const l = node.elements.length;
  18527. const multilines = l > 3;
  18528. for (let i = 0; i < l; i++) {
  18529. const e = node.elements[i];
  18530. if (isString(e)) {
  18531. push(e.replace(/(`|\$|\\)/g, '\\$1'));
  18532. }
  18533. else {
  18534. push('${');
  18535. if (multilines)
  18536. indent();
  18537. genNode(e, context);
  18538. if (multilines)
  18539. deindent();
  18540. push('}');
  18541. }
  18542. }
  18543. push('`');
  18544. }
  18545. function genIfStatement(node, context) {
  18546. const { push, indent, deindent } = context;
  18547. const { test, consequent, alternate } = node;
  18548. push(`if (`);
  18549. genNode(test, context);
  18550. push(`) {`);
  18551. indent();
  18552. genNode(consequent, context);
  18553. deindent();
  18554. push(`}`);
  18555. if (alternate) {
  18556. push(` else `);
  18557. if (alternate.type === 23 /* JS_IF_STATEMENT */) {
  18558. genIfStatement(alternate, context);
  18559. }
  18560. else {
  18561. push(`{`);
  18562. indent();
  18563. genNode(alternate, context);
  18564. deindent();
  18565. push(`}`);
  18566. }
  18567. }
  18568. }
  18569. function genAssignmentExpression(node, context) {
  18570. genNode(node.left, context);
  18571. context.push(` = `);
  18572. genNode(node.right, context);
  18573. }
  18574. function genSequenceExpression(node, context) {
  18575. context.push(`(`);
  18576. genNodeList(node.expressions, context);
  18577. context.push(`)`);
  18578. }
  18579. function genReturnStatement({ returns }, context) {
  18580. context.push(`return `);
  18581. if (isArray(returns)) {
  18582. genNodeListAsArray(returns, context);
  18583. }
  18584. else {
  18585. genNode(returns, context);
  18586. }
  18587. }
  18588. // @ts-check
  18589. /** @typedef { import('estree').BaseNode} BaseNode */
  18590. /** @typedef {{
  18591. skip: () => void;
  18592. remove: () => void;
  18593. replace: (node: BaseNode) => void;
  18594. }} WalkerContext */
  18595. class WalkerBase {
  18596. constructor() {
  18597. /** @type {boolean} */
  18598. this.should_skip = false;
  18599. /** @type {boolean} */
  18600. this.should_remove = false;
  18601. /** @type {BaseNode | null} */
  18602. this.replacement = null;
  18603. /** @type {WalkerContext} */
  18604. this.context = {
  18605. skip: () => (this.should_skip = true),
  18606. remove: () => (this.should_remove = true),
  18607. replace: (node) => (this.replacement = node)
  18608. };
  18609. }
  18610. /**
  18611. *
  18612. * @param {any} parent
  18613. * @param {string} prop
  18614. * @param {number} index
  18615. * @param {BaseNode} node
  18616. */
  18617. replace(parent, prop, index, node) {
  18618. if (parent) {
  18619. if (index !== null) {
  18620. parent[prop][index] = node;
  18621. } else {
  18622. parent[prop] = node;
  18623. }
  18624. }
  18625. }
  18626. /**
  18627. *
  18628. * @param {any} parent
  18629. * @param {string} prop
  18630. * @param {number} index
  18631. */
  18632. remove(parent, prop, index) {
  18633. if (parent) {
  18634. if (index !== null) {
  18635. parent[prop].splice(index, 1);
  18636. } else {
  18637. delete parent[prop];
  18638. }
  18639. }
  18640. }
  18641. }
  18642. // @ts-check
  18643. /** @typedef { import('estree').BaseNode} BaseNode */
  18644. /** @typedef { import('./walker.js').WalkerContext} WalkerContext */
  18645. /** @typedef {(
  18646. * this: WalkerContext,
  18647. * node: BaseNode,
  18648. * parent: BaseNode,
  18649. * key: string,
  18650. * index: number
  18651. * ) => void} SyncHandler */
  18652. class SyncWalker extends WalkerBase {
  18653. /**
  18654. *
  18655. * @param {SyncHandler} enter
  18656. * @param {SyncHandler} leave
  18657. */
  18658. constructor(enter, leave) {
  18659. super();
  18660. /** @type {SyncHandler} */
  18661. this.enter = enter;
  18662. /** @type {SyncHandler} */
  18663. this.leave = leave;
  18664. }
  18665. /**
  18666. *
  18667. * @param {BaseNode} node
  18668. * @param {BaseNode} parent
  18669. * @param {string} [prop]
  18670. * @param {number} [index]
  18671. * @returns {BaseNode}
  18672. */
  18673. visit(node, parent, prop, index) {
  18674. if (node) {
  18675. if (this.enter) {
  18676. const _should_skip = this.should_skip;
  18677. const _should_remove = this.should_remove;
  18678. const _replacement = this.replacement;
  18679. this.should_skip = false;
  18680. this.should_remove = false;
  18681. this.replacement = null;
  18682. this.enter.call(this.context, node, parent, prop, index);
  18683. if (this.replacement) {
  18684. node = this.replacement;
  18685. this.replace(parent, prop, index, node);
  18686. }
  18687. if (this.should_remove) {
  18688. this.remove(parent, prop, index);
  18689. }
  18690. const skipped = this.should_skip;
  18691. const removed = this.should_remove;
  18692. this.should_skip = _should_skip;
  18693. this.should_remove = _should_remove;
  18694. this.replacement = _replacement;
  18695. if (skipped) return node;
  18696. if (removed) return null;
  18697. }
  18698. for (const key in node) {
  18699. const value = node[key];
  18700. if (typeof value !== "object") {
  18701. continue;
  18702. } else if (Array.isArray(value)) {
  18703. for (let i = 0; i < value.length; i += 1) {
  18704. if (value[i] !== null && typeof value[i].type === 'string') {
  18705. if (!this.visit(value[i], node, key, i)) {
  18706. // removed
  18707. i--;
  18708. }
  18709. }
  18710. }
  18711. } else if (value !== null && typeof value.type === "string") {
  18712. this.visit(value, node, key, null);
  18713. }
  18714. }
  18715. if (this.leave) {
  18716. const _replacement = this.replacement;
  18717. const _should_remove = this.should_remove;
  18718. this.replacement = null;
  18719. this.should_remove = false;
  18720. this.leave.call(this.context, node, parent, prop, index);
  18721. if (this.replacement) {
  18722. node = this.replacement;
  18723. this.replace(parent, prop, index, node);
  18724. }
  18725. if (this.should_remove) {
  18726. this.remove(parent, prop, index);
  18727. }
  18728. const removed = this.should_remove;
  18729. this.replacement = _replacement;
  18730. this.should_remove = _should_remove;
  18731. if (removed) return null;
  18732. }
  18733. }
  18734. return node;
  18735. }
  18736. }
  18737. // @ts-check
  18738. /** @typedef { import('estree').BaseNode} BaseNode */
  18739. /** @typedef { import('./sync.js').SyncHandler} SyncHandler */
  18740. /** @typedef { import('./async.js').AsyncHandler} AsyncHandler */
  18741. /**
  18742. *
  18743. * @param {BaseNode} ast
  18744. * @param {{
  18745. * enter?: SyncHandler
  18746. * leave?: SyncHandler
  18747. * }} walker
  18748. * @returns {BaseNode}
  18749. */
  18750. function walk$1(ast, { enter, leave }) {
  18751. const instance = new SyncWalker(enter, leave);
  18752. return instance.visit(ast, null);
  18753. }
  18754. function walkIdentifiers(root, onIdentifier, includeAll = false, parentStack = [], knownIds = Object.create(null)) {
  18755. const rootExp = root.type === 'Program' &&
  18756. root.body[0].type === 'ExpressionStatement' &&
  18757. root.body[0].expression;
  18758. walk$1(root, {
  18759. enter(node, parent) {
  18760. parent && parentStack.push(parent);
  18761. if (parent &&
  18762. parent.type.startsWith('TS') &&
  18763. parent.type !== 'TSAsExpression' &&
  18764. parent.type !== 'TSNonNullExpression' &&
  18765. parent.type !== 'TSTypeAssertion') {
  18766. return this.skip();
  18767. }
  18768. if (node.type === 'Identifier') {
  18769. const isLocal = !!knownIds[node.name];
  18770. const isRefed = isReferencedIdentifier(node, parent, parentStack);
  18771. if (includeAll || (isRefed && !isLocal)) {
  18772. onIdentifier(node, parent, parentStack, isRefed, isLocal);
  18773. }
  18774. }
  18775. else if (node.type === 'ObjectProperty' &&
  18776. parent.type === 'ObjectPattern') {
  18777. node.inPattern = true;
  18778. }
  18779. else if (isFunctionType(node)) {
  18780. // walk function expressions and add its arguments to known identifiers
  18781. // so that we don't prefix them
  18782. walkFunctionParams(node, id => markScopeIdentifier(node, id, knownIds));
  18783. }
  18784. else if (node.type === 'BlockStatement') {
  18785. // #3445 record block-level local variables
  18786. walkBlockDeclarations(node, id => markScopeIdentifier(node, id, knownIds));
  18787. }
  18788. },
  18789. leave(node, parent) {
  18790. parent && parentStack.pop();
  18791. if (node !== rootExp && node.scopeIds) {
  18792. for (const id of node.scopeIds) {
  18793. knownIds[id]--;
  18794. if (knownIds[id] === 0) {
  18795. delete knownIds[id];
  18796. }
  18797. }
  18798. }
  18799. }
  18800. });
  18801. }
  18802. function isReferencedIdentifier(id, parent, parentStack) {
  18803. if (!parent) {
  18804. return true;
  18805. }
  18806. // is a special keyword but parsed as identifier
  18807. if (id.name === 'arguments') {
  18808. return false;
  18809. }
  18810. if (isReferenced(id, parent)) {
  18811. return true;
  18812. }
  18813. // babel's isReferenced check returns false for ids being assigned to, so we
  18814. // need to cover those cases here
  18815. switch (parent.type) {
  18816. case 'AssignmentExpression':
  18817. case 'AssignmentPattern':
  18818. return true;
  18819. case 'ObjectPattern':
  18820. case 'ArrayPattern':
  18821. return isInDestructureAssignment(parent, parentStack);
  18822. }
  18823. return false;
  18824. }
  18825. function isInDestructureAssignment(parent, parentStack) {
  18826. if (parent &&
  18827. (parent.type === 'ObjectProperty' || parent.type === 'ArrayPattern')) {
  18828. let i = parentStack.length;
  18829. while (i--) {
  18830. const p = parentStack[i];
  18831. if (p.type === 'AssignmentExpression') {
  18832. return true;
  18833. }
  18834. else if (p.type !== 'ObjectProperty' && !p.type.endsWith('Pattern')) {
  18835. break;
  18836. }
  18837. }
  18838. }
  18839. return false;
  18840. }
  18841. function walkFunctionParams(node, onIdent) {
  18842. for (const p of node.params) {
  18843. for (const id of extractIdentifiers(p)) {
  18844. onIdent(id);
  18845. }
  18846. }
  18847. }
  18848. function walkBlockDeclarations(block, onIdent) {
  18849. for (const stmt of block.body) {
  18850. if (stmt.type === 'VariableDeclaration') {
  18851. if (stmt.declare)
  18852. continue;
  18853. for (const decl of stmt.declarations) {
  18854. for (const id of extractIdentifiers(decl.id)) {
  18855. onIdent(id);
  18856. }
  18857. }
  18858. }
  18859. else if (stmt.type === 'FunctionDeclaration' ||
  18860. stmt.type === 'ClassDeclaration') {
  18861. if (stmt.declare || !stmt.id)
  18862. continue;
  18863. onIdent(stmt.id);
  18864. }
  18865. }
  18866. }
  18867. function extractIdentifiers(param, nodes = []) {
  18868. switch (param.type) {
  18869. case 'Identifier':
  18870. nodes.push(param);
  18871. break;
  18872. case 'MemberExpression':
  18873. let object = param;
  18874. while (object.type === 'MemberExpression') {
  18875. object = object.object;
  18876. }
  18877. nodes.push(object);
  18878. break;
  18879. case 'ObjectPattern':
  18880. for (const prop of param.properties) {
  18881. if (prop.type === 'RestElement') {
  18882. extractIdentifiers(prop.argument, nodes);
  18883. }
  18884. else {
  18885. extractIdentifiers(prop.value, nodes);
  18886. }
  18887. }
  18888. break;
  18889. case 'ArrayPattern':
  18890. param.elements.forEach(element => {
  18891. if (element)
  18892. extractIdentifiers(element, nodes);
  18893. });
  18894. break;
  18895. case 'RestElement':
  18896. extractIdentifiers(param.argument, nodes);
  18897. break;
  18898. case 'AssignmentPattern':
  18899. extractIdentifiers(param.left, nodes);
  18900. break;
  18901. }
  18902. return nodes;
  18903. }
  18904. function markScopeIdentifier(node, child, knownIds) {
  18905. const { name } = child;
  18906. if (node.scopeIds && node.scopeIds.has(name)) {
  18907. return;
  18908. }
  18909. if (name in knownIds) {
  18910. knownIds[name]++;
  18911. }
  18912. else {
  18913. knownIds[name] = 1;
  18914. }
  18915. (node.scopeIds || (node.scopeIds = new Set())).add(name);
  18916. }
  18917. const isFunctionType = (node) => {
  18918. return /Function(?:Expression|Declaration)$|Method$/.test(node.type);
  18919. };
  18920. const isStaticProperty = (node) => node &&
  18921. (node.type === 'ObjectProperty' || node.type === 'ObjectMethod') &&
  18922. !node.computed;
  18923. const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node;
  18924. /**
  18925. * Copied from https://github.com/babel/babel/blob/main/packages/babel-types/src/validators/isReferenced.ts
  18926. * To avoid runtime dependency on @babel/types (which includes process references)
  18927. * This file should not change very often in babel but we may need to keep it
  18928. * up-to-date from time to time.
  18929. *
  18930. * https://github.com/babel/babel/blob/main/LICENSE
  18931. *
  18932. */
  18933. function isReferenced(node, parent, grandparent) {
  18934. switch (parent.type) {
  18935. // yes: PARENT[NODE]
  18936. // yes: NODE.child
  18937. // no: parent.NODE
  18938. case 'MemberExpression':
  18939. case 'OptionalMemberExpression':
  18940. if (parent.property === node) {
  18941. return !!parent.computed;
  18942. }
  18943. return parent.object === node;
  18944. case 'JSXMemberExpression':
  18945. return parent.object === node;
  18946. // no: let NODE = init;
  18947. // yes: let id = NODE;
  18948. case 'VariableDeclarator':
  18949. return parent.init === node;
  18950. // yes: () => NODE
  18951. // no: (NODE) => {}
  18952. case 'ArrowFunctionExpression':
  18953. return parent.body === node;
  18954. // no: class { #NODE; }
  18955. // no: class { get #NODE() {} }
  18956. // no: class { #NODE() {} }
  18957. // no: class { fn() { return this.#NODE; } }
  18958. case 'PrivateName':
  18959. return false;
  18960. // no: class { NODE() {} }
  18961. // yes: class { [NODE]() {} }
  18962. // no: class { foo(NODE) {} }
  18963. case 'ClassMethod':
  18964. case 'ClassPrivateMethod':
  18965. case 'ObjectMethod':
  18966. if (parent.key === node) {
  18967. return !!parent.computed;
  18968. }
  18969. return false;
  18970. // yes: { [NODE]: "" }
  18971. // no: { NODE: "" }
  18972. // depends: { NODE }
  18973. // depends: { key: NODE }
  18974. case 'ObjectProperty':
  18975. if (parent.key === node) {
  18976. return !!parent.computed;
  18977. }
  18978. // parent.value === node
  18979. return !grandparent || grandparent.type !== 'ObjectPattern';
  18980. // no: class { NODE = value; }
  18981. // yes: class { [NODE] = value; }
  18982. // yes: class { key = NODE; }
  18983. case 'ClassProperty':
  18984. if (parent.key === node) {
  18985. return !!parent.computed;
  18986. }
  18987. return true;
  18988. case 'ClassPrivateProperty':
  18989. return parent.key !== node;
  18990. // no: class NODE {}
  18991. // yes: class Foo extends NODE {}
  18992. case 'ClassDeclaration':
  18993. case 'ClassExpression':
  18994. return parent.superClass === node;
  18995. // yes: left = NODE;
  18996. // no: NODE = right;
  18997. case 'AssignmentExpression':
  18998. return parent.right === node;
  18999. // no: [NODE = foo] = [];
  19000. // yes: [foo = NODE] = [];
  19001. case 'AssignmentPattern':
  19002. return parent.right === node;
  19003. // no: NODE: for (;;) {}
  19004. case 'LabeledStatement':
  19005. return false;
  19006. // no: try {} catch (NODE) {}
  19007. case 'CatchClause':
  19008. return false;
  19009. // no: function foo(...NODE) {}
  19010. case 'RestElement':
  19011. return false;
  19012. case 'BreakStatement':
  19013. case 'ContinueStatement':
  19014. return false;
  19015. // no: function NODE() {}
  19016. // no: function foo(NODE) {}
  19017. case 'FunctionDeclaration':
  19018. case 'FunctionExpression':
  19019. return false;
  19020. // no: export NODE from "foo";
  19021. // no: export * as NODE from "foo";
  19022. case 'ExportNamespaceSpecifier':
  19023. case 'ExportDefaultSpecifier':
  19024. return false;
  19025. // no: export { foo as NODE };
  19026. // yes: export { NODE as foo };
  19027. // no: export { NODE as foo } from "foo";
  19028. case 'ExportSpecifier':
  19029. // @ts-expect-error
  19030. if (grandparent === null || grandparent === void 0 ? void 0 : grandparent.source) {
  19031. return false;
  19032. }
  19033. return parent.local === node;
  19034. // no: import NODE from "foo";
  19035. // no: import * as NODE from "foo";
  19036. // no: import { NODE as foo } from "foo";
  19037. // no: import { foo as NODE } from "foo";
  19038. // no: import NODE from "bar";
  19039. case 'ImportDefaultSpecifier':
  19040. case 'ImportNamespaceSpecifier':
  19041. case 'ImportSpecifier':
  19042. return false;
  19043. // no: import "foo" assert { NODE: "json" }
  19044. case 'ImportAttribute':
  19045. return false;
  19046. // no: <div NODE="foo" />
  19047. case 'JSXAttribute':
  19048. return false;
  19049. // no: [NODE] = [];
  19050. // no: ({ NODE }) = [];
  19051. case 'ObjectPattern':
  19052. case 'ArrayPattern':
  19053. return false;
  19054. // no: new.NODE
  19055. // no: NODE.target
  19056. case 'MetaProperty':
  19057. return false;
  19058. // yes: type X = { somePropert: NODE }
  19059. // no: type X = { NODE: OtherType }
  19060. case 'ObjectTypeProperty':
  19061. return parent.key !== node;
  19062. // yes: enum X { Foo = NODE }
  19063. // no: enum X { NODE }
  19064. case 'TSEnumMember':
  19065. return parent.id !== node;
  19066. // yes: { [NODE]: value }
  19067. // no: { NODE: value }
  19068. case 'TSPropertySignature':
  19069. if (parent.key === node) {
  19070. return !!parent.computed;
  19071. }
  19072. return true;
  19073. }
  19074. return true;
  19075. }
  19076. const isLiteralWhitelisted = /*#__PURE__*/ makeMap('true,false,null,this');
  19077. const transformExpression = (node, context) => {
  19078. if (node.type === 5 /* INTERPOLATION */) {
  19079. node.content = processExpression(node.content, context);
  19080. }
  19081. else if (node.type === 1 /* ELEMENT */) {
  19082. // handle directives on element
  19083. for (let i = 0; i < node.props.length; i++) {
  19084. const dir = node.props[i];
  19085. // do not process for v-on & v-for since they are special handled
  19086. if (dir.type === 7 /* DIRECTIVE */ && dir.name !== 'for') {
  19087. const exp = dir.exp;
  19088. const arg = dir.arg;
  19089. // do not process exp if this is v-on:arg - we need special handling
  19090. // for wrapping inline statements.
  19091. if (exp &&
  19092. exp.type === 4 /* SIMPLE_EXPRESSION */ &&
  19093. !(dir.name === 'on' && arg)) {
  19094. dir.exp = processExpression(exp, context,
  19095. // slot args must be processed as function params
  19096. dir.name === 'slot');
  19097. }
  19098. if (arg && arg.type === 4 /* SIMPLE_EXPRESSION */ && !arg.isStatic) {
  19099. dir.arg = processExpression(arg, context);
  19100. }
  19101. }
  19102. }
  19103. }
  19104. };
  19105. // Important: since this function uses Node.js only dependencies, it should
  19106. // always be used with a leading !false check so that it can be
  19107. // tree-shaken from the browser build.
  19108. function processExpression(node, context,
  19109. // some expressions like v-slot props & v-for aliases should be parsed as
  19110. // function params
  19111. asParams = false,
  19112. // v-on handler values may contain multiple statements
  19113. asRawStatements = false, localVars = Object.create(context.identifiers)) {
  19114. if (!context.prefixIdentifiers || !node.content.trim()) {
  19115. return node;
  19116. }
  19117. const { inline, bindingMetadata } = context;
  19118. const rewriteIdentifier = (raw, parent, id) => {
  19119. const type = hasOwn(bindingMetadata, raw) && bindingMetadata[raw];
  19120. if (inline) {
  19121. // x = y
  19122. const isAssignmentLVal = parent && parent.type === 'AssignmentExpression' && parent.left === id;
  19123. // x++
  19124. const isUpdateArg = parent && parent.type === 'UpdateExpression' && parent.argument === id;
  19125. // ({ x } = y)
  19126. const isDestructureAssignment = parent && isInDestructureAssignment(parent, parentStack);
  19127. if (type === "setup-const" /* SETUP_CONST */ || localVars[raw]) {
  19128. return raw;
  19129. }
  19130. else if (type === "setup-ref" /* SETUP_REF */) {
  19131. return `${raw}.value`;
  19132. }
  19133. else if (type === "setup-maybe-ref" /* SETUP_MAYBE_REF */) {
  19134. // const binding that may or may not be ref
  19135. // if it's not a ref, then assignments don't make sense -
  19136. // so we ignore the non-ref assignment case and generate code
  19137. // that assumes the value to be a ref for more efficiency
  19138. return isAssignmentLVal || isUpdateArg || isDestructureAssignment
  19139. ? `${raw}.value`
  19140. : `${context.helperString(UNREF)}(${raw})`;
  19141. }
  19142. else if (type === "setup-let" /* SETUP_LET */) {
  19143. if (isAssignmentLVal) {
  19144. // let binding.
  19145. // this is a bit more tricky as we need to cover the case where
  19146. // let is a local non-ref value, and we need to replicate the
  19147. // right hand side value.
  19148. // x = y --> isRef(x) ? x.value = y : x = y
  19149. const { right: rVal, operator } = parent;
  19150. const rExp = rawExp.slice(rVal.start - 1, rVal.end - 1);
  19151. const rExpString = stringifyExpression(processExpression(createSimpleExpression(rExp, false), context, false, false, knownIds));
  19152. return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore\n` : ``} ? ${raw}.value ${operator} ${rExpString} : ${raw}`;
  19153. }
  19154. else if (isUpdateArg) {
  19155. // make id replace parent in the code range so the raw update operator
  19156. // is removed
  19157. id.start = parent.start;
  19158. id.end = parent.end;
  19159. const { prefix: isPrefix, operator } = parent;
  19160. const prefix = isPrefix ? operator : ``;
  19161. const postfix = isPrefix ? `` : operator;
  19162. // let binding.
  19163. // x++ --> isRef(a) ? a.value++ : a++
  19164. return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore\n` : ``} ? ${prefix}${raw}.value${postfix} : ${prefix}${raw}${postfix}`;
  19165. }
  19166. else if (isDestructureAssignment) {
  19167. // TODO
  19168. // let binding in a destructure assignment - it's very tricky to
  19169. // handle both possible cases here without altering the original
  19170. // structure of the code, so we just assume it's not a ref here
  19171. // for now
  19172. return raw;
  19173. }
  19174. else {
  19175. return `${context.helperString(UNREF)}(${raw})`;
  19176. }
  19177. }
  19178. else if (type === "props" /* PROPS */) {
  19179. // use __props which is generated by compileScript so in ts mode
  19180. // it gets correct type
  19181. return `__props.${raw}`;
  19182. }
  19183. else if (type === "props-aliased" /* PROPS_ALIASED */) {
  19184. // prop with a different local alias (from defineProps() destructure)
  19185. return `__props.${bindingMetadata.__propsAliases[raw]}`;
  19186. }
  19187. }
  19188. else {
  19189. if (type && type.startsWith('setup')) {
  19190. // setup bindings in non-inline mode
  19191. return `$setup.${raw}`;
  19192. }
  19193. else if (type === "props-aliased" /* PROPS_ALIASED */) {
  19194. return `$props.${bindingMetadata.__propsAliases[raw]}`;
  19195. }
  19196. else if (type) {
  19197. return `$${type}.${raw}`;
  19198. }
  19199. }
  19200. // fallback to ctx
  19201. return `_ctx.${raw}`;
  19202. };
  19203. // fast path if expression is a simple identifier.
  19204. const rawExp = node.content;
  19205. // bail constant on parens (function invocation) and dot (member access)
  19206. const bailConstant = rawExp.indexOf(`(`) > -1 || rawExp.indexOf('.') > 0;
  19207. if (isSimpleIdentifier(rawExp)) {
  19208. const isScopeVarReference = context.identifiers[rawExp];
  19209. const isAllowedGlobal = isGloballyWhitelisted(rawExp);
  19210. const isLiteral = isLiteralWhitelisted(rawExp);
  19211. if (!asParams && !isScopeVarReference && !isAllowedGlobal && !isLiteral) {
  19212. // const bindings exposed from setup can be skipped for patching but
  19213. // cannot be hoisted to module scope
  19214. if (bindingMetadata[node.content] === "setup-const" /* SETUP_CONST */) {
  19215. node.constType = 1 /* CAN_SKIP_PATCH */;
  19216. }
  19217. node.content = rewriteIdentifier(rawExp);
  19218. }
  19219. else if (!isScopeVarReference) {
  19220. if (isLiteral) {
  19221. node.constType = 3 /* CAN_STRINGIFY */;
  19222. }
  19223. else {
  19224. node.constType = 2 /* CAN_HOIST */;
  19225. }
  19226. }
  19227. return node;
  19228. }
  19229. let ast;
  19230. // exp needs to be parsed differently:
  19231. // 1. Multiple inline statements (v-on, with presence of `;`): parse as raw
  19232. // exp, but make sure to pad with spaces for consistent ranges
  19233. // 2. Expressions: wrap with parens (for e.g. object expressions)
  19234. // 3. Function arguments (v-for, v-slot): place in a function argument position
  19235. const source = asRawStatements
  19236. ? ` ${rawExp} `
  19237. : `(${rawExp})${asParams ? `=>{}` : ``}`;
  19238. try {
  19239. ast = parse_1(source, {
  19240. plugins: context.expressionPlugins
  19241. }).program;
  19242. }
  19243. catch (e) {
  19244. context.onError(createCompilerError(44 /* X_INVALID_EXPRESSION */, node.loc, undefined, e.message));
  19245. return node;
  19246. }
  19247. const ids = [];
  19248. const parentStack = [];
  19249. const knownIds = Object.create(context.identifiers);
  19250. walkIdentifiers(ast, (node, parent, _, isReferenced, isLocal) => {
  19251. if (isStaticPropertyKey(node, parent)) {
  19252. return;
  19253. }
  19254. const needPrefix = isReferenced && canPrefix(node);
  19255. if (needPrefix && !isLocal) {
  19256. if (isStaticProperty(parent) && parent.shorthand) {
  19257. node.prefix = `${node.name}: `;
  19258. }
  19259. node.name = rewriteIdentifier(node.name, parent, node);
  19260. ids.push(node);
  19261. }
  19262. else {
  19263. // The identifier is considered constant unless it's pointing to a
  19264. // local scope variable (a v-for alias, or a v-slot prop)
  19265. if (!(needPrefix && isLocal) && !bailConstant) {
  19266. node.isConstant = true;
  19267. }
  19268. // also generate sub-expressions for other identifiers for better
  19269. // source map support. (except for property keys which are static)
  19270. ids.push(node);
  19271. }
  19272. }, true, // invoke on ALL identifiers
  19273. parentStack, knownIds);
  19274. // We break up the compound expression into an array of strings and sub
  19275. // expressions (for identifiers that have been prefixed). In codegen, if
  19276. // an ExpressionNode has the `.children` property, it will be used instead of
  19277. // `.content`.
  19278. const children = [];
  19279. ids.sort((a, b) => a.start - b.start);
  19280. ids.forEach((id, i) => {
  19281. // range is offset by -1 due to the wrapping parens when parsed
  19282. const start = id.start - 1;
  19283. const end = id.end - 1;
  19284. const last = ids[i - 1];
  19285. const leadingText = rawExp.slice(last ? last.end - 1 : 0, start);
  19286. if (leadingText.length || id.prefix) {
  19287. children.push(leadingText + (id.prefix || ``));
  19288. }
  19289. const source = rawExp.slice(start, end);
  19290. children.push(createSimpleExpression(id.name, false, {
  19291. source,
  19292. start: advancePositionWithClone(node.loc.start, source, start),
  19293. end: advancePositionWithClone(node.loc.start, source, end)
  19294. }, id.isConstant ? 3 /* CAN_STRINGIFY */ : 0 /* NOT_CONSTANT */));
  19295. if (i === ids.length - 1 && end < rawExp.length) {
  19296. children.push(rawExp.slice(end));
  19297. }
  19298. });
  19299. let ret;
  19300. if (children.length) {
  19301. ret = createCompoundExpression(children, node.loc);
  19302. }
  19303. else {
  19304. ret = node;
  19305. ret.constType = bailConstant
  19306. ? 0 /* NOT_CONSTANT */
  19307. : 3 /* CAN_STRINGIFY */;
  19308. }
  19309. ret.identifiers = Object.keys(knownIds);
  19310. return ret;
  19311. }
  19312. function canPrefix(id) {
  19313. // skip whitelisted globals
  19314. if (isGloballyWhitelisted(id.name)) {
  19315. return false;
  19316. }
  19317. // special case for webpack compilation
  19318. if (id.name === 'require') {
  19319. return false;
  19320. }
  19321. return true;
  19322. }
  19323. function stringifyExpression(exp) {
  19324. if (isString(exp)) {
  19325. return exp;
  19326. }
  19327. else if (exp.type === 4 /* SIMPLE_EXPRESSION */) {
  19328. return exp.content;
  19329. }
  19330. else {
  19331. return exp.children
  19332. .map(stringifyExpression)
  19333. .join('');
  19334. }
  19335. }
  19336. const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
  19337. return processIf(node, dir, context, (ifNode, branch, isRoot) => {
  19338. // #1587: We need to dynamically increment the key based on the current
  19339. // node's sibling nodes, since chained v-if/else branches are
  19340. // rendered at the same depth
  19341. const siblings = context.parent.children;
  19342. let i = siblings.indexOf(ifNode);
  19343. let key = 0;
  19344. while (i-- >= 0) {
  19345. const sibling = siblings[i];
  19346. if (sibling && sibling.type === 9 /* IF */) {
  19347. key += sibling.branches.length;
  19348. }
  19349. }
  19350. // Exit callback. Complete the codegenNode when all children have been
  19351. // transformed.
  19352. return () => {
  19353. if (isRoot) {
  19354. ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
  19355. }
  19356. else {
  19357. // attach this branch's codegen node to the v-if root.
  19358. const parentCondition = getParentCondition(ifNode.codegenNode);
  19359. parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
  19360. }
  19361. };
  19362. });
  19363. });
  19364. // target-agnostic transform used for both Client and SSR
  19365. function processIf(node, dir, context, processCodegen) {
  19366. if (dir.name !== 'else' &&
  19367. (!dir.exp || !dir.exp.content.trim())) {
  19368. const loc = dir.exp ? dir.exp.loc : node.loc;
  19369. context.onError(createCompilerError(28 /* X_V_IF_NO_EXPRESSION */, dir.loc));
  19370. dir.exp = createSimpleExpression(`true`, false, loc);
  19371. }
  19372. if (context.prefixIdentifiers && dir.exp) {
  19373. // dir.exp can only be simple expression because vIf transform is applied
  19374. // before expression transform.
  19375. dir.exp = processExpression(dir.exp, context);
  19376. }
  19377. if (dir.name === 'if') {
  19378. const branch = createIfBranch(node, dir);
  19379. const ifNode = {
  19380. type: 9 /* IF */,
  19381. loc: node.loc,
  19382. branches: [branch]
  19383. };
  19384. context.replaceNode(ifNode);
  19385. if (processCodegen) {
  19386. return processCodegen(ifNode, branch, true);
  19387. }
  19388. }
  19389. else {
  19390. // locate the adjacent v-if
  19391. const siblings = context.parent.children;
  19392. const comments = [];
  19393. let i = siblings.indexOf(node);
  19394. while (i-- >= -1) {
  19395. const sibling = siblings[i];
  19396. if (sibling && sibling.type === 3 /* COMMENT */) {
  19397. context.removeNode(sibling);
  19398. comments.unshift(sibling);
  19399. continue;
  19400. }
  19401. if (sibling &&
  19402. sibling.type === 2 /* TEXT */ &&
  19403. !sibling.content.trim().length) {
  19404. context.removeNode(sibling);
  19405. continue;
  19406. }
  19407. if (sibling && sibling.type === 9 /* IF */) {
  19408. // Check if v-else was followed by v-else-if
  19409. if (dir.name === 'else-if' &&
  19410. sibling.branches[sibling.branches.length - 1].condition === undefined) {
  19411. context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  19412. }
  19413. // move the node to the if node's branches
  19414. context.removeNode();
  19415. const branch = createIfBranch(node, dir);
  19416. if (comments.length &&
  19417. // #3619 ignore comments if the v-if is direct child of <transition>
  19418. !(context.parent &&
  19419. context.parent.type === 1 /* ELEMENT */ &&
  19420. isBuiltInType(context.parent.tag, 'transition'))) {
  19421. branch.children = [...comments, ...branch.children];
  19422. }
  19423. // check if user is forcing same key on different branches
  19424. {
  19425. const key = branch.userKey;
  19426. if (key) {
  19427. sibling.branches.forEach(({ userKey }) => {
  19428. if (isSameKey(userKey, key)) {
  19429. context.onError(createCompilerError(29 /* X_V_IF_SAME_KEY */, branch.userKey.loc));
  19430. }
  19431. });
  19432. }
  19433. }
  19434. sibling.branches.push(branch);
  19435. const onExit = processCodegen && processCodegen(sibling, branch, false);
  19436. // since the branch was removed, it will not be traversed.
  19437. // make sure to traverse here.
  19438. traverseNode(branch, context);
  19439. // call on exit
  19440. if (onExit)
  19441. onExit();
  19442. // make sure to reset currentNode after traversal to indicate this
  19443. // node has been removed.
  19444. context.currentNode = null;
  19445. }
  19446. else {
  19447. context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  19448. }
  19449. break;
  19450. }
  19451. }
  19452. }
  19453. function createIfBranch(node, dir) {
  19454. return {
  19455. type: 10 /* IF_BRANCH */,
  19456. loc: node.loc,
  19457. condition: dir.name === 'else' ? undefined : dir.exp,
  19458. children: node.tagType === 3 /* TEMPLATE */ && !findDir(node, 'for')
  19459. ? node.children
  19460. : [node],
  19461. userKey: findProp(node, `key`)
  19462. };
  19463. }
  19464. function createCodegenNodeForBranch(branch, keyIndex, context) {
  19465. if (branch.condition) {
  19466. return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
  19467. // make sure to pass in asBlock: true so that the comment node call
  19468. // closes the current block.
  19469. createCallExpression(context.helper(CREATE_COMMENT), [
  19470. '"v-if"' ,
  19471. 'true'
  19472. ]));
  19473. }
  19474. else {
  19475. return createChildrenCodegenNode(branch, keyIndex, context);
  19476. }
  19477. }
  19478. function createChildrenCodegenNode(branch, keyIndex, context) {
  19479. const { helper } = context;
  19480. const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* CAN_HOIST */));
  19481. const { children } = branch;
  19482. const firstChild = children[0];
  19483. const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* ELEMENT */;
  19484. if (needFragmentWrapper) {
  19485. if (children.length === 1 && firstChild.type === 11 /* FOR */) {
  19486. // optimize away nested fragments when child is a ForNode
  19487. const vnodeCall = firstChild.codegenNode;
  19488. injectProp(vnodeCall, keyProperty, context);
  19489. return vnodeCall;
  19490. }
  19491. else {
  19492. let patchFlag = 64 /* STABLE_FRAGMENT */;
  19493. let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
  19494. // check if the fragment actually contains a single valid child with
  19495. // the rest being comments
  19496. if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
  19497. patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
  19498. patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
  19499. }
  19500. return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, false, false /* isComponent */, branch.loc);
  19501. }
  19502. }
  19503. else {
  19504. const ret = firstChild.codegenNode;
  19505. const vnodeCall = getMemoedVNodeCall(ret);
  19506. // Change createVNode to createBlock.
  19507. if (vnodeCall.type === 13 /* VNODE_CALL */) {
  19508. makeBlock(vnodeCall, context);
  19509. }
  19510. // inject branch key
  19511. injectProp(vnodeCall, keyProperty, context);
  19512. return ret;
  19513. }
  19514. }
  19515. function isSameKey(a, b) {
  19516. if (!a || a.type !== b.type) {
  19517. return false;
  19518. }
  19519. if (a.type === 6 /* ATTRIBUTE */) {
  19520. if (a.value.content !== b.value.content) {
  19521. return false;
  19522. }
  19523. }
  19524. else {
  19525. // directive
  19526. const exp = a.exp;
  19527. const branchExp = b.exp;
  19528. if (exp.type !== branchExp.type) {
  19529. return false;
  19530. }
  19531. if (exp.type !== 4 /* SIMPLE_EXPRESSION */ ||
  19532. exp.isStatic !== branchExp.isStatic ||
  19533. exp.content !== branchExp.content) {
  19534. return false;
  19535. }
  19536. }
  19537. return true;
  19538. }
  19539. function getParentCondition(node) {
  19540. while (true) {
  19541. if (node.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  19542. if (node.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  19543. node = node.alternate;
  19544. }
  19545. else {
  19546. return node;
  19547. }
  19548. }
  19549. else if (node.type === 20 /* JS_CACHE_EXPRESSION */) {
  19550. node = node.value;
  19551. }
  19552. }
  19553. }
  19554. const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
  19555. const { helper, removeHelper } = context;
  19556. return processFor(node, dir, context, forNode => {
  19557. // create the loop render function expression now, and add the
  19558. // iterator on exit after all children have been traversed
  19559. const renderExp = createCallExpression(helper(RENDER_LIST), [
  19560. forNode.source
  19561. ]);
  19562. const memo = findDir(node, 'memo');
  19563. const keyProp = findProp(node, `key`);
  19564. const keyExp = keyProp &&
  19565. (keyProp.type === 6 /* ATTRIBUTE */
  19566. ? createSimpleExpression(keyProp.value.content, true)
  19567. : keyProp.exp);
  19568. const keyProperty = keyProp ? createObjectProperty(`key`, keyExp) : null;
  19569. if (context.prefixIdentifiers &&
  19570. keyProperty &&
  19571. keyProp.type !== 6 /* ATTRIBUTE */) {
  19572. // #2085 process :key expression needs to be processed in order for it
  19573. // to behave consistently for <template v-for> and <div v-for>.
  19574. // In the case of `<template v-for>`, the node is discarded and never
  19575. // traversed so its key expression won't be processed by the normal
  19576. // transforms.
  19577. keyProperty.value = processExpression(keyProperty.value, context);
  19578. }
  19579. const isStableFragment = forNode.source.type === 4 /* SIMPLE_EXPRESSION */ &&
  19580. forNode.source.constType > 0 /* NOT_CONSTANT */;
  19581. const fragmentFlag = isStableFragment
  19582. ? 64 /* STABLE_FRAGMENT */
  19583. : keyProp
  19584. ? 128 /* KEYED_FRAGMENT */
  19585. : 256 /* UNKEYED_FRAGMENT */;
  19586. forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
  19587. (` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, false /* isComponent */, node.loc);
  19588. return () => {
  19589. // finish the codegen now that all children have been traversed
  19590. let childBlock;
  19591. const isTemplate = isTemplateNode(node);
  19592. const { children } = forNode;
  19593. // check <template v-for> key placement
  19594. if (isTemplate) {
  19595. node.children.some(c => {
  19596. if (c.type === 1 /* ELEMENT */) {
  19597. const key = findProp(c, 'key');
  19598. if (key) {
  19599. context.onError(createCompilerError(33 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
  19600. return true;
  19601. }
  19602. }
  19603. });
  19604. }
  19605. const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* ELEMENT */;
  19606. const slotOutlet = isSlotOutlet(node)
  19607. ? node
  19608. : isTemplate &&
  19609. node.children.length === 1 &&
  19610. isSlotOutlet(node.children[0])
  19611. ? node.children[0] // api-extractor somehow fails to infer this
  19612. : null;
  19613. if (slotOutlet) {
  19614. // <slot v-for="..."> or <template v-for="..."><slot/></template>
  19615. childBlock = slotOutlet.codegenNode;
  19616. if (isTemplate && keyProperty) {
  19617. // <template v-for="..." :key="..."><slot/></template>
  19618. // we need to inject the key to the renderSlot() call.
  19619. // the props for renderSlot is passed as the 3rd argument.
  19620. injectProp(childBlock, keyProperty, context);
  19621. }
  19622. }
  19623. else if (needFragmentWrapper) {
  19624. // <template v-for="..."> with text or multi-elements
  19625. // should generate a fragment block for each loop
  19626. childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* STABLE_FRAGMENT */ +
  19627. (` /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`
  19628. ), undefined, undefined, true, undefined, false /* isComponent */);
  19629. }
  19630. else {
  19631. // Normal element v-for. Directly use the child's codegenNode
  19632. // but mark it as a block.
  19633. childBlock = children[0]
  19634. .codegenNode;
  19635. if (isTemplate && keyProperty) {
  19636. injectProp(childBlock, keyProperty, context);
  19637. }
  19638. if (childBlock.isBlock !== !isStableFragment) {
  19639. if (childBlock.isBlock) {
  19640. // switch from block to vnode
  19641. removeHelper(OPEN_BLOCK);
  19642. removeHelper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
  19643. }
  19644. else {
  19645. // switch from vnode to block
  19646. removeHelper(getVNodeHelper(context.inSSR, childBlock.isComponent));
  19647. }
  19648. }
  19649. childBlock.isBlock = !isStableFragment;
  19650. if (childBlock.isBlock) {
  19651. helper(OPEN_BLOCK);
  19652. helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
  19653. }
  19654. else {
  19655. helper(getVNodeHelper(context.inSSR, childBlock.isComponent));
  19656. }
  19657. }
  19658. if (memo) {
  19659. const loop = createFunctionExpression(createForLoopParams(forNode.parseResult, [
  19660. createSimpleExpression(`_cached`)
  19661. ]));
  19662. loop.body = createBlockStatement([
  19663. createCompoundExpression([`const _memo = (`, memo.exp, `)`]),
  19664. createCompoundExpression([
  19665. `if (_cached`,
  19666. ...(keyExp ? [` && _cached.key === `, keyExp] : []),
  19667. ` && ${context.helperString(IS_MEMO_SAME)}(_cached, _memo)) return _cached`
  19668. ]),
  19669. createCompoundExpression([`const _item = `, childBlock]),
  19670. createSimpleExpression(`_item.memo = _memo`),
  19671. createSimpleExpression(`return _item`)
  19672. ]);
  19673. renderExp.arguments.push(loop, createSimpleExpression(`_cache`), createSimpleExpression(String(context.cached++)));
  19674. }
  19675. else {
  19676. renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
  19677. }
  19678. };
  19679. });
  19680. });
  19681. // target-agnostic transform used for both Client and SSR
  19682. function processFor(node, dir, context, processCodegen) {
  19683. if (!dir.exp) {
  19684. context.onError(createCompilerError(31 /* X_V_FOR_NO_EXPRESSION */, dir.loc));
  19685. return;
  19686. }
  19687. const parseResult = parseForExpression(
  19688. // can only be simple expression because vFor transform is applied
  19689. // before expression transform.
  19690. dir.exp, context);
  19691. if (!parseResult) {
  19692. context.onError(createCompilerError(32 /* X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
  19693. return;
  19694. }
  19695. const { addIdentifiers, removeIdentifiers, scopes } = context;
  19696. const { source, value, key, index } = parseResult;
  19697. const forNode = {
  19698. type: 11 /* FOR */,
  19699. loc: dir.loc,
  19700. source,
  19701. valueAlias: value,
  19702. keyAlias: key,
  19703. objectIndexAlias: index,
  19704. parseResult,
  19705. children: isTemplateNode(node) ? node.children : [node]
  19706. };
  19707. context.replaceNode(forNode);
  19708. // bookkeeping
  19709. scopes.vFor++;
  19710. if (context.prefixIdentifiers) {
  19711. // scope management
  19712. // inject identifiers to context
  19713. value && addIdentifiers(value);
  19714. key && addIdentifiers(key);
  19715. index && addIdentifiers(index);
  19716. }
  19717. const onExit = processCodegen && processCodegen(forNode);
  19718. return () => {
  19719. scopes.vFor--;
  19720. if (context.prefixIdentifiers) {
  19721. value && removeIdentifiers(value);
  19722. key && removeIdentifiers(key);
  19723. index && removeIdentifiers(index);
  19724. }
  19725. if (onExit)
  19726. onExit();
  19727. };
  19728. }
  19729. const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
  19730. // This regex doesn't cover the case if key or index aliases have destructuring,
  19731. // but those do not make sense in the first place, so this works in practice.
  19732. const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
  19733. const stripParensRE = /^\(|\)$/g;
  19734. function parseForExpression(input, context) {
  19735. const loc = input.loc;
  19736. const exp = input.content;
  19737. const inMatch = exp.match(forAliasRE);
  19738. if (!inMatch)
  19739. return;
  19740. const [, LHS, RHS] = inMatch;
  19741. const result = {
  19742. source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
  19743. value: undefined,
  19744. key: undefined,
  19745. index: undefined
  19746. };
  19747. if (context.prefixIdentifiers) {
  19748. result.source = processExpression(result.source, context);
  19749. }
  19750. let valueContent = LHS.trim().replace(stripParensRE, '').trim();
  19751. const trimmedOffset = LHS.indexOf(valueContent);
  19752. const iteratorMatch = valueContent.match(forIteratorRE);
  19753. if (iteratorMatch) {
  19754. valueContent = valueContent.replace(forIteratorRE, '').trim();
  19755. const keyContent = iteratorMatch[1].trim();
  19756. let keyOffset;
  19757. if (keyContent) {
  19758. keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
  19759. result.key = createAliasExpression(loc, keyContent, keyOffset);
  19760. if (context.prefixIdentifiers) {
  19761. result.key = processExpression(result.key, context, true);
  19762. }
  19763. }
  19764. if (iteratorMatch[2]) {
  19765. const indexContent = iteratorMatch[2].trim();
  19766. if (indexContent) {
  19767. result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
  19768. ? keyOffset + keyContent.length
  19769. : trimmedOffset + valueContent.length));
  19770. if (context.prefixIdentifiers) {
  19771. result.index = processExpression(result.index, context, true);
  19772. }
  19773. }
  19774. }
  19775. }
  19776. if (valueContent) {
  19777. result.value = createAliasExpression(loc, valueContent, trimmedOffset);
  19778. if (context.prefixIdentifiers) {
  19779. result.value = processExpression(result.value, context, true);
  19780. }
  19781. }
  19782. return result;
  19783. }
  19784. function createAliasExpression(range, content, offset) {
  19785. return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
  19786. }
  19787. function createForLoopParams({ value, key, index }, memoArgs = []) {
  19788. return createParamsList([value, key, index, ...memoArgs]);
  19789. }
  19790. function createParamsList(args) {
  19791. let i = args.length;
  19792. while (i--) {
  19793. if (args[i])
  19794. break;
  19795. }
  19796. return args
  19797. .slice(0, i + 1)
  19798. .map((arg, i) => arg || createSimpleExpression(`_`.repeat(i + 1), false));
  19799. }
  19800. const defaultFallback = createSimpleExpression(`undefined`, false);
  19801. // A NodeTransform that:
  19802. // 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
  19803. // by transformExpression. This is only applied in non-browser builds with
  19804. // { prefixIdentifiers: true }.
  19805. // 2. Track v-slot depths so that we know a slot is inside another slot.
  19806. // Note the exit callback is executed before buildSlots() on the same node,
  19807. // so only nested slots see positive numbers.
  19808. const trackSlotScopes = (node, context) => {
  19809. if (node.type === 1 /* ELEMENT */ &&
  19810. (node.tagType === 1 /* COMPONENT */ ||
  19811. node.tagType === 3 /* TEMPLATE */)) {
  19812. // We are only checking non-empty v-slot here
  19813. // since we only care about slots that introduce scope variables.
  19814. const vSlot = findDir(node, 'slot');
  19815. if (vSlot) {
  19816. const slotProps = vSlot.exp;
  19817. if (context.prefixIdentifiers) {
  19818. slotProps && context.addIdentifiers(slotProps);
  19819. }
  19820. context.scopes.vSlot++;
  19821. return () => {
  19822. if (context.prefixIdentifiers) {
  19823. slotProps && context.removeIdentifiers(slotProps);
  19824. }
  19825. context.scopes.vSlot--;
  19826. };
  19827. }
  19828. }
  19829. };
  19830. // A NodeTransform that tracks scope identifiers for scoped slots with v-for.
  19831. // This transform is only applied in non-browser builds with { prefixIdentifiers: true }
  19832. const trackVForSlotScopes = (node, context) => {
  19833. let vFor;
  19834. if (isTemplateNode(node) &&
  19835. node.props.some(isVSlot) &&
  19836. (vFor = findDir(node, 'for'))) {
  19837. const result = (vFor.parseResult = parseForExpression(vFor.exp, context));
  19838. if (result) {
  19839. const { value, key, index } = result;
  19840. const { addIdentifiers, removeIdentifiers } = context;
  19841. value && addIdentifiers(value);
  19842. key && addIdentifiers(key);
  19843. index && addIdentifiers(index);
  19844. return () => {
  19845. value && removeIdentifiers(value);
  19846. key && removeIdentifiers(key);
  19847. index && removeIdentifiers(index);
  19848. };
  19849. }
  19850. }
  19851. };
  19852. const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
  19853. // Instead of being a DirectiveTransform, v-slot processing is called during
  19854. // transformElement to build the slots object for a component.
  19855. function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
  19856. context.helper(WITH_CTX);
  19857. const { children, loc } = node;
  19858. const slotsProperties = [];
  19859. const dynamicSlots = [];
  19860. // If the slot is inside a v-for or another v-slot, force it to be dynamic
  19861. // since it likely uses a scope variable.
  19862. let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
  19863. // with `prefixIdentifiers: true`, this can be further optimized to make
  19864. // it dynamic only when the slot actually uses the scope variables.
  19865. if (!context.ssr && context.prefixIdentifiers) {
  19866. hasDynamicSlots = hasScopeRef(node, context.identifiers);
  19867. }
  19868. // 1. Check for slot with slotProps on component itself.
  19869. // <Comp v-slot="{ prop }"/>
  19870. const onComponentSlot = findDir(node, 'slot', true);
  19871. if (onComponentSlot) {
  19872. const { arg, exp } = onComponentSlot;
  19873. if (arg && !isStaticExp(arg)) {
  19874. hasDynamicSlots = true;
  19875. }
  19876. slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
  19877. }
  19878. // 2. Iterate through children and check for template slots
  19879. // <template v-slot:foo="{ prop }">
  19880. let hasTemplateSlots = false;
  19881. let hasNamedDefaultSlot = false;
  19882. const implicitDefaultChildren = [];
  19883. const seenSlotNames = new Set();
  19884. for (let i = 0; i < children.length; i++) {
  19885. const slotElement = children[i];
  19886. let slotDir;
  19887. if (!isTemplateNode(slotElement) ||
  19888. !(slotDir = findDir(slotElement, 'slot', true))) {
  19889. // not a <template v-slot>, skip.
  19890. if (slotElement.type !== 3 /* COMMENT */) {
  19891. implicitDefaultChildren.push(slotElement);
  19892. }
  19893. continue;
  19894. }
  19895. if (onComponentSlot) {
  19896. // already has on-component slot - this is incorrect usage.
  19897. context.onError(createCompilerError(37 /* X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
  19898. break;
  19899. }
  19900. hasTemplateSlots = true;
  19901. const { children: slotChildren, loc: slotLoc } = slotElement;
  19902. const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
  19903. // check if name is dynamic.
  19904. let staticSlotName;
  19905. if (isStaticExp(slotName)) {
  19906. staticSlotName = slotName ? slotName.content : `default`;
  19907. }
  19908. else {
  19909. hasDynamicSlots = true;
  19910. }
  19911. const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
  19912. // check if this slot is conditional (v-if/v-for)
  19913. let vIf;
  19914. let vElse;
  19915. let vFor;
  19916. if ((vIf = findDir(slotElement, 'if'))) {
  19917. hasDynamicSlots = true;
  19918. dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback));
  19919. }
  19920. else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
  19921. // find adjacent v-if
  19922. let j = i;
  19923. let prev;
  19924. while (j--) {
  19925. prev = children[j];
  19926. if (prev.type !== 3 /* COMMENT */) {
  19927. break;
  19928. }
  19929. }
  19930. if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
  19931. // remove node
  19932. children.splice(i, 1);
  19933. i--;
  19934. // attach this slot to previous conditional
  19935. let conditional = dynamicSlots[dynamicSlots.length - 1];
  19936. while (conditional.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  19937. conditional = conditional.alternate;
  19938. }
  19939. conditional.alternate = vElse.exp
  19940. ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback)
  19941. : buildDynamicSlot(slotName, slotFunction);
  19942. }
  19943. else {
  19944. context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
  19945. }
  19946. }
  19947. else if ((vFor = findDir(slotElement, 'for'))) {
  19948. hasDynamicSlots = true;
  19949. const parseResult = vFor.parseResult ||
  19950. parseForExpression(vFor.exp, context);
  19951. if (parseResult) {
  19952. // Render the dynamic slots as an array and add it to the createSlot()
  19953. // args. The runtime knows how to handle it appropriately.
  19954. dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
  19955. parseResult.source,
  19956. createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
  19957. ]));
  19958. }
  19959. else {
  19960. context.onError(createCompilerError(32 /* X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
  19961. }
  19962. }
  19963. else {
  19964. // check duplicate static names
  19965. if (staticSlotName) {
  19966. if (seenSlotNames.has(staticSlotName)) {
  19967. context.onError(createCompilerError(38 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
  19968. continue;
  19969. }
  19970. seenSlotNames.add(staticSlotName);
  19971. if (staticSlotName === 'default') {
  19972. hasNamedDefaultSlot = true;
  19973. }
  19974. }
  19975. slotsProperties.push(createObjectProperty(slotName, slotFunction));
  19976. }
  19977. }
  19978. if (!onComponentSlot) {
  19979. const buildDefaultSlotProperty = (props, children) => {
  19980. const fn = buildSlotFn(props, children, loc);
  19981. return createObjectProperty(`default`, fn);
  19982. };
  19983. if (!hasTemplateSlots) {
  19984. // implicit default slot (on component)
  19985. slotsProperties.push(buildDefaultSlotProperty(undefined, children));
  19986. }
  19987. else if (implicitDefaultChildren.length &&
  19988. // #3766
  19989. // with whitespace: 'preserve', whitespaces between slots will end up in
  19990. // implicitDefaultChildren. Ignore if all implicit children are whitespaces.
  19991. implicitDefaultChildren.some(node => isNonWhitespaceContent(node))) {
  19992. // implicit default slot (mixed with named slots)
  19993. if (hasNamedDefaultSlot) {
  19994. context.onError(createCompilerError(39 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
  19995. }
  19996. else {
  19997. slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
  19998. }
  19999. }
  20000. }
  20001. const slotFlag = hasDynamicSlots
  20002. ? 2 /* DYNAMIC */
  20003. : hasForwardedSlots(node.children)
  20004. ? 3 /* FORWARDED */
  20005. : 1 /* STABLE */;
  20006. let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
  20007. // 2 = compiled but dynamic = can skip normalization, but must run diff
  20008. // 1 = compiled and static = can skip normalization AND diff as optimized
  20009. createSimpleExpression(slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
  20010. if (dynamicSlots.length) {
  20011. slots = createCallExpression(context.helper(CREATE_SLOTS), [
  20012. slots,
  20013. createArrayExpression(dynamicSlots)
  20014. ]);
  20015. }
  20016. return {
  20017. slots,
  20018. hasDynamicSlots
  20019. };
  20020. }
  20021. function buildDynamicSlot(name, fn) {
  20022. return createObjectExpression([
  20023. createObjectProperty(`name`, name),
  20024. createObjectProperty(`fn`, fn)
  20025. ]);
  20026. }
  20027. function hasForwardedSlots(children) {
  20028. for (let i = 0; i < children.length; i++) {
  20029. const child = children[i];
  20030. switch (child.type) {
  20031. case 1 /* ELEMENT */:
  20032. if (child.tagType === 2 /* SLOT */ ||
  20033. hasForwardedSlots(child.children)) {
  20034. return true;
  20035. }
  20036. break;
  20037. case 9 /* IF */:
  20038. if (hasForwardedSlots(child.branches))
  20039. return true;
  20040. break;
  20041. case 10 /* IF_BRANCH */:
  20042. case 11 /* FOR */:
  20043. if (hasForwardedSlots(child.children))
  20044. return true;
  20045. break;
  20046. }
  20047. }
  20048. return false;
  20049. }
  20050. function isNonWhitespaceContent(node) {
  20051. if (node.type !== 2 /* TEXT */ && node.type !== 12 /* TEXT_CALL */)
  20052. return true;
  20053. return node.type === 2 /* TEXT */
  20054. ? !!node.content.trim()
  20055. : isNonWhitespaceContent(node.content);
  20056. }
  20057. // some directive transforms (e.g. v-model) may return a symbol for runtime
  20058. // import, which should be used instead of a resolveDirective call.
  20059. const directiveImportMap = new WeakMap();
  20060. // generate a JavaScript AST for this element's codegen
  20061. const transformElement = (node, context) => {
  20062. // perform the work on exit, after all child expressions have been
  20063. // processed and merged.
  20064. return function postTransformElement() {
  20065. node = context.currentNode;
  20066. if (!(node.type === 1 /* ELEMENT */ &&
  20067. (node.tagType === 0 /* ELEMENT */ ||
  20068. node.tagType === 1 /* COMPONENT */))) {
  20069. return;
  20070. }
  20071. const { tag, props } = node;
  20072. const isComponent = node.tagType === 1 /* COMPONENT */;
  20073. // The goal of the transform is to create a codegenNode implementing the
  20074. // VNodeCall interface.
  20075. let vnodeTag = isComponent
  20076. ? resolveComponentType(node, context)
  20077. : `"${tag}"`;
  20078. const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
  20079. let vnodeProps;
  20080. let vnodeChildren;
  20081. let vnodePatchFlag;
  20082. let patchFlag = 0;
  20083. let vnodeDynamicProps;
  20084. let dynamicPropNames;
  20085. let vnodeDirectives;
  20086. let shouldUseBlock =
  20087. // dynamic component may resolve to plain elements
  20088. isDynamicComponent ||
  20089. vnodeTag === TELEPORT ||
  20090. vnodeTag === SUSPENSE ||
  20091. (!isComponent &&
  20092. // <svg> and <foreignObject> must be forced into blocks so that block
  20093. // updates inside get proper isSVG flag at runtime. (#639, #643)
  20094. // This is technically web-specific, but splitting the logic out of core
  20095. // leads to too much unnecessary complexity.
  20096. (tag === 'svg' || tag === 'foreignObject'));
  20097. // props
  20098. if (props.length > 0) {
  20099. const propsBuildResult = buildProps(node, context);
  20100. vnodeProps = propsBuildResult.props;
  20101. patchFlag = propsBuildResult.patchFlag;
  20102. dynamicPropNames = propsBuildResult.dynamicPropNames;
  20103. const directives = propsBuildResult.directives;
  20104. vnodeDirectives =
  20105. directives && directives.length
  20106. ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
  20107. : undefined;
  20108. if (propsBuildResult.shouldUseBlock) {
  20109. shouldUseBlock = true;
  20110. }
  20111. }
  20112. // children
  20113. if (node.children.length > 0) {
  20114. if (vnodeTag === KEEP_ALIVE) {
  20115. // Although a built-in component, we compile KeepAlive with raw children
  20116. // instead of slot functions so that it can be used inside Transition
  20117. // or other Transition-wrapping HOCs.
  20118. // To ensure correct updates with block optimizations, we need to:
  20119. // 1. Force keep-alive into a block. This avoids its children being
  20120. // collected by a parent block.
  20121. shouldUseBlock = true;
  20122. // 2. Force keep-alive to always be updated, since it uses raw children.
  20123. patchFlag |= 1024 /* DYNAMIC_SLOTS */;
  20124. if (node.children.length > 1) {
  20125. context.onError(createCompilerError(45 /* X_KEEP_ALIVE_INVALID_CHILDREN */, {
  20126. start: node.children[0].loc.start,
  20127. end: node.children[node.children.length - 1].loc.end,
  20128. source: ''
  20129. }));
  20130. }
  20131. }
  20132. const shouldBuildAsSlots = isComponent &&
  20133. // Teleport is not a real component and has dedicated runtime handling
  20134. vnodeTag !== TELEPORT &&
  20135. // explained above.
  20136. vnodeTag !== KEEP_ALIVE;
  20137. if (shouldBuildAsSlots) {
  20138. const { slots, hasDynamicSlots } = buildSlots(node, context);
  20139. vnodeChildren = slots;
  20140. if (hasDynamicSlots) {
  20141. patchFlag |= 1024 /* DYNAMIC_SLOTS */;
  20142. }
  20143. }
  20144. else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
  20145. const child = node.children[0];
  20146. const type = child.type;
  20147. // check for dynamic text children
  20148. const hasDynamicTextChild = type === 5 /* INTERPOLATION */ ||
  20149. type === 8 /* COMPOUND_EXPRESSION */;
  20150. if (hasDynamicTextChild &&
  20151. getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
  20152. patchFlag |= 1 /* TEXT */;
  20153. }
  20154. // pass directly if the only child is a text node
  20155. // (plain / interpolation / expression)
  20156. if (hasDynamicTextChild || type === 2 /* TEXT */) {
  20157. vnodeChildren = child;
  20158. }
  20159. else {
  20160. vnodeChildren = node.children;
  20161. }
  20162. }
  20163. else {
  20164. vnodeChildren = node.children;
  20165. }
  20166. }
  20167. // patchFlag & dynamicPropNames
  20168. if (patchFlag !== 0) {
  20169. {
  20170. if (patchFlag < 0) {
  20171. // special flags (negative and mutually exclusive)
  20172. vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
  20173. }
  20174. else {
  20175. // bitwise flags
  20176. const flagNames = Object.keys(PatchFlagNames)
  20177. .map(Number)
  20178. .filter(n => n > 0 && patchFlag & n)
  20179. .map(n => PatchFlagNames[n])
  20180. .join(`, `);
  20181. vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
  20182. }
  20183. }
  20184. if (dynamicPropNames && dynamicPropNames.length) {
  20185. vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
  20186. }
  20187. }
  20188. node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, isComponent, node.loc);
  20189. };
  20190. };
  20191. function resolveComponentType(node, context, ssr = false) {
  20192. let { tag } = node;
  20193. // 1. dynamic component
  20194. const isExplicitDynamic = isComponentTag(tag);
  20195. const isProp = findProp(node, 'is');
  20196. if (isProp) {
  20197. if (isExplicitDynamic ||
  20198. (false )) {
  20199. const exp = isProp.type === 6 /* ATTRIBUTE */
  20200. ? isProp.value && createSimpleExpression(isProp.value.content, true)
  20201. : isProp.exp;
  20202. if (exp) {
  20203. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  20204. exp
  20205. ]);
  20206. }
  20207. }
  20208. else if (isProp.type === 6 /* ATTRIBUTE */ &&
  20209. isProp.value.content.startsWith('vue:')) {
  20210. // <button is="vue:xxx">
  20211. // if not <component>, only is value that starts with "vue:" will be
  20212. // treated as component by the parse phase and reach here, unless it's
  20213. // compat mode where all is values are considered components
  20214. tag = isProp.value.content.slice(4);
  20215. }
  20216. }
  20217. // 1.5 v-is (TODO: Deprecate)
  20218. const isDir = !isExplicitDynamic && findDir(node, 'is');
  20219. if (isDir && isDir.exp) {
  20220. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  20221. isDir.exp
  20222. ]);
  20223. }
  20224. // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
  20225. const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
  20226. if (builtIn) {
  20227. // built-ins are simply fallthroughs / have special handling during ssr
  20228. // so we don't need to import their runtime equivalents
  20229. if (!ssr)
  20230. context.helper(builtIn);
  20231. return builtIn;
  20232. }
  20233. // 3. user component (from setup bindings)
  20234. // this is skipped in browser build since browser builds do not perform
  20235. // binding analysis.
  20236. {
  20237. const fromSetup = resolveSetupReference(tag, context);
  20238. if (fromSetup) {
  20239. return fromSetup;
  20240. }
  20241. const dotIndex = tag.indexOf('.');
  20242. if (dotIndex > 0) {
  20243. const ns = resolveSetupReference(tag.slice(0, dotIndex), context);
  20244. if (ns) {
  20245. return ns + tag.slice(dotIndex);
  20246. }
  20247. }
  20248. }
  20249. // 4. Self referencing component (inferred from filename)
  20250. if (context.selfName &&
  20251. capitalize(camelize(tag)) === context.selfName) {
  20252. context.helper(RESOLVE_COMPONENT);
  20253. // codegen.ts has special check for __self postfix when generating
  20254. // component imports, which will pass additional `maybeSelfReference` flag
  20255. // to `resolveComponent`.
  20256. context.components.add(tag + `__self`);
  20257. return toValidAssetId(tag, `component`);
  20258. }
  20259. // 5. user component (resolve)
  20260. context.helper(RESOLVE_COMPONENT);
  20261. context.components.add(tag);
  20262. return toValidAssetId(tag, `component`);
  20263. }
  20264. function resolveSetupReference(name, context) {
  20265. const bindings = context.bindingMetadata;
  20266. if (!bindings || bindings.__isScriptSetup === false) {
  20267. return;
  20268. }
  20269. const camelName = camelize(name);
  20270. const PascalName = capitalize(camelName);
  20271. const checkType = (type) => {
  20272. if (bindings[name] === type) {
  20273. return name;
  20274. }
  20275. if (bindings[camelName] === type) {
  20276. return camelName;
  20277. }
  20278. if (bindings[PascalName] === type) {
  20279. return PascalName;
  20280. }
  20281. };
  20282. const fromConst = checkType("setup-const" /* SETUP_CONST */);
  20283. if (fromConst) {
  20284. return context.inline
  20285. ? // in inline mode, const setup bindings (e.g. imports) can be used as-is
  20286. fromConst
  20287. : `$setup[${JSON.stringify(fromConst)}]`;
  20288. }
  20289. const fromMaybeRef = checkType("setup-let" /* SETUP_LET */) ||
  20290. checkType("setup-ref" /* SETUP_REF */) ||
  20291. checkType("setup-maybe-ref" /* SETUP_MAYBE_REF */);
  20292. if (fromMaybeRef) {
  20293. return context.inline
  20294. ? // setup scope bindings that may be refs need to be unrefed
  20295. `${context.helperString(UNREF)}(${fromMaybeRef})`
  20296. : `$setup[${JSON.stringify(fromMaybeRef)}]`;
  20297. }
  20298. }
  20299. function buildProps(node, context, props = node.props, ssr = false) {
  20300. const { tag, loc: elementLoc, children } = node;
  20301. const isComponent = node.tagType === 1 /* COMPONENT */;
  20302. let properties = [];
  20303. const mergeArgs = [];
  20304. const runtimeDirectives = [];
  20305. const hasChildren = children.length > 0;
  20306. let shouldUseBlock = false;
  20307. // patchFlag analysis
  20308. let patchFlag = 0;
  20309. let hasRef = false;
  20310. let hasClassBinding = false;
  20311. let hasStyleBinding = false;
  20312. let hasHydrationEventBinding = false;
  20313. let hasDynamicKeys = false;
  20314. let hasVnodeHook = false;
  20315. const dynamicPropNames = [];
  20316. const analyzePatchFlag = ({ key, value }) => {
  20317. if (isStaticExp(key)) {
  20318. const name = key.content;
  20319. const isEventHandler = isOn(name);
  20320. if (!isComponent &&
  20321. isEventHandler &&
  20322. // omit the flag for click handlers because hydration gives click
  20323. // dedicated fast path.
  20324. name.toLowerCase() !== 'onclick' &&
  20325. // omit v-model handlers
  20326. name !== 'onUpdate:modelValue' &&
  20327. // omit onVnodeXXX hooks
  20328. !isReservedProp(name)) {
  20329. hasHydrationEventBinding = true;
  20330. }
  20331. if (isEventHandler && isReservedProp(name)) {
  20332. hasVnodeHook = true;
  20333. }
  20334. if (value.type === 20 /* JS_CACHE_EXPRESSION */ ||
  20335. ((value.type === 4 /* SIMPLE_EXPRESSION */ ||
  20336. value.type === 8 /* COMPOUND_EXPRESSION */) &&
  20337. getConstantType(value, context) > 0)) {
  20338. // skip if the prop is a cached handler or has constant value
  20339. return;
  20340. }
  20341. if (name === 'ref') {
  20342. hasRef = true;
  20343. }
  20344. else if (name === 'class') {
  20345. hasClassBinding = true;
  20346. }
  20347. else if (name === 'style') {
  20348. hasStyleBinding = true;
  20349. }
  20350. else if (name !== 'key' && !dynamicPropNames.includes(name)) {
  20351. dynamicPropNames.push(name);
  20352. }
  20353. // treat the dynamic class and style binding of the component as dynamic props
  20354. if (isComponent &&
  20355. (name === 'class' || name === 'style') &&
  20356. !dynamicPropNames.includes(name)) {
  20357. dynamicPropNames.push(name);
  20358. }
  20359. }
  20360. else {
  20361. hasDynamicKeys = true;
  20362. }
  20363. };
  20364. for (let i = 0; i < props.length; i++) {
  20365. // static attribute
  20366. const prop = props[i];
  20367. if (prop.type === 6 /* ATTRIBUTE */) {
  20368. const { loc, name, value } = prop;
  20369. let isStatic = true;
  20370. if (name === 'ref') {
  20371. hasRef = true;
  20372. if (context.scopes.vFor > 0) {
  20373. properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
  20374. }
  20375. // in inline mode there is no setupState object, so we can't use string
  20376. // keys to set the ref. Instead, we need to transform it to pass the
  20377. // actual ref instead.
  20378. if (value &&
  20379. context.inline &&
  20380. context.bindingMetadata[value.content]) {
  20381. isStatic = false;
  20382. properties.push(createObjectProperty(createSimpleExpression('ref_key', true), createSimpleExpression(value.content, true, value.loc)));
  20383. }
  20384. }
  20385. // skip is on <component>, or is="vue:xxx"
  20386. if (name === 'is' &&
  20387. (isComponentTag(tag) ||
  20388. (value && value.content.startsWith('vue:')) ||
  20389. (false ))) {
  20390. continue;
  20391. }
  20392. properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', isStatic, value ? value.loc : loc)));
  20393. }
  20394. else {
  20395. // directives
  20396. const { name, arg, exp, loc } = prop;
  20397. const isVBind = name === 'bind';
  20398. const isVOn = name === 'on';
  20399. // skip v-slot - it is handled by its dedicated transform.
  20400. if (name === 'slot') {
  20401. if (!isComponent) {
  20402. context.onError(createCompilerError(40 /* X_V_SLOT_MISPLACED */, loc));
  20403. }
  20404. continue;
  20405. }
  20406. // skip v-once/v-memo - they are handled by dedicated transforms.
  20407. if (name === 'once' || name === 'memo') {
  20408. continue;
  20409. }
  20410. // skip v-is and :is on <component>
  20411. if (name === 'is' ||
  20412. (isVBind &&
  20413. isStaticArgOf(arg, 'is') &&
  20414. (isComponentTag(tag) ||
  20415. (false )))) {
  20416. continue;
  20417. }
  20418. // skip v-on in SSR compilation
  20419. if (isVOn && ssr) {
  20420. continue;
  20421. }
  20422. if (
  20423. // #938: elements with dynamic keys should be forced into blocks
  20424. (isVBind && isStaticArgOf(arg, 'key')) ||
  20425. // inline before-update hooks need to force block so that it is invoked
  20426. // before children
  20427. (isVOn && hasChildren && isStaticArgOf(arg, 'vue:before-update'))) {
  20428. shouldUseBlock = true;
  20429. }
  20430. if (isVBind && isStaticArgOf(arg, 'ref') && context.scopes.vFor > 0) {
  20431. properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
  20432. }
  20433. // special case for v-bind and v-on with no argument
  20434. if (!arg && (isVBind || isVOn)) {
  20435. hasDynamicKeys = true;
  20436. if (exp) {
  20437. if (properties.length) {
  20438. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  20439. properties = [];
  20440. }
  20441. if (isVBind) {
  20442. mergeArgs.push(exp);
  20443. }
  20444. else {
  20445. // v-on="obj" -> toHandlers(obj)
  20446. mergeArgs.push({
  20447. type: 14 /* JS_CALL_EXPRESSION */,
  20448. loc,
  20449. callee: context.helper(TO_HANDLERS),
  20450. arguments: [exp]
  20451. });
  20452. }
  20453. }
  20454. else {
  20455. context.onError(createCompilerError(isVBind
  20456. ? 34 /* X_V_BIND_NO_EXPRESSION */
  20457. : 35 /* X_V_ON_NO_EXPRESSION */, loc));
  20458. }
  20459. continue;
  20460. }
  20461. const directiveTransform = context.directiveTransforms[name];
  20462. if (directiveTransform) {
  20463. // has built-in directive transform.
  20464. const { props, needRuntime } = directiveTransform(prop, node, context);
  20465. !ssr && props.forEach(analyzePatchFlag);
  20466. properties.push(...props);
  20467. if (needRuntime) {
  20468. runtimeDirectives.push(prop);
  20469. if (isSymbol(needRuntime)) {
  20470. directiveImportMap.set(prop, needRuntime);
  20471. }
  20472. }
  20473. }
  20474. else {
  20475. // no built-in transform, this is a user custom directive.
  20476. runtimeDirectives.push(prop);
  20477. // custom dirs may use beforeUpdate so they need to force blocks
  20478. // to ensure before-update gets called before children update
  20479. if (hasChildren) {
  20480. shouldUseBlock = true;
  20481. }
  20482. }
  20483. }
  20484. }
  20485. let propsExpression = undefined;
  20486. // has v-bind="object" or v-on="object", wrap with mergeProps
  20487. if (mergeArgs.length) {
  20488. if (properties.length) {
  20489. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  20490. }
  20491. if (mergeArgs.length > 1) {
  20492. propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
  20493. }
  20494. else {
  20495. // single v-bind with nothing else - no need for a mergeProps call
  20496. propsExpression = mergeArgs[0];
  20497. }
  20498. }
  20499. else if (properties.length) {
  20500. propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
  20501. }
  20502. // patchFlag analysis
  20503. if (hasDynamicKeys) {
  20504. patchFlag |= 16 /* FULL_PROPS */;
  20505. }
  20506. else {
  20507. if (hasClassBinding && !isComponent) {
  20508. patchFlag |= 2 /* CLASS */;
  20509. }
  20510. if (hasStyleBinding && !isComponent) {
  20511. patchFlag |= 4 /* STYLE */;
  20512. }
  20513. if (dynamicPropNames.length) {
  20514. patchFlag |= 8 /* PROPS */;
  20515. }
  20516. if (hasHydrationEventBinding) {
  20517. patchFlag |= 32 /* HYDRATE_EVENTS */;
  20518. }
  20519. }
  20520. if (!shouldUseBlock &&
  20521. (patchFlag === 0 || patchFlag === 32 /* HYDRATE_EVENTS */) &&
  20522. (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
  20523. patchFlag |= 512 /* NEED_PATCH */;
  20524. }
  20525. // pre-normalize props, SSR is skipped for now
  20526. if (!context.inSSR && propsExpression) {
  20527. switch (propsExpression.type) {
  20528. case 15 /* JS_OBJECT_EXPRESSION */:
  20529. // means that there is no v-bind,
  20530. // but still need to deal with dynamic key binding
  20531. let classKeyIndex = -1;
  20532. let styleKeyIndex = -1;
  20533. let hasDynamicKey = false;
  20534. for (let i = 0; i < propsExpression.properties.length; i++) {
  20535. const key = propsExpression.properties[i].key;
  20536. if (isStaticExp(key)) {
  20537. if (key.content === 'class') {
  20538. classKeyIndex = i;
  20539. }
  20540. else if (key.content === 'style') {
  20541. styleKeyIndex = i;
  20542. }
  20543. }
  20544. else if (!key.isHandlerKey) {
  20545. hasDynamicKey = true;
  20546. }
  20547. }
  20548. const classProp = propsExpression.properties[classKeyIndex];
  20549. const styleProp = propsExpression.properties[styleKeyIndex];
  20550. // no dynamic key
  20551. if (!hasDynamicKey) {
  20552. if (classProp && !isStaticExp(classProp.value)) {
  20553. classProp.value = createCallExpression(context.helper(NORMALIZE_CLASS), [classProp.value]);
  20554. }
  20555. if (styleProp &&
  20556. !isStaticExp(styleProp.value) &&
  20557. // the static style is compiled into an object,
  20558. // so use `hasStyleBinding` to ensure that it is a dynamic style binding
  20559. (hasStyleBinding ||
  20560. // v-bind:style and style both exist,
  20561. // v-bind:style with static literal object
  20562. styleProp.value.type === 17 /* JS_ARRAY_EXPRESSION */)) {
  20563. styleProp.value = createCallExpression(context.helper(NORMALIZE_STYLE), [styleProp.value]);
  20564. }
  20565. }
  20566. else {
  20567. // dynamic key binding, wrap with `normalizeProps`
  20568. propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [propsExpression]);
  20569. }
  20570. break;
  20571. case 14 /* JS_CALL_EXPRESSION */:
  20572. // mergeProps call, do nothing
  20573. break;
  20574. default:
  20575. // single v-bind
  20576. propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [
  20577. createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [
  20578. propsExpression
  20579. ])
  20580. ]);
  20581. break;
  20582. }
  20583. }
  20584. return {
  20585. props: propsExpression,
  20586. directives: runtimeDirectives,
  20587. patchFlag,
  20588. dynamicPropNames,
  20589. shouldUseBlock
  20590. };
  20591. }
  20592. // Dedupe props in an object literal.
  20593. // Literal duplicated attributes would have been warned during the parse phase,
  20594. // however, it's possible to encounter duplicated `onXXX` handlers with different
  20595. // modifiers. We also need to merge static and dynamic class / style attributes.
  20596. // - onXXX handlers / style: merge into array
  20597. // - class: merge into single expression with concatenation
  20598. function dedupeProperties(properties) {
  20599. const knownProps = new Map();
  20600. const deduped = [];
  20601. for (let i = 0; i < properties.length; i++) {
  20602. const prop = properties[i];
  20603. // dynamic keys are always allowed
  20604. if (prop.key.type === 8 /* COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
  20605. deduped.push(prop);
  20606. continue;
  20607. }
  20608. const name = prop.key.content;
  20609. const existing = knownProps.get(name);
  20610. if (existing) {
  20611. if (name === 'style' || name === 'class' || isOn(name)) {
  20612. mergeAsArray(existing, prop);
  20613. }
  20614. // unexpected duplicate, should have emitted error during parse
  20615. }
  20616. else {
  20617. knownProps.set(name, prop);
  20618. deduped.push(prop);
  20619. }
  20620. }
  20621. return deduped;
  20622. }
  20623. function mergeAsArray(existing, incoming) {
  20624. if (existing.value.type === 17 /* JS_ARRAY_EXPRESSION */) {
  20625. existing.value.elements.push(incoming.value);
  20626. }
  20627. else {
  20628. existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
  20629. }
  20630. }
  20631. function buildDirectiveArgs(dir, context) {
  20632. const dirArgs = [];
  20633. const runtime = directiveImportMap.get(dir);
  20634. if (runtime) {
  20635. // built-in directive with runtime
  20636. dirArgs.push(context.helperString(runtime));
  20637. }
  20638. else {
  20639. // user directive.
  20640. // see if we have directives exposed via <script setup>
  20641. const fromSetup = resolveSetupReference('v-' + dir.name, context);
  20642. if (fromSetup) {
  20643. dirArgs.push(fromSetup);
  20644. }
  20645. else {
  20646. // inject statement for resolving directive
  20647. context.helper(RESOLVE_DIRECTIVE);
  20648. context.directives.add(dir.name);
  20649. dirArgs.push(toValidAssetId(dir.name, `directive`));
  20650. }
  20651. }
  20652. const { loc } = dir;
  20653. if (dir.exp)
  20654. dirArgs.push(dir.exp);
  20655. if (dir.arg) {
  20656. if (!dir.exp) {
  20657. dirArgs.push(`void 0`);
  20658. }
  20659. dirArgs.push(dir.arg);
  20660. }
  20661. if (Object.keys(dir.modifiers).length) {
  20662. if (!dir.arg) {
  20663. if (!dir.exp) {
  20664. dirArgs.push(`void 0`);
  20665. }
  20666. dirArgs.push(`void 0`);
  20667. }
  20668. const trueExpression = createSimpleExpression(`true`, false, loc);
  20669. dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
  20670. }
  20671. return createArrayExpression(dirArgs, dir.loc);
  20672. }
  20673. function stringifyDynamicPropNames(props) {
  20674. let propsNamesString = `[`;
  20675. for (let i = 0, l = props.length; i < l; i++) {
  20676. propsNamesString += JSON.stringify(props[i]);
  20677. if (i < l - 1)
  20678. propsNamesString += ', ';
  20679. }
  20680. return propsNamesString + `]`;
  20681. }
  20682. function isComponentTag(tag) {
  20683. return tag === 'component' || tag === 'Component';
  20684. }
  20685. const transformSlotOutlet = (node, context) => {
  20686. if (isSlotOutlet(node)) {
  20687. const { children, loc } = node;
  20688. const { slotName, slotProps } = processSlotOutlet(node, context);
  20689. const slotArgs = [
  20690. context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
  20691. slotName,
  20692. '{}',
  20693. 'undefined',
  20694. 'true'
  20695. ];
  20696. let expectedLen = 2;
  20697. if (slotProps) {
  20698. slotArgs[2] = slotProps;
  20699. expectedLen = 3;
  20700. }
  20701. if (children.length) {
  20702. slotArgs[3] = createFunctionExpression([], children, false, false, loc);
  20703. expectedLen = 4;
  20704. }
  20705. if (context.scopeId && !context.slotted) {
  20706. expectedLen = 5;
  20707. }
  20708. slotArgs.splice(expectedLen); // remove unused arguments
  20709. node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
  20710. }
  20711. };
  20712. function processSlotOutlet(node, context) {
  20713. let slotName = `"default"`;
  20714. let slotProps = undefined;
  20715. const nonNameProps = [];
  20716. for (let i = 0; i < node.props.length; i++) {
  20717. const p = node.props[i];
  20718. if (p.type === 6 /* ATTRIBUTE */) {
  20719. if (p.value) {
  20720. if (p.name === 'name') {
  20721. slotName = JSON.stringify(p.value.content);
  20722. }
  20723. else {
  20724. p.name = camelize(p.name);
  20725. nonNameProps.push(p);
  20726. }
  20727. }
  20728. }
  20729. else {
  20730. if (p.name === 'bind' && isStaticArgOf(p.arg, 'name')) {
  20731. if (p.exp)
  20732. slotName = p.exp;
  20733. }
  20734. else {
  20735. if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
  20736. p.arg.content = camelize(p.arg.content);
  20737. }
  20738. nonNameProps.push(p);
  20739. }
  20740. }
  20741. }
  20742. if (nonNameProps.length > 0) {
  20743. const { props, directives } = buildProps(node, context, nonNameProps);
  20744. slotProps = props;
  20745. if (directives.length) {
  20746. context.onError(createCompilerError(36 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
  20747. }
  20748. }
  20749. return {
  20750. slotName,
  20751. slotProps
  20752. };
  20753. }
  20754. const fnExpRE = /^\s*([\w$_]+|(async\s*)?\([^)]*?\))\s*=>|^\s*(async\s+)?function(?:\s+[\w$]+)?\s*\(/;
  20755. const transformOn = (dir, node, context, augmentor) => {
  20756. const { loc, modifiers, arg } = dir;
  20757. if (!dir.exp && !modifiers.length) {
  20758. context.onError(createCompilerError(35 /* X_V_ON_NO_EXPRESSION */, loc));
  20759. }
  20760. let eventName;
  20761. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  20762. if (arg.isStatic) {
  20763. let rawName = arg.content;
  20764. // TODO deprecate @vnodeXXX usage
  20765. if (rawName.startsWith('vue:')) {
  20766. rawName = `vnode-${rawName.slice(4)}`;
  20767. }
  20768. // for all event listeners, auto convert it to camelCase. See issue #2249
  20769. eventName = createSimpleExpression(toHandlerKey(camelize(rawName)), true, arg.loc);
  20770. }
  20771. else {
  20772. // #2388
  20773. eventName = createCompoundExpression([
  20774. `${context.helperString(TO_HANDLER_KEY)}(`,
  20775. arg,
  20776. `)`
  20777. ]);
  20778. }
  20779. }
  20780. else {
  20781. // already a compound expression.
  20782. eventName = arg;
  20783. eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
  20784. eventName.children.push(`)`);
  20785. }
  20786. // handler processing
  20787. let exp = dir.exp;
  20788. if (exp && !exp.content.trim()) {
  20789. exp = undefined;
  20790. }
  20791. let shouldCache = context.cacheHandlers && !exp && !context.inVOnce;
  20792. if (exp) {
  20793. const isMemberExp = isMemberExpression(exp.content, context);
  20794. const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
  20795. const hasMultipleStatements = exp.content.includes(`;`);
  20796. // process the expression since it's been skipped
  20797. if (context.prefixIdentifiers) {
  20798. isInlineStatement && context.addIdentifiers(`$event`);
  20799. exp = dir.exp = processExpression(exp, context, false, hasMultipleStatements);
  20800. isInlineStatement && context.removeIdentifiers(`$event`);
  20801. // with scope analysis, the function is hoistable if it has no reference
  20802. // to scope variables.
  20803. shouldCache =
  20804. context.cacheHandlers &&
  20805. // unnecessary to cache inside v-once
  20806. !context.inVOnce &&
  20807. // runtime constants don't need to be cached
  20808. // (this is analyzed by compileScript in SFC <script setup>)
  20809. !(exp.type === 4 /* SIMPLE_EXPRESSION */ && exp.constType > 0) &&
  20810. // #1541 bail if this is a member exp handler passed to a component -
  20811. // we need to use the original function to preserve arity,
  20812. // e.g. <transition> relies on checking cb.length to determine
  20813. // transition end handling. Inline function is ok since its arity
  20814. // is preserved even when cached.
  20815. !(isMemberExp && node.tagType === 1 /* COMPONENT */) &&
  20816. // bail if the function references closure variables (v-for, v-slot)
  20817. // it must be passed fresh to avoid stale values.
  20818. !hasScopeRef(exp, context.identifiers);
  20819. // If the expression is optimizable and is a member expression pointing
  20820. // to a function, turn it into invocation (and wrap in an arrow function
  20821. // below) so that it always accesses the latest value when called - thus
  20822. // avoiding the need to be patched.
  20823. if (shouldCache && isMemberExp) {
  20824. if (exp.type === 4 /* SIMPLE_EXPRESSION */) {
  20825. exp.content = `${exp.content} && ${exp.content}(...args)`;
  20826. }
  20827. else {
  20828. exp.children = [...exp.children, ` && `, ...exp.children, `(...args)`];
  20829. }
  20830. }
  20831. }
  20832. if (isInlineStatement || (shouldCache && isMemberExp)) {
  20833. // wrap inline statement in a function expression
  20834. exp = createCompoundExpression([
  20835. `${isInlineStatement
  20836. ? context.isTS
  20837. ? `($event: any)`
  20838. : `$event`
  20839. : `${context.isTS ? `\n//@ts-ignore\n` : ``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
  20840. exp,
  20841. hasMultipleStatements ? `}` : `)`
  20842. ]);
  20843. }
  20844. }
  20845. let ret = {
  20846. props: [
  20847. createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
  20848. ]
  20849. };
  20850. // apply extended compiler augmentor
  20851. if (augmentor) {
  20852. ret = augmentor(ret);
  20853. }
  20854. if (shouldCache) {
  20855. // cache handlers so that it's always the same handler being passed down.
  20856. // this avoids unnecessary re-renders when users use inline handlers on
  20857. // components.
  20858. ret.props[0].value = context.cache(ret.props[0].value);
  20859. }
  20860. // mark the key as handler for props normalization check
  20861. ret.props.forEach(p => (p.key.isHandlerKey = true));
  20862. return ret;
  20863. };
  20864. // v-bind without arg is handled directly in ./transformElements.ts due to it affecting
  20865. // codegen for the entire props object. This transform here is only for v-bind
  20866. // *with* args.
  20867. const transformBind = (dir, _node, context) => {
  20868. const { exp, modifiers, loc } = dir;
  20869. const arg = dir.arg;
  20870. if (arg.type !== 4 /* SIMPLE_EXPRESSION */) {
  20871. arg.children.unshift(`(`);
  20872. arg.children.push(`) || ""`);
  20873. }
  20874. else if (!arg.isStatic) {
  20875. arg.content = `${arg.content} || ""`;
  20876. }
  20877. // .sync is replaced by v-model:arg
  20878. if (modifiers.includes('camel')) {
  20879. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  20880. if (arg.isStatic) {
  20881. arg.content = camelize(arg.content);
  20882. }
  20883. else {
  20884. arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
  20885. }
  20886. }
  20887. else {
  20888. arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
  20889. arg.children.push(`)`);
  20890. }
  20891. }
  20892. if (!context.inSSR) {
  20893. if (modifiers.includes('prop')) {
  20894. injectPrefix(arg, '.');
  20895. }
  20896. if (modifiers.includes('attr')) {
  20897. injectPrefix(arg, '^');
  20898. }
  20899. }
  20900. if (!exp ||
  20901. (exp.type === 4 /* SIMPLE_EXPRESSION */ && !exp.content.trim())) {
  20902. context.onError(createCompilerError(34 /* X_V_BIND_NO_EXPRESSION */, loc));
  20903. return {
  20904. props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
  20905. };
  20906. }
  20907. return {
  20908. props: [createObjectProperty(arg, exp)]
  20909. };
  20910. };
  20911. const injectPrefix = (arg, prefix) => {
  20912. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  20913. if (arg.isStatic) {
  20914. arg.content = prefix + arg.content;
  20915. }
  20916. else {
  20917. arg.content = `\`${prefix}\${${arg.content}}\``;
  20918. }
  20919. }
  20920. else {
  20921. arg.children.unshift(`'${prefix}' + (`);
  20922. arg.children.push(`)`);
  20923. }
  20924. };
  20925. // Merge adjacent text nodes and expressions into a single expression
  20926. // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
  20927. const transformText = (node, context) => {
  20928. if (node.type === 0 /* ROOT */ ||
  20929. node.type === 1 /* ELEMENT */ ||
  20930. node.type === 11 /* FOR */ ||
  20931. node.type === 10 /* IF_BRANCH */) {
  20932. // perform the transform on node exit so that all expressions have already
  20933. // been processed.
  20934. return () => {
  20935. const children = node.children;
  20936. let currentContainer = undefined;
  20937. let hasText = false;
  20938. for (let i = 0; i < children.length; i++) {
  20939. const child = children[i];
  20940. if (isText(child)) {
  20941. hasText = true;
  20942. for (let j = i + 1; j < children.length; j++) {
  20943. const next = children[j];
  20944. if (isText(next)) {
  20945. if (!currentContainer) {
  20946. currentContainer = children[i] = {
  20947. type: 8 /* COMPOUND_EXPRESSION */,
  20948. loc: child.loc,
  20949. children: [child]
  20950. };
  20951. }
  20952. // merge adjacent text node into current
  20953. currentContainer.children.push(` + `, next);
  20954. children.splice(j, 1);
  20955. j--;
  20956. }
  20957. else {
  20958. currentContainer = undefined;
  20959. break;
  20960. }
  20961. }
  20962. }
  20963. }
  20964. if (!hasText ||
  20965. // if this is a plain element with a single text child, leave it
  20966. // as-is since the runtime has dedicated fast path for this by directly
  20967. // setting textContent of the element.
  20968. // for component root it's always normalized anyway.
  20969. (children.length === 1 &&
  20970. (node.type === 0 /* ROOT */ ||
  20971. (node.type === 1 /* ELEMENT */ &&
  20972. node.tagType === 0 /* ELEMENT */ &&
  20973. // #3756
  20974. // custom directives can potentially add DOM elements arbitrarily,
  20975. // we need to avoid setting textContent of the element at runtime
  20976. // to avoid accidentally overwriting the DOM elements added
  20977. // by the user through custom directives.
  20978. !node.props.find(p => p.type === 7 /* DIRECTIVE */ &&
  20979. !context.directiveTransforms[p.name]) &&
  20980. // in compat mode, <template> tags with no special directives
  20981. // will be rendered as a fragment so its children must be
  20982. // converted into vnodes.
  20983. !(false ))))) {
  20984. return;
  20985. }
  20986. // pre-convert text nodes into createTextVNode(text) calls to avoid
  20987. // runtime normalization.
  20988. for (let i = 0; i < children.length; i++) {
  20989. const child = children[i];
  20990. if (isText(child) || child.type === 8 /* COMPOUND_EXPRESSION */) {
  20991. const callArgs = [];
  20992. // createTextVNode defaults to single whitespace, so if it is a
  20993. // single space the code could be an empty call to save bytes.
  20994. if (child.type !== 2 /* TEXT */ || child.content !== ' ') {
  20995. callArgs.push(child);
  20996. }
  20997. // mark dynamic text with flag so it gets patched inside a block
  20998. if (!context.ssr &&
  20999. getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
  21000. callArgs.push(1 /* TEXT */ +
  21001. (` /* ${PatchFlagNames[1 /* TEXT */]} */` ));
  21002. }
  21003. children[i] = {
  21004. type: 12 /* TEXT_CALL */,
  21005. content: child,
  21006. loc: child.loc,
  21007. codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
  21008. };
  21009. }
  21010. }
  21011. };
  21012. }
  21013. };
  21014. const seen = new WeakSet();
  21015. const transformOnce = (node, context) => {
  21016. if (node.type === 1 /* ELEMENT */ && findDir(node, 'once', true)) {
  21017. if (seen.has(node) || context.inVOnce) {
  21018. return;
  21019. }
  21020. seen.add(node);
  21021. context.inVOnce = true;
  21022. context.helper(SET_BLOCK_TRACKING);
  21023. return () => {
  21024. context.inVOnce = false;
  21025. const cur = context.currentNode;
  21026. if (cur.codegenNode) {
  21027. cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
  21028. }
  21029. };
  21030. }
  21031. };
  21032. const transformModel = (dir, node, context) => {
  21033. const { exp, arg } = dir;
  21034. if (!exp) {
  21035. context.onError(createCompilerError(41 /* X_V_MODEL_NO_EXPRESSION */, dir.loc));
  21036. return createTransformProps();
  21037. }
  21038. const rawExp = exp.loc.source;
  21039. const expString = exp.type === 4 /* SIMPLE_EXPRESSION */ ? exp.content : rawExp;
  21040. // im SFC <script setup> inline mode, the exp may have been transformed into
  21041. // _unref(exp)
  21042. const bindingType = context.bindingMetadata[rawExp];
  21043. const maybeRef = context.inline &&
  21044. bindingType &&
  21045. bindingType !== "setup-const" /* SETUP_CONST */;
  21046. if (!expString.trim() ||
  21047. (!isMemberExpression(expString, context) && !maybeRef)) {
  21048. context.onError(createCompilerError(42 /* X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
  21049. return createTransformProps();
  21050. }
  21051. if (context.prefixIdentifiers &&
  21052. isSimpleIdentifier(expString) &&
  21053. context.identifiers[expString]) {
  21054. context.onError(createCompilerError(43 /* X_V_MODEL_ON_SCOPE_VARIABLE */, exp.loc));
  21055. return createTransformProps();
  21056. }
  21057. const propName = arg ? arg : createSimpleExpression('modelValue', true);
  21058. const eventName = arg
  21059. ? isStaticExp(arg)
  21060. ? `onUpdate:${arg.content}`
  21061. : createCompoundExpression(['"onUpdate:" + ', arg])
  21062. : `onUpdate:modelValue`;
  21063. let assignmentExp;
  21064. const eventArg = context.isTS ? `($event: any)` : `$event`;
  21065. if (maybeRef) {
  21066. if (bindingType === "setup-ref" /* SETUP_REF */) {
  21067. // v-model used on known ref.
  21068. assignmentExp = createCompoundExpression([
  21069. `${eventArg} => ((`,
  21070. createSimpleExpression(rawExp, false, exp.loc),
  21071. `).value = $event)`
  21072. ]);
  21073. }
  21074. else {
  21075. // v-model used on a potentially ref binding in <script setup> inline mode.
  21076. // the assignment needs to check whether the binding is actually a ref.
  21077. const altAssignment = bindingType === "setup-let" /* SETUP_LET */ ? `${rawExp} = $event` : `null`;
  21078. assignmentExp = createCompoundExpression([
  21079. `${eventArg} => (${context.helperString(IS_REF)}(${rawExp}) ? (`,
  21080. createSimpleExpression(rawExp, false, exp.loc),
  21081. `).value = $event : ${altAssignment})`
  21082. ]);
  21083. }
  21084. }
  21085. else {
  21086. assignmentExp = createCompoundExpression([
  21087. `${eventArg} => ((`,
  21088. exp,
  21089. `) = $event)`
  21090. ]);
  21091. }
  21092. const props = [
  21093. // modelValue: foo
  21094. createObjectProperty(propName, dir.exp),
  21095. // "onUpdate:modelValue": $event => (foo = $event)
  21096. createObjectProperty(eventName, assignmentExp)
  21097. ];
  21098. // cache v-model handler if applicable (when it doesn't refer any scope vars)
  21099. if (context.prefixIdentifiers &&
  21100. !context.inVOnce &&
  21101. context.cacheHandlers &&
  21102. !hasScopeRef(exp, context.identifiers)) {
  21103. props[1].value = context.cache(props[1].value);
  21104. }
  21105. // modelModifiers: { foo: true, "bar-baz": true }
  21106. if (dir.modifiers.length && node.tagType === 1 /* COMPONENT */) {
  21107. const modifiers = dir.modifiers
  21108. .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
  21109. .join(`, `);
  21110. const modifiersKey = arg
  21111. ? isStaticExp(arg)
  21112. ? `${arg.content}Modifiers`
  21113. : createCompoundExpression([arg, ' + "Modifiers"'])
  21114. : `modelModifiers`;
  21115. props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* CAN_HOIST */)));
  21116. }
  21117. return createTransformProps(props);
  21118. };
  21119. function createTransformProps(props = []) {
  21120. return { props };
  21121. }
  21122. const seen$1 = new WeakSet();
  21123. const transformMemo = (node, context) => {
  21124. if (node.type === 1 /* ELEMENT */) {
  21125. const dir = findDir(node, 'memo');
  21126. if (!dir || seen$1.has(node)) {
  21127. return;
  21128. }
  21129. seen$1.add(node);
  21130. return () => {
  21131. const codegenNode = node.codegenNode ||
  21132. context.currentNode.codegenNode;
  21133. if (codegenNode && codegenNode.type === 13 /* VNODE_CALL */) {
  21134. // non-component sub tree should be turned into a block
  21135. if (node.tagType !== 1 /* COMPONENT */) {
  21136. makeBlock(codegenNode, context);
  21137. }
  21138. node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [
  21139. dir.exp,
  21140. createFunctionExpression(undefined, codegenNode),
  21141. `_cache`,
  21142. String(context.cached++)
  21143. ]);
  21144. }
  21145. };
  21146. }
  21147. };
  21148. function getBaseTransformPreset(prefixIdentifiers) {
  21149. return [
  21150. [
  21151. transformOnce,
  21152. transformIf,
  21153. transformMemo,
  21154. transformFor,
  21155. ...([]),
  21156. ...(prefixIdentifiers
  21157. ? [
  21158. // order is important
  21159. trackVForSlotScopes,
  21160. transformExpression
  21161. ]
  21162. : []),
  21163. transformSlotOutlet,
  21164. transformElement,
  21165. trackSlotScopes,
  21166. transformText
  21167. ],
  21168. {
  21169. on: transformOn,
  21170. bind: transformBind,
  21171. model: transformModel
  21172. }
  21173. ];
  21174. }
  21175. // we name it `baseCompile` so that higher order compilers like
  21176. // @vue/compiler-dom can export `compile` while re-exporting everything else.
  21177. function baseCompile(template, options = {}) {
  21178. const onError = options.onError || defaultOnError;
  21179. const isModuleMode = options.mode === 'module';
  21180. const prefixIdentifiers = (options.prefixIdentifiers === true || isModuleMode);
  21181. if (!prefixIdentifiers && options.cacheHandlers) {
  21182. onError(createCompilerError(48 /* X_CACHE_HANDLER_NOT_SUPPORTED */));
  21183. }
  21184. if (options.scopeId && !isModuleMode) {
  21185. onError(createCompilerError(49 /* X_SCOPE_ID_NOT_SUPPORTED */));
  21186. }
  21187. const ast = isString(template) ? baseParse(template, options) : template;
  21188. const [nodeTransforms, directiveTransforms] = getBaseTransformPreset(prefixIdentifiers);
  21189. if (options.isTS) {
  21190. const { expressionPlugins } = options;
  21191. if (!expressionPlugins || !expressionPlugins.includes('typescript')) {
  21192. options.expressionPlugins = [...(expressionPlugins || []), 'typescript'];
  21193. }
  21194. }
  21195. transform(ast, extend({}, options, {
  21196. prefixIdentifiers,
  21197. nodeTransforms: [
  21198. ...nodeTransforms,
  21199. ...(options.nodeTransforms || []) // user transforms
  21200. ],
  21201. directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
  21202. )
  21203. }));
  21204. return generate(ast, extend({}, options, {
  21205. prefixIdentifiers
  21206. }));
  21207. }
  21208. const noopDirectiveTransform = () => ({ props: [] });
  21209. const V_MODEL_RADIO = Symbol(`vModelRadio` );
  21210. const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` );
  21211. const V_MODEL_TEXT = Symbol(`vModelText` );
  21212. const V_MODEL_SELECT = Symbol(`vModelSelect` );
  21213. const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` );
  21214. const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` );
  21215. const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` );
  21216. const V_SHOW = Symbol(`vShow` );
  21217. const TRANSITION = Symbol(`Transition` );
  21218. const TRANSITION_GROUP = Symbol(`TransitionGroup` );
  21219. registerRuntimeHelpers({
  21220. [V_MODEL_RADIO]: `vModelRadio`,
  21221. [V_MODEL_CHECKBOX]: `vModelCheckbox`,
  21222. [V_MODEL_TEXT]: `vModelText`,
  21223. [V_MODEL_SELECT]: `vModelSelect`,
  21224. [V_MODEL_DYNAMIC]: `vModelDynamic`,
  21225. [V_ON_WITH_MODIFIERS]: `withModifiers`,
  21226. [V_ON_WITH_KEYS]: `withKeys`,
  21227. [V_SHOW]: `vShow`,
  21228. [TRANSITION]: `Transition`,
  21229. [TRANSITION_GROUP]: `TransitionGroup`
  21230. });
  21231. var namedCharacterReferences = {
  21232. GT: ">",
  21233. gt: ">",
  21234. LT: "<",
  21235. lt: "<",
  21236. "ac;": "∾",
  21237. "af;": "⁡",
  21238. AMP: "&",
  21239. amp: "&",
  21240. "ap;": "≈",
  21241. "DD;": "ⅅ",
  21242. "dd;": "ⅆ",
  21243. deg: "°",
  21244. "ee;": "ⅇ",
  21245. "eg;": "⪚",
  21246. "el;": "⪙",
  21247. ETH: "Ð",
  21248. eth: "ð",
  21249. "gE;": "≧",
  21250. "ge;": "≥",
  21251. "Gg;": "⋙",
  21252. "gg;": "≫",
  21253. "gl;": "≷",
  21254. "GT;": ">",
  21255. "Gt;": "≫",
  21256. "gt;": ">",
  21257. "ic;": "⁣",
  21258. "ii;": "ⅈ",
  21259. "Im;": "ℑ",
  21260. "in;": "∈",
  21261. "it;": "⁢",
  21262. "lE;": "≦",
  21263. "le;": "≤",
  21264. "lg;": "≶",
  21265. "Ll;": "⋘",
  21266. "ll;": "≪",
  21267. "LT;": "<",
  21268. "Lt;": "≪",
  21269. "lt;": "<",
  21270. "mp;": "∓",
  21271. "Mu;": "Μ",
  21272. "mu;": "μ",
  21273. "ne;": "≠",
  21274. "ni;": "∋",
  21275. not: "¬",
  21276. "Nu;": "Ν",
  21277. "nu;": "ν",
  21278. "Or;": "⩔",
  21279. "or;": "∨",
  21280. "oS;": "Ⓢ",
  21281. "Pi;": "Π",
  21282. "pi;": "π",
  21283. "pm;": "±",
  21284. "Pr;": "⪻",
  21285. "pr;": "≺",
  21286. "Re;": "ℜ",
  21287. REG: "®",
  21288. reg: "®",
  21289. "rx;": "℞",
  21290. "Sc;": "⪼",
  21291. "sc;": "≻",
  21292. shy: "­",
  21293. uml: "¨",
  21294. "wp;": "℘",
  21295. "wr;": "≀",
  21296. "Xi;": "Ξ",
  21297. "xi;": "ξ",
  21298. yen: "¥",
  21299. "acd;": "∿",
  21300. "acE;": "∾̳",
  21301. "Acy;": "А",
  21302. "acy;": "а",
  21303. "Afr;": "𝔄",
  21304. "afr;": "𝔞",
  21305. "AMP;": "&",
  21306. "amp;": "&",
  21307. "And;": "⩓",
  21308. "and;": "∧",
  21309. "ang;": "∠",
  21310. "apE;": "⩰",
  21311. "ape;": "≊",
  21312. "ast;": "*",
  21313. Auml: "Ä",
  21314. auml: "ä",
  21315. "Bcy;": "Б",
  21316. "bcy;": "б",
  21317. "Bfr;": "𝔅",
  21318. "bfr;": "𝔟",
  21319. "bne;": "=⃥",
  21320. "bot;": "⊥",
  21321. "Cap;": "⋒",
  21322. "cap;": "∩",
  21323. cent: "¢",
  21324. "Cfr;": "ℭ",
  21325. "cfr;": "𝔠",
  21326. "Chi;": "Χ",
  21327. "chi;": "χ",
  21328. "cir;": "○",
  21329. COPY: "©",
  21330. copy: "©",
  21331. "Cup;": "⋓",
  21332. "cup;": "∪",
  21333. "Dcy;": "Д",
  21334. "dcy;": "д",
  21335. "deg;": "°",
  21336. "Del;": "∇",
  21337. "Dfr;": "𝔇",
  21338. "dfr;": "𝔡",
  21339. "die;": "¨",
  21340. "div;": "÷",
  21341. "Dot;": "¨",
  21342. "dot;": "˙",
  21343. "Ecy;": "Э",
  21344. "ecy;": "э",
  21345. "Efr;": "𝔈",
  21346. "efr;": "𝔢",
  21347. "egs;": "⪖",
  21348. "ell;": "ℓ",
  21349. "els;": "⪕",
  21350. "ENG;": "Ŋ",
  21351. "eng;": "ŋ",
  21352. "Eta;": "Η",
  21353. "eta;": "η",
  21354. "ETH;": "Ð",
  21355. "eth;": "ð",
  21356. Euml: "Ë",
  21357. euml: "ë",
  21358. "Fcy;": "Ф",
  21359. "fcy;": "ф",
  21360. "Ffr;": "𝔉",
  21361. "ffr;": "𝔣",
  21362. "gap;": "⪆",
  21363. "Gcy;": "Г",
  21364. "gcy;": "г",
  21365. "gEl;": "⪌",
  21366. "gel;": "⋛",
  21367. "geq;": "≥",
  21368. "ges;": "⩾",
  21369. "Gfr;": "𝔊",
  21370. "gfr;": "𝔤",
  21371. "ggg;": "⋙",
  21372. "gla;": "⪥",
  21373. "glE;": "⪒",
  21374. "glj;": "⪤",
  21375. "gnE;": "≩",
  21376. "gne;": "⪈",
  21377. "Hat;": "^",
  21378. "Hfr;": "ℌ",
  21379. "hfr;": "𝔥",
  21380. "Icy;": "И",
  21381. "icy;": "и",
  21382. "iff;": "⇔",
  21383. "Ifr;": "ℑ",
  21384. "ifr;": "𝔦",
  21385. "Int;": "∬",
  21386. "int;": "∫",
  21387. Iuml: "Ï",
  21388. iuml: "ï",
  21389. "Jcy;": "Й",
  21390. "jcy;": "й",
  21391. "Jfr;": "𝔍",
  21392. "jfr;": "𝔧",
  21393. "Kcy;": "К",
  21394. "kcy;": "к",
  21395. "Kfr;": "𝔎",
  21396. "kfr;": "𝔨",
  21397. "lap;": "⪅",
  21398. "lat;": "⪫",
  21399. "Lcy;": "Л",
  21400. "lcy;": "л",
  21401. "lEg;": "⪋",
  21402. "leg;": "⋚",
  21403. "leq;": "≤",
  21404. "les;": "⩽",
  21405. "Lfr;": "𝔏",
  21406. "lfr;": "𝔩",
  21407. "lgE;": "⪑",
  21408. "lnE;": "≨",
  21409. "lne;": "⪇",
  21410. "loz;": "◊",
  21411. "lrm;": "‎",
  21412. "Lsh;": "↰",
  21413. "lsh;": "↰",
  21414. macr: "¯",
  21415. "Map;": "⤅",
  21416. "map;": "↦",
  21417. "Mcy;": "М",
  21418. "mcy;": "м",
  21419. "Mfr;": "𝔐",
  21420. "mfr;": "𝔪",
  21421. "mho;": "℧",
  21422. "mid;": "∣",
  21423. "nap;": "≉",
  21424. nbsp: " ",
  21425. "Ncy;": "Н",
  21426. "ncy;": "н",
  21427. "Nfr;": "𝔑",
  21428. "nfr;": "𝔫",
  21429. "ngE;": "≧̸",
  21430. "nge;": "≱",
  21431. "nGg;": "⋙̸",
  21432. "nGt;": "≫⃒",
  21433. "ngt;": "≯",
  21434. "nis;": "⋼",
  21435. "niv;": "∋",
  21436. "nlE;": "≦̸",
  21437. "nle;": "≰",
  21438. "nLl;": "⋘̸",
  21439. "nLt;": "≪⃒",
  21440. "nlt;": "≮",
  21441. "Not;": "⫬",
  21442. "not;": "¬",
  21443. "npr;": "⊀",
  21444. "nsc;": "⊁",
  21445. "num;": "#",
  21446. "Ocy;": "О",
  21447. "ocy;": "о",
  21448. "Ofr;": "𝔒",
  21449. "ofr;": "𝔬",
  21450. "ogt;": "⧁",
  21451. "ohm;": "Ω",
  21452. "olt;": "⧀",
  21453. "ord;": "⩝",
  21454. ordf: "ª",
  21455. ordm: "º",
  21456. "orv;": "⩛",
  21457. Ouml: "Ö",
  21458. ouml: "ö",
  21459. "par;": "∥",
  21460. para: "¶",
  21461. "Pcy;": "П",
  21462. "pcy;": "п",
  21463. "Pfr;": "𝔓",
  21464. "pfr;": "𝔭",
  21465. "Phi;": "Φ",
  21466. "phi;": "φ",
  21467. "piv;": "ϖ",
  21468. "prE;": "⪳",
  21469. "pre;": "⪯",
  21470. "Psi;": "Ψ",
  21471. "psi;": "ψ",
  21472. "Qfr;": "𝔔",
  21473. "qfr;": "𝔮",
  21474. QUOT: "\"",
  21475. quot: "\"",
  21476. "Rcy;": "Р",
  21477. "rcy;": "р",
  21478. "REG;": "®",
  21479. "reg;": "®",
  21480. "Rfr;": "ℜ",
  21481. "rfr;": "𝔯",
  21482. "Rho;": "Ρ",
  21483. "rho;": "ρ",
  21484. "rlm;": "‏",
  21485. "Rsh;": "↱",
  21486. "rsh;": "↱",
  21487. "scE;": "⪴",
  21488. "sce;": "⪰",
  21489. "Scy;": "С",
  21490. "scy;": "с",
  21491. sect: "§",
  21492. "Sfr;": "𝔖",
  21493. "sfr;": "𝔰",
  21494. "shy;": "­",
  21495. "sim;": "∼",
  21496. "smt;": "⪪",
  21497. "sol;": "/",
  21498. "squ;": "□",
  21499. "Sub;": "⋐",
  21500. "sub;": "⊂",
  21501. "Sum;": "∑",
  21502. "sum;": "∑",
  21503. "Sup;": "⋑",
  21504. "sup;": "⊃",
  21505. sup1: "¹",
  21506. sup2: "²",
  21507. sup3: "³",
  21508. "Tab;": "\t",
  21509. "Tau;": "Τ",
  21510. "tau;": "τ",
  21511. "Tcy;": "Т",
  21512. "tcy;": "т",
  21513. "Tfr;": "𝔗",
  21514. "tfr;": "𝔱",
  21515. "top;": "⊤",
  21516. "Ucy;": "У",
  21517. "ucy;": "у",
  21518. "Ufr;": "𝔘",
  21519. "ufr;": "𝔲",
  21520. "uml;": "¨",
  21521. Uuml: "Ü",
  21522. uuml: "ü",
  21523. "Vcy;": "В",
  21524. "vcy;": "в",
  21525. "Vee;": "⋁",
  21526. "vee;": "∨",
  21527. "Vfr;": "𝔙",
  21528. "vfr;": "𝔳",
  21529. "Wfr;": "𝔚",
  21530. "wfr;": "𝔴",
  21531. "Xfr;": "𝔛",
  21532. "xfr;": "𝔵",
  21533. "Ycy;": "Ы",
  21534. "ycy;": "ы",
  21535. "yen;": "¥",
  21536. "Yfr;": "𝔜",
  21537. "yfr;": "𝔶",
  21538. yuml: "ÿ",
  21539. "Zcy;": "З",
  21540. "zcy;": "з",
  21541. "Zfr;": "ℨ",
  21542. "zfr;": "𝔷",
  21543. "zwj;": "‍",
  21544. Acirc: "Â",
  21545. acirc: "â",
  21546. acute: "´",
  21547. AElig: "Æ",
  21548. aelig: "æ",
  21549. "andd;": "⩜",
  21550. "andv;": "⩚",
  21551. "ange;": "⦤",
  21552. "Aopf;": "𝔸",
  21553. "aopf;": "𝕒",
  21554. "apid;": "≋",
  21555. "apos;": "'",
  21556. Aring: "Å",
  21557. aring: "å",
  21558. "Ascr;": "𝒜",
  21559. "ascr;": "𝒶",
  21560. "Auml;": "Ä",
  21561. "auml;": "ä",
  21562. "Barv;": "⫧",
  21563. "bbrk;": "⎵",
  21564. "Beta;": "Β",
  21565. "beta;": "β",
  21566. "beth;": "ℶ",
  21567. "bNot;": "⫭",
  21568. "bnot;": "⌐",
  21569. "Bopf;": "𝔹",
  21570. "bopf;": "𝕓",
  21571. "boxH;": "═",
  21572. "boxh;": "─",
  21573. "boxV;": "║",
  21574. "boxv;": "│",
  21575. "Bscr;": "ℬ",
  21576. "bscr;": "𝒷",
  21577. "bsim;": "∽",
  21578. "bsol;": "\\",
  21579. "bull;": "•",
  21580. "bump;": "≎",
  21581. "caps;": "∩︀",
  21582. "Cdot;": "Ċ",
  21583. "cdot;": "ċ",
  21584. cedil: "¸",
  21585. "cent;": "¢",
  21586. "CHcy;": "Ч",
  21587. "chcy;": "ч",
  21588. "circ;": "ˆ",
  21589. "cirE;": "⧃",
  21590. "cire;": "≗",
  21591. "comp;": "∁",
  21592. "cong;": "≅",
  21593. "Copf;": "ℂ",
  21594. "copf;": "𝕔",
  21595. "COPY;": "©",
  21596. "copy;": "©",
  21597. "Cscr;": "𝒞",
  21598. "cscr;": "𝒸",
  21599. "csub;": "⫏",
  21600. "csup;": "⫐",
  21601. "cups;": "∪︀",
  21602. "Darr;": "↡",
  21603. "dArr;": "⇓",
  21604. "darr;": "↓",
  21605. "dash;": "‐",
  21606. "dHar;": "⥥",
  21607. "diam;": "⋄",
  21608. "DJcy;": "Ђ",
  21609. "djcy;": "ђ",
  21610. "Dopf;": "𝔻",
  21611. "dopf;": "𝕕",
  21612. "Dscr;": "𝒟",
  21613. "dscr;": "𝒹",
  21614. "DScy;": "Ѕ",
  21615. "dscy;": "ѕ",
  21616. "dsol;": "⧶",
  21617. "dtri;": "▿",
  21618. "DZcy;": "Џ",
  21619. "dzcy;": "џ",
  21620. "ecir;": "≖",
  21621. Ecirc: "Ê",
  21622. ecirc: "ê",
  21623. "Edot;": "Ė",
  21624. "eDot;": "≑",
  21625. "edot;": "ė",
  21626. "emsp;": " ",
  21627. "ensp;": " ",
  21628. "Eopf;": "𝔼",
  21629. "eopf;": "𝕖",
  21630. "epar;": "⋕",
  21631. "epsi;": "ε",
  21632. "Escr;": "ℰ",
  21633. "escr;": "ℯ",
  21634. "Esim;": "⩳",
  21635. "esim;": "≂",
  21636. "Euml;": "Ë",
  21637. "euml;": "ë",
  21638. "euro;": "€",
  21639. "excl;": "!",
  21640. "flat;": "♭",
  21641. "fnof;": "ƒ",
  21642. "Fopf;": "𝔽",
  21643. "fopf;": "𝕗",
  21644. "fork;": "⋔",
  21645. "Fscr;": "ℱ",
  21646. "fscr;": "𝒻",
  21647. "Gdot;": "Ġ",
  21648. "gdot;": "ġ",
  21649. "geqq;": "≧",
  21650. "gesl;": "⋛︀",
  21651. "GJcy;": "Ѓ",
  21652. "gjcy;": "ѓ",
  21653. "gnap;": "⪊",
  21654. "gneq;": "⪈",
  21655. "Gopf;": "𝔾",
  21656. "gopf;": "𝕘",
  21657. "Gscr;": "𝒢",
  21658. "gscr;": "ℊ",
  21659. "gsim;": "≳",
  21660. "gtcc;": "⪧",
  21661. "gvnE;": "≩︀",
  21662. "half;": "½",
  21663. "hArr;": "⇔",
  21664. "harr;": "↔",
  21665. "hbar;": "ℏ",
  21666. "Hopf;": "ℍ",
  21667. "hopf;": "𝕙",
  21668. "Hscr;": "ℋ",
  21669. "hscr;": "𝒽",
  21670. Icirc: "Î",
  21671. icirc: "î",
  21672. "Idot;": "İ",
  21673. "IEcy;": "Е",
  21674. "iecy;": "е",
  21675. iexcl: "¡",
  21676. "imof;": "⊷",
  21677. "IOcy;": "Ё",
  21678. "iocy;": "ё",
  21679. "Iopf;": "𝕀",
  21680. "iopf;": "𝕚",
  21681. "Iota;": "Ι",
  21682. "iota;": "ι",
  21683. "Iscr;": "ℐ",
  21684. "iscr;": "𝒾",
  21685. "isin;": "∈",
  21686. "Iuml;": "Ï",
  21687. "iuml;": "ï",
  21688. "Jopf;": "𝕁",
  21689. "jopf;": "𝕛",
  21690. "Jscr;": "𝒥",
  21691. "jscr;": "𝒿",
  21692. "KHcy;": "Х",
  21693. "khcy;": "х",
  21694. "KJcy;": "Ќ",
  21695. "kjcy;": "ќ",
  21696. "Kopf;": "𝕂",
  21697. "kopf;": "𝕜",
  21698. "Kscr;": "𝒦",
  21699. "kscr;": "𝓀",
  21700. "Lang;": "⟪",
  21701. "lang;": "⟨",
  21702. laquo: "«",
  21703. "Larr;": "↞",
  21704. "lArr;": "⇐",
  21705. "larr;": "←",
  21706. "late;": "⪭",
  21707. "lcub;": "{",
  21708. "ldca;": "⤶",
  21709. "ldsh;": "↲",
  21710. "leqq;": "≦",
  21711. "lesg;": "⋚︀",
  21712. "lHar;": "⥢",
  21713. "LJcy;": "Љ",
  21714. "ljcy;": "љ",
  21715. "lnap;": "⪉",
  21716. "lneq;": "⪇",
  21717. "Lopf;": "𝕃",
  21718. "lopf;": "𝕝",
  21719. "lozf;": "⧫",
  21720. "lpar;": "(",
  21721. "Lscr;": "ℒ",
  21722. "lscr;": "𝓁",
  21723. "lsim;": "≲",
  21724. "lsqb;": "[",
  21725. "ltcc;": "⪦",
  21726. "ltri;": "◃",
  21727. "lvnE;": "≨︀",
  21728. "macr;": "¯",
  21729. "male;": "♂",
  21730. "malt;": "✠",
  21731. micro: "µ",
  21732. "mlcp;": "⫛",
  21733. "mldr;": "…",
  21734. "Mopf;": "𝕄",
  21735. "mopf;": "𝕞",
  21736. "Mscr;": "ℳ",
  21737. "mscr;": "𝓂",
  21738. "nang;": "∠⃒",
  21739. "napE;": "⩰̸",
  21740. "nbsp;": " ",
  21741. "ncap;": "⩃",
  21742. "ncup;": "⩂",
  21743. "ngeq;": "≱",
  21744. "nges;": "⩾̸",
  21745. "ngtr;": "≯",
  21746. "nGtv;": "≫̸",
  21747. "nisd;": "⋺",
  21748. "NJcy;": "Њ",
  21749. "njcy;": "њ",
  21750. "nldr;": "‥",
  21751. "nleq;": "≰",
  21752. "nles;": "⩽̸",
  21753. "nLtv;": "≪̸",
  21754. "nmid;": "∤",
  21755. "Nopf;": "ℕ",
  21756. "nopf;": "𝕟",
  21757. "npar;": "∦",
  21758. "npre;": "⪯̸",
  21759. "nsce;": "⪰̸",
  21760. "Nscr;": "𝒩",
  21761. "nscr;": "𝓃",
  21762. "nsim;": "≁",
  21763. "nsub;": "⊄",
  21764. "nsup;": "⊅",
  21765. "ntgl;": "≹",
  21766. "ntlg;": "≸",
  21767. "nvap;": "≍⃒",
  21768. "nvge;": "≥⃒",
  21769. "nvgt;": ">⃒",
  21770. "nvle;": "≤⃒",
  21771. "nvlt;": "<⃒",
  21772. "oast;": "⊛",
  21773. "ocir;": "⊚",
  21774. Ocirc: "Ô",
  21775. ocirc: "ô",
  21776. "odiv;": "⨸",
  21777. "odot;": "⊙",
  21778. "ogon;": "˛",
  21779. "oint;": "∮",
  21780. "omid;": "⦶",
  21781. "Oopf;": "𝕆",
  21782. "oopf;": "𝕠",
  21783. "opar;": "⦷",
  21784. "ordf;": "ª",
  21785. "ordm;": "º",
  21786. "oror;": "⩖",
  21787. "Oscr;": "𝒪",
  21788. "oscr;": "ℴ",
  21789. "osol;": "⊘",
  21790. "Ouml;": "Ö",
  21791. "ouml;": "ö",
  21792. "para;": "¶",
  21793. "part;": "∂",
  21794. "perp;": "⊥",
  21795. "phiv;": "ϕ",
  21796. "plus;": "+",
  21797. "Popf;": "ℙ",
  21798. "popf;": "𝕡",
  21799. pound: "£",
  21800. "prap;": "⪷",
  21801. "prec;": "≺",
  21802. "prnE;": "⪵",
  21803. "prod;": "∏",
  21804. "prop;": "∝",
  21805. "Pscr;": "𝒫",
  21806. "pscr;": "𝓅",
  21807. "qint;": "⨌",
  21808. "Qopf;": "ℚ",
  21809. "qopf;": "𝕢",
  21810. "Qscr;": "𝒬",
  21811. "qscr;": "𝓆",
  21812. "QUOT;": "\"",
  21813. "quot;": "\"",
  21814. "race;": "∽̱",
  21815. "Rang;": "⟫",
  21816. "rang;": "⟩",
  21817. raquo: "»",
  21818. "Rarr;": "↠",
  21819. "rArr;": "⇒",
  21820. "rarr;": "→",
  21821. "rcub;": "}",
  21822. "rdca;": "⤷",
  21823. "rdsh;": "↳",
  21824. "real;": "ℜ",
  21825. "rect;": "▭",
  21826. "rHar;": "⥤",
  21827. "rhov;": "ϱ",
  21828. "ring;": "˚",
  21829. "Ropf;": "ℝ",
  21830. "ropf;": "𝕣",
  21831. "rpar;": ")",
  21832. "Rscr;": "ℛ",
  21833. "rscr;": "𝓇",
  21834. "rsqb;": "]",
  21835. "rtri;": "▹",
  21836. "scap;": "⪸",
  21837. "scnE;": "⪶",
  21838. "sdot;": "⋅",
  21839. "sect;": "§",
  21840. "semi;": ";",
  21841. "sext;": "✶",
  21842. "SHcy;": "Ш",
  21843. "shcy;": "ш",
  21844. "sime;": "≃",
  21845. "simg;": "⪞",
  21846. "siml;": "⪝",
  21847. "smid;": "∣",
  21848. "smte;": "⪬",
  21849. "solb;": "⧄",
  21850. "Sopf;": "𝕊",
  21851. "sopf;": "𝕤",
  21852. "spar;": "∥",
  21853. "Sqrt;": "√",
  21854. "squf;": "▪",
  21855. "Sscr;": "𝒮",
  21856. "sscr;": "𝓈",
  21857. "Star;": "⋆",
  21858. "star;": "☆",
  21859. "subE;": "⫅",
  21860. "sube;": "⊆",
  21861. "succ;": "≻",
  21862. "sung;": "♪",
  21863. "sup1;": "¹",
  21864. "sup2;": "²",
  21865. "sup3;": "³",
  21866. "supE;": "⫆",
  21867. "supe;": "⊇",
  21868. szlig: "ß",
  21869. "tbrk;": "⎴",
  21870. "tdot;": "⃛",
  21871. THORN: "Þ",
  21872. thorn: "þ",
  21873. times: "×",
  21874. "tint;": "∭",
  21875. "toea;": "⤨",
  21876. "Topf;": "𝕋",
  21877. "topf;": "𝕥",
  21878. "tosa;": "⤩",
  21879. "trie;": "≜",
  21880. "Tscr;": "𝒯",
  21881. "tscr;": "𝓉",
  21882. "TScy;": "Ц",
  21883. "tscy;": "ц",
  21884. "Uarr;": "↟",
  21885. "uArr;": "⇑",
  21886. "uarr;": "↑",
  21887. Ucirc: "Û",
  21888. ucirc: "û",
  21889. "uHar;": "⥣",
  21890. "Uopf;": "𝕌",
  21891. "uopf;": "𝕦",
  21892. "Upsi;": "ϒ",
  21893. "upsi;": "υ",
  21894. "Uscr;": "𝒰",
  21895. "uscr;": "𝓊",
  21896. "utri;": "▵",
  21897. "Uuml;": "Ü",
  21898. "uuml;": "ü",
  21899. "vArr;": "⇕",
  21900. "varr;": "↕",
  21901. "Vbar;": "⫫",
  21902. "vBar;": "⫨",
  21903. "Vert;": "‖",
  21904. "vert;": "|",
  21905. "Vopf;": "𝕍",
  21906. "vopf;": "𝕧",
  21907. "Vscr;": "𝒱",
  21908. "vscr;": "𝓋",
  21909. "Wopf;": "𝕎",
  21910. "wopf;": "𝕨",
  21911. "Wscr;": "𝒲",
  21912. "wscr;": "𝓌",
  21913. "xcap;": "⋂",
  21914. "xcup;": "⋃",
  21915. "xmap;": "⟼",
  21916. "xnis;": "⋻",
  21917. "Xopf;": "𝕏",
  21918. "xopf;": "𝕩",
  21919. "Xscr;": "𝒳",
  21920. "xscr;": "𝓍",
  21921. "xvee;": "⋁",
  21922. "YAcy;": "Я",
  21923. "yacy;": "я",
  21924. "YIcy;": "Ї",
  21925. "yicy;": "ї",
  21926. "Yopf;": "𝕐",
  21927. "yopf;": "𝕪",
  21928. "Yscr;": "𝒴",
  21929. "yscr;": "𝓎",
  21930. "YUcy;": "Ю",
  21931. "yucy;": "ю",
  21932. "Yuml;": "Ÿ",
  21933. "yuml;": "ÿ",
  21934. "Zdot;": "Ż",
  21935. "zdot;": "ż",
  21936. "Zeta;": "Ζ",
  21937. "zeta;": "ζ",
  21938. "ZHcy;": "Ж",
  21939. "zhcy;": "ж",
  21940. "Zopf;": "ℤ",
  21941. "zopf;": "𝕫",
  21942. "Zscr;": "𝒵",
  21943. "zscr;": "𝓏",
  21944. "zwnj;": "‌",
  21945. Aacute: "Á",
  21946. aacute: "á",
  21947. "Acirc;": "Â",
  21948. "acirc;": "â",
  21949. "acute;": "´",
  21950. "AElig;": "Æ",
  21951. "aelig;": "æ",
  21952. Agrave: "À",
  21953. agrave: "à",
  21954. "aleph;": "ℵ",
  21955. "Alpha;": "Α",
  21956. "alpha;": "α",
  21957. "Amacr;": "Ā",
  21958. "amacr;": "ā",
  21959. "amalg;": "⨿",
  21960. "angle;": "∠",
  21961. "angrt;": "∟",
  21962. "angst;": "Å",
  21963. "Aogon;": "Ą",
  21964. "aogon;": "ą",
  21965. "Aring;": "Å",
  21966. "aring;": "å",
  21967. "asymp;": "≈",
  21968. Atilde: "Ã",
  21969. atilde: "ã",
  21970. "awint;": "⨑",
  21971. "bcong;": "≌",
  21972. "bdquo;": "„",
  21973. "bepsi;": "϶",
  21974. "blank;": "␣",
  21975. "blk12;": "▒",
  21976. "blk14;": "░",
  21977. "blk34;": "▓",
  21978. "block;": "█",
  21979. "boxDL;": "╗",
  21980. "boxDl;": "╖",
  21981. "boxdL;": "╕",
  21982. "boxdl;": "┐",
  21983. "boxDR;": "╔",
  21984. "boxDr;": "╓",
  21985. "boxdR;": "╒",
  21986. "boxdr;": "┌",
  21987. "boxHD;": "╦",
  21988. "boxHd;": "╤",
  21989. "boxhD;": "╥",
  21990. "boxhd;": "┬",
  21991. "boxHU;": "╩",
  21992. "boxHu;": "╧",
  21993. "boxhU;": "╨",
  21994. "boxhu;": "┴",
  21995. "boxUL;": "╝",
  21996. "boxUl;": "╜",
  21997. "boxuL;": "╛",
  21998. "boxul;": "┘",
  21999. "boxUR;": "╚",
  22000. "boxUr;": "╙",
  22001. "boxuR;": "╘",
  22002. "boxur;": "└",
  22003. "boxVH;": "╬",
  22004. "boxVh;": "╫",
  22005. "boxvH;": "╪",
  22006. "boxvh;": "┼",
  22007. "boxVL;": "╣",
  22008. "boxVl;": "╢",
  22009. "boxvL;": "╡",
  22010. "boxvl;": "┤",
  22011. "boxVR;": "╠",
  22012. "boxVr;": "╟",
  22013. "boxvR;": "╞",
  22014. "boxvr;": "├",
  22015. "Breve;": "˘",
  22016. "breve;": "˘",
  22017. brvbar: "¦",
  22018. "bsemi;": "⁏",
  22019. "bsime;": "⋍",
  22020. "bsolb;": "⧅",
  22021. "bumpE;": "⪮",
  22022. "bumpe;": "≏",
  22023. "caret;": "⁁",
  22024. "caron;": "ˇ",
  22025. "ccaps;": "⩍",
  22026. Ccedil: "Ç",
  22027. ccedil: "ç",
  22028. "Ccirc;": "Ĉ",
  22029. "ccirc;": "ĉ",
  22030. "ccups;": "⩌",
  22031. "cedil;": "¸",
  22032. "check;": "✓",
  22033. "clubs;": "♣",
  22034. "Colon;": "∷",
  22035. "colon;": ":",
  22036. "comma;": ",",
  22037. "crarr;": "↵",
  22038. "Cross;": "⨯",
  22039. "cross;": "✗",
  22040. "csube;": "⫑",
  22041. "csupe;": "⫒",
  22042. "ctdot;": "⋯",
  22043. "cuepr;": "⋞",
  22044. "cuesc;": "⋟",
  22045. "cupor;": "⩅",
  22046. curren: "¤",
  22047. "cuvee;": "⋎",
  22048. "cuwed;": "⋏",
  22049. "cwint;": "∱",
  22050. "Dashv;": "⫤",
  22051. "dashv;": "⊣",
  22052. "dblac;": "˝",
  22053. "ddarr;": "⇊",
  22054. "Delta;": "Δ",
  22055. "delta;": "δ",
  22056. "dharl;": "⇃",
  22057. "dharr;": "⇂",
  22058. "diams;": "♦",
  22059. "disin;": "⋲",
  22060. divide: "÷",
  22061. "doteq;": "≐",
  22062. "dtdot;": "⋱",
  22063. "dtrif;": "▾",
  22064. "duarr;": "⇵",
  22065. "duhar;": "⥯",
  22066. Eacute: "É",
  22067. eacute: "é",
  22068. "Ecirc;": "Ê",
  22069. "ecirc;": "ê",
  22070. "eDDot;": "⩷",
  22071. "efDot;": "≒",
  22072. Egrave: "È",
  22073. egrave: "è",
  22074. "Emacr;": "Ē",
  22075. "emacr;": "ē",
  22076. "empty;": "∅",
  22077. "Eogon;": "Ę",
  22078. "eogon;": "ę",
  22079. "eplus;": "⩱",
  22080. "epsiv;": "ϵ",
  22081. "eqsim;": "≂",
  22082. "Equal;": "⩵",
  22083. "equiv;": "≡",
  22084. "erarr;": "⥱",
  22085. "erDot;": "≓",
  22086. "esdot;": "≐",
  22087. "exist;": "∃",
  22088. "fflig;": "ff",
  22089. "filig;": "fi",
  22090. "fjlig;": "fj",
  22091. "fllig;": "fl",
  22092. "fltns;": "▱",
  22093. "forkv;": "⫙",
  22094. frac12: "½",
  22095. frac14: "¼",
  22096. frac34: "¾",
  22097. "frasl;": "⁄",
  22098. "frown;": "⌢",
  22099. "Gamma;": "Γ",
  22100. "gamma;": "γ",
  22101. "Gcirc;": "Ĝ",
  22102. "gcirc;": "ĝ",
  22103. "gescc;": "⪩",
  22104. "gimel;": "ℷ",
  22105. "gneqq;": "≩",
  22106. "gnsim;": "⋧",
  22107. "grave;": "`",
  22108. "gsime;": "⪎",
  22109. "gsiml;": "⪐",
  22110. "gtcir;": "⩺",
  22111. "gtdot;": "⋗",
  22112. "Hacek;": "ˇ",
  22113. "harrw;": "↭",
  22114. "Hcirc;": "Ĥ",
  22115. "hcirc;": "ĥ",
  22116. "hoarr;": "⇿",
  22117. Iacute: "Í",
  22118. iacute: "í",
  22119. "Icirc;": "Î",
  22120. "icirc;": "î",
  22121. "iexcl;": "¡",
  22122. Igrave: "Ì",
  22123. igrave: "ì",
  22124. "iiint;": "∭",
  22125. "iiota;": "℩",
  22126. "IJlig;": "IJ",
  22127. "ijlig;": "ij",
  22128. "Imacr;": "Ī",
  22129. "imacr;": "ī",
  22130. "image;": "ℑ",
  22131. "imath;": "ı",
  22132. "imped;": "Ƶ",
  22133. "infin;": "∞",
  22134. "Iogon;": "Į",
  22135. "iogon;": "į",
  22136. "iprod;": "⨼",
  22137. iquest: "¿",
  22138. "isinE;": "⋹",
  22139. "isins;": "⋴",
  22140. "isinv;": "∈",
  22141. "Iukcy;": "І",
  22142. "iukcy;": "і",
  22143. "Jcirc;": "Ĵ",
  22144. "jcirc;": "ĵ",
  22145. "jmath;": "ȷ",
  22146. "Jukcy;": "Є",
  22147. "jukcy;": "є",
  22148. "Kappa;": "Κ",
  22149. "kappa;": "κ",
  22150. "lAarr;": "⇚",
  22151. "langd;": "⦑",
  22152. "laquo;": "«",
  22153. "larrb;": "⇤",
  22154. "lates;": "⪭︀",
  22155. "lBarr;": "⤎",
  22156. "lbarr;": "⤌",
  22157. "lbbrk;": "❲",
  22158. "lbrke;": "⦋",
  22159. "lceil;": "⌈",
  22160. "ldquo;": "“",
  22161. "lescc;": "⪨",
  22162. "lhard;": "↽",
  22163. "lharu;": "↼",
  22164. "lhblk;": "▄",
  22165. "llarr;": "⇇",
  22166. "lltri;": "◺",
  22167. "lneqq;": "≨",
  22168. "lnsim;": "⋦",
  22169. "loang;": "⟬",
  22170. "loarr;": "⇽",
  22171. "lobrk;": "⟦",
  22172. "lopar;": "⦅",
  22173. "lrarr;": "⇆",
  22174. "lrhar;": "⇋",
  22175. "lrtri;": "⊿",
  22176. "lsime;": "⪍",
  22177. "lsimg;": "⪏",
  22178. "lsquo;": "‘",
  22179. "ltcir;": "⩹",
  22180. "ltdot;": "⋖",
  22181. "ltrie;": "⊴",
  22182. "ltrif;": "◂",
  22183. "mdash;": "—",
  22184. "mDDot;": "∺",
  22185. "micro;": "µ",
  22186. middot: "·",
  22187. "minus;": "−",
  22188. "mumap;": "⊸",
  22189. "nabla;": "∇",
  22190. "napid;": "≋̸",
  22191. "napos;": "ʼn",
  22192. "natur;": "♮",
  22193. "nbump;": "≎̸",
  22194. "ncong;": "≇",
  22195. "ndash;": "–",
  22196. "neArr;": "⇗",
  22197. "nearr;": "↗",
  22198. "nedot;": "≐̸",
  22199. "nesim;": "≂̸",
  22200. "ngeqq;": "≧̸",
  22201. "ngsim;": "≵",
  22202. "nhArr;": "⇎",
  22203. "nharr;": "↮",
  22204. "nhpar;": "⫲",
  22205. "nlArr;": "⇍",
  22206. "nlarr;": "↚",
  22207. "nleqq;": "≦̸",
  22208. "nless;": "≮",
  22209. "nlsim;": "≴",
  22210. "nltri;": "⋪",
  22211. "notin;": "∉",
  22212. "notni;": "∌",
  22213. "npart;": "∂̸",
  22214. "nprec;": "⊀",
  22215. "nrArr;": "⇏",
  22216. "nrarr;": "↛",
  22217. "nrtri;": "⋫",
  22218. "nsime;": "≄",
  22219. "nsmid;": "∤",
  22220. "nspar;": "∦",
  22221. "nsubE;": "⫅̸",
  22222. "nsube;": "⊈",
  22223. "nsucc;": "⊁",
  22224. "nsupE;": "⫆̸",
  22225. "nsupe;": "⊉",
  22226. Ntilde: "Ñ",
  22227. ntilde: "ñ",
  22228. "numsp;": " ",
  22229. "nvsim;": "∼⃒",
  22230. "nwArr;": "⇖",
  22231. "nwarr;": "↖",
  22232. Oacute: "Ó",
  22233. oacute: "ó",
  22234. "Ocirc;": "Ô",
  22235. "ocirc;": "ô",
  22236. "odash;": "⊝",
  22237. "OElig;": "Œ",
  22238. "oelig;": "œ",
  22239. "ofcir;": "⦿",
  22240. Ograve: "Ò",
  22241. ograve: "ò",
  22242. "ohbar;": "⦵",
  22243. "olarr;": "↺",
  22244. "olcir;": "⦾",
  22245. "oline;": "‾",
  22246. "Omacr;": "Ō",
  22247. "omacr;": "ō",
  22248. "Omega;": "Ω",
  22249. "omega;": "ω",
  22250. "operp;": "⦹",
  22251. "oplus;": "⊕",
  22252. "orarr;": "↻",
  22253. "order;": "ℴ",
  22254. Oslash: "Ø",
  22255. oslash: "ø",
  22256. Otilde: "Õ",
  22257. otilde: "õ",
  22258. "ovbar;": "⌽",
  22259. "parsl;": "⫽",
  22260. "phone;": "☎",
  22261. "plusb;": "⊞",
  22262. "pluse;": "⩲",
  22263. plusmn: "±",
  22264. "pound;": "£",
  22265. "prcue;": "≼",
  22266. "Prime;": "″",
  22267. "prime;": "′",
  22268. "prnap;": "⪹",
  22269. "prsim;": "≾",
  22270. "quest;": "?",
  22271. "rAarr;": "⇛",
  22272. "radic;": "√",
  22273. "rangd;": "⦒",
  22274. "range;": "⦥",
  22275. "raquo;": "»",
  22276. "rarrb;": "⇥",
  22277. "rarrc;": "⤳",
  22278. "rarrw;": "↝",
  22279. "ratio;": "∶",
  22280. "RBarr;": "⤐",
  22281. "rBarr;": "⤏",
  22282. "rbarr;": "⤍",
  22283. "rbbrk;": "❳",
  22284. "rbrke;": "⦌",
  22285. "rceil;": "⌉",
  22286. "rdquo;": "”",
  22287. "reals;": "ℝ",
  22288. "rhard;": "⇁",
  22289. "rharu;": "⇀",
  22290. "rlarr;": "⇄",
  22291. "rlhar;": "⇌",
  22292. "rnmid;": "⫮",
  22293. "roang;": "⟭",
  22294. "roarr;": "⇾",
  22295. "robrk;": "⟧",
  22296. "ropar;": "⦆",
  22297. "rrarr;": "⇉",
  22298. "rsquo;": "’",
  22299. "rtrie;": "⊵",
  22300. "rtrif;": "▸",
  22301. "sbquo;": "‚",
  22302. "sccue;": "≽",
  22303. "Scirc;": "Ŝ",
  22304. "scirc;": "ŝ",
  22305. "scnap;": "⪺",
  22306. "scsim;": "≿",
  22307. "sdotb;": "⊡",
  22308. "sdote;": "⩦",
  22309. "seArr;": "⇘",
  22310. "searr;": "↘",
  22311. "setmn;": "∖",
  22312. "sharp;": "♯",
  22313. "Sigma;": "Σ",
  22314. "sigma;": "σ",
  22315. "simeq;": "≃",
  22316. "simgE;": "⪠",
  22317. "simlE;": "⪟",
  22318. "simne;": "≆",
  22319. "slarr;": "←",
  22320. "smile;": "⌣",
  22321. "smtes;": "⪬︀",
  22322. "sqcap;": "⊓",
  22323. "sqcup;": "⊔",
  22324. "sqsub;": "⊏",
  22325. "sqsup;": "⊐",
  22326. "srarr;": "→",
  22327. "starf;": "★",
  22328. "strns;": "¯",
  22329. "subnE;": "⫋",
  22330. "subne;": "⊊",
  22331. "supnE;": "⫌",
  22332. "supne;": "⊋",
  22333. "swArr;": "⇙",
  22334. "swarr;": "↙",
  22335. "szlig;": "ß",
  22336. "Theta;": "Θ",
  22337. "theta;": "θ",
  22338. "thkap;": "≈",
  22339. "THORN;": "Þ",
  22340. "thorn;": "þ",
  22341. "Tilde;": "∼",
  22342. "tilde;": "˜",
  22343. "times;": "×",
  22344. "TRADE;": "™",
  22345. "trade;": "™",
  22346. "trisb;": "⧍",
  22347. "TSHcy;": "Ћ",
  22348. "tshcy;": "ћ",
  22349. "twixt;": "≬",
  22350. Uacute: "Ú",
  22351. uacute: "ú",
  22352. "Ubrcy;": "Ў",
  22353. "ubrcy;": "ў",
  22354. "Ucirc;": "Û",
  22355. "ucirc;": "û",
  22356. "udarr;": "⇅",
  22357. "udhar;": "⥮",
  22358. Ugrave: "Ù",
  22359. ugrave: "ù",
  22360. "uharl;": "↿",
  22361. "uharr;": "↾",
  22362. "uhblk;": "▀",
  22363. "ultri;": "◸",
  22364. "Umacr;": "Ū",
  22365. "umacr;": "ū",
  22366. "Union;": "⋃",
  22367. "Uogon;": "Ų",
  22368. "uogon;": "ų",
  22369. "uplus;": "⊎",
  22370. "upsih;": "ϒ",
  22371. "UpTee;": "⊥",
  22372. "Uring;": "Ů",
  22373. "uring;": "ů",
  22374. "urtri;": "◹",
  22375. "utdot;": "⋰",
  22376. "utrif;": "▴",
  22377. "uuarr;": "⇈",
  22378. "varpi;": "ϖ",
  22379. "vBarv;": "⫩",
  22380. "VDash;": "⊫",
  22381. "Vdash;": "⊩",
  22382. "vDash;": "⊨",
  22383. "vdash;": "⊢",
  22384. "veeeq;": "≚",
  22385. "vltri;": "⊲",
  22386. "vnsub;": "⊂⃒",
  22387. "vnsup;": "⊃⃒",
  22388. "vprop;": "∝",
  22389. "vrtri;": "⊳",
  22390. "Wcirc;": "Ŵ",
  22391. "wcirc;": "ŵ",
  22392. "Wedge;": "⋀",
  22393. "wedge;": "∧",
  22394. "xcirc;": "◯",
  22395. "xdtri;": "▽",
  22396. "xhArr;": "⟺",
  22397. "xharr;": "⟷",
  22398. "xlArr;": "⟸",
  22399. "xlarr;": "⟵",
  22400. "xodot;": "⨀",
  22401. "xrArr;": "⟹",
  22402. "xrarr;": "⟶",
  22403. "xutri;": "△",
  22404. Yacute: "Ý",
  22405. yacute: "ý",
  22406. "Ycirc;": "Ŷ",
  22407. "ycirc;": "ŷ",
  22408. "Aacute;": "Á",
  22409. "aacute;": "á",
  22410. "Abreve;": "Ă",
  22411. "abreve;": "ă",
  22412. "Agrave;": "À",
  22413. "agrave;": "à",
  22414. "andand;": "⩕",
  22415. "angmsd;": "∡",
  22416. "angsph;": "∢",
  22417. "apacir;": "⩯",
  22418. "approx;": "≈",
  22419. "Assign;": "≔",
  22420. "Atilde;": "Ã",
  22421. "atilde;": "ã",
  22422. "barvee;": "⊽",
  22423. "Barwed;": "⌆",
  22424. "barwed;": "⌅",
  22425. "becaus;": "∵",
  22426. "bernou;": "ℬ",
  22427. "bigcap;": "⋂",
  22428. "bigcup;": "⋃",
  22429. "bigvee;": "⋁",
  22430. "bkarow;": "⤍",
  22431. "bottom;": "⊥",
  22432. "bowtie;": "⋈",
  22433. "boxbox;": "⧉",
  22434. "bprime;": "‵",
  22435. "brvbar;": "¦",
  22436. "bullet;": "•",
  22437. "Bumpeq;": "≎",
  22438. "bumpeq;": "≏",
  22439. "Cacute;": "Ć",
  22440. "cacute;": "ć",
  22441. "capand;": "⩄",
  22442. "capcap;": "⩋",
  22443. "capcup;": "⩇",
  22444. "capdot;": "⩀",
  22445. "Ccaron;": "Č",
  22446. "ccaron;": "č",
  22447. "Ccedil;": "Ç",
  22448. "ccedil;": "ç",
  22449. "circeq;": "≗",
  22450. "cirmid;": "⫯",
  22451. "Colone;": "⩴",
  22452. "colone;": "≔",
  22453. "commat;": "@",
  22454. "compfn;": "∘",
  22455. "Conint;": "∯",
  22456. "conint;": "∮",
  22457. "coprod;": "∐",
  22458. "copysr;": "℗",
  22459. "cularr;": "↶",
  22460. "CupCap;": "≍",
  22461. "cupcap;": "⩆",
  22462. "cupcup;": "⩊",
  22463. "cupdot;": "⊍",
  22464. "curarr;": "↷",
  22465. "curren;": "¤",
  22466. "cylcty;": "⌭",
  22467. "Dagger;": "‡",
  22468. "dagger;": "†",
  22469. "daleth;": "ℸ",
  22470. "Dcaron;": "Ď",
  22471. "dcaron;": "ď",
  22472. "dfisht;": "⥿",
  22473. "divide;": "÷",
  22474. "divonx;": "⋇",
  22475. "dlcorn;": "⌞",
  22476. "dlcrop;": "⌍",
  22477. "dollar;": "$",
  22478. "DotDot;": "⃜",
  22479. "drcorn;": "⌟",
  22480. "drcrop;": "⌌",
  22481. "Dstrok;": "Đ",
  22482. "dstrok;": "đ",
  22483. "Eacute;": "É",
  22484. "eacute;": "é",
  22485. "easter;": "⩮",
  22486. "Ecaron;": "Ě",
  22487. "ecaron;": "ě",
  22488. "ecolon;": "≕",
  22489. "Egrave;": "È",
  22490. "egrave;": "è",
  22491. "egsdot;": "⪘",
  22492. "elsdot;": "⪗",
  22493. "emptyv;": "∅",
  22494. "emsp13;": " ",
  22495. "emsp14;": " ",
  22496. "eparsl;": "⧣",
  22497. "eqcirc;": "≖",
  22498. "equals;": "=",
  22499. "equest;": "≟",
  22500. "Exists;": "∃",
  22501. "female;": "♀",
  22502. "ffilig;": "ffi",
  22503. "ffllig;": "ffl",
  22504. "ForAll;": "∀",
  22505. "forall;": "∀",
  22506. "frac12;": "½",
  22507. "frac13;": "⅓",
  22508. "frac14;": "¼",
  22509. "frac15;": "⅕",
  22510. "frac16;": "⅙",
  22511. "frac18;": "⅛",
  22512. "frac23;": "⅔",
  22513. "frac25;": "⅖",
  22514. "frac34;": "¾",
  22515. "frac35;": "⅗",
  22516. "frac38;": "⅜",
  22517. "frac45;": "⅘",
  22518. "frac56;": "⅚",
  22519. "frac58;": "⅝",
  22520. "frac78;": "⅞",
  22521. "gacute;": "ǵ",
  22522. "Gammad;": "Ϝ",
  22523. "gammad;": "ϝ",
  22524. "Gbreve;": "Ğ",
  22525. "gbreve;": "ğ",
  22526. "Gcedil;": "Ģ",
  22527. "gesdot;": "⪀",
  22528. "gesles;": "⪔",
  22529. "gtlPar;": "⦕",
  22530. "gtrarr;": "⥸",
  22531. "gtrdot;": "⋗",
  22532. "gtrsim;": "≳",
  22533. "hairsp;": " ",
  22534. "hamilt;": "ℋ",
  22535. "HARDcy;": "Ъ",
  22536. "hardcy;": "ъ",
  22537. "hearts;": "♥",
  22538. "hellip;": "…",
  22539. "hercon;": "⊹",
  22540. "homtht;": "∻",
  22541. "horbar;": "―",
  22542. "hslash;": "ℏ",
  22543. "Hstrok;": "Ħ",
  22544. "hstrok;": "ħ",
  22545. "hybull;": "⁃",
  22546. "hyphen;": "‐",
  22547. "Iacute;": "Í",
  22548. "iacute;": "í",
  22549. "Igrave;": "Ì",
  22550. "igrave;": "ì",
  22551. "iiiint;": "⨌",
  22552. "iinfin;": "⧜",
  22553. "incare;": "℅",
  22554. "inodot;": "ı",
  22555. "intcal;": "⊺",
  22556. "iquest;": "¿",
  22557. "isinsv;": "⋳",
  22558. "Itilde;": "Ĩ",
  22559. "itilde;": "ĩ",
  22560. "Jsercy;": "Ј",
  22561. "jsercy;": "ј",
  22562. "kappav;": "ϰ",
  22563. "Kcedil;": "Ķ",
  22564. "kcedil;": "ķ",
  22565. "kgreen;": "ĸ",
  22566. "Lacute;": "Ĺ",
  22567. "lacute;": "ĺ",
  22568. "lagran;": "ℒ",
  22569. "Lambda;": "Λ",
  22570. "lambda;": "λ",
  22571. "langle;": "⟨",
  22572. "larrfs;": "⤝",
  22573. "larrhk;": "↩",
  22574. "larrlp;": "↫",
  22575. "larrpl;": "⤹",
  22576. "larrtl;": "↢",
  22577. "lAtail;": "⤛",
  22578. "latail;": "⤙",
  22579. "lbrace;": "{",
  22580. "lbrack;": "[",
  22581. "Lcaron;": "Ľ",
  22582. "lcaron;": "ľ",
  22583. "Lcedil;": "Ļ",
  22584. "lcedil;": "ļ",
  22585. "ldquor;": "„",
  22586. "lesdot;": "⩿",
  22587. "lesges;": "⪓",
  22588. "lfisht;": "⥼",
  22589. "lfloor;": "⌊",
  22590. "lharul;": "⥪",
  22591. "llhard;": "⥫",
  22592. "Lmidot;": "Ŀ",
  22593. "lmidot;": "ŀ",
  22594. "lmoust;": "⎰",
  22595. "loplus;": "⨭",
  22596. "lowast;": "∗",
  22597. "lowbar;": "_",
  22598. "lparlt;": "⦓",
  22599. "lrhard;": "⥭",
  22600. "lsaquo;": "‹",
  22601. "lsquor;": "‚",
  22602. "Lstrok;": "Ł",
  22603. "lstrok;": "ł",
  22604. "lthree;": "⋋",
  22605. "ltimes;": "⋉",
  22606. "ltlarr;": "⥶",
  22607. "ltrPar;": "⦖",
  22608. "mapsto;": "↦",
  22609. "marker;": "▮",
  22610. "mcomma;": "⨩",
  22611. "midast;": "*",
  22612. "midcir;": "⫰",
  22613. "middot;": "·",
  22614. "minusb;": "⊟",
  22615. "minusd;": "∸",
  22616. "mnplus;": "∓",
  22617. "models;": "⊧",
  22618. "mstpos;": "∾",
  22619. "Nacute;": "Ń",
  22620. "nacute;": "ń",
  22621. "nbumpe;": "≏̸",
  22622. "Ncaron;": "Ň",
  22623. "ncaron;": "ň",
  22624. "Ncedil;": "Ņ",
  22625. "ncedil;": "ņ",
  22626. "nearhk;": "⤤",
  22627. "nequiv;": "≢",
  22628. "nesear;": "⤨",
  22629. "nexist;": "∄",
  22630. "nltrie;": "⋬",
  22631. "notinE;": "⋹̸",
  22632. "nparsl;": "⫽⃥",
  22633. "nprcue;": "⋠",
  22634. "nrarrc;": "⤳̸",
  22635. "nrarrw;": "↝̸",
  22636. "nrtrie;": "⋭",
  22637. "nsccue;": "⋡",
  22638. "nsimeq;": "≄",
  22639. "Ntilde;": "Ñ",
  22640. "ntilde;": "ñ",
  22641. "numero;": "№",
  22642. "nVDash;": "⊯",
  22643. "nVdash;": "⊮",
  22644. "nvDash;": "⊭",
  22645. "nvdash;": "⊬",
  22646. "nvHarr;": "⤄",
  22647. "nvlArr;": "⤂",
  22648. "nvrArr;": "⤃",
  22649. "nwarhk;": "⤣",
  22650. "nwnear;": "⤧",
  22651. "Oacute;": "Ó",
  22652. "oacute;": "ó",
  22653. "Odblac;": "Ő",
  22654. "odblac;": "ő",
  22655. "odsold;": "⦼",
  22656. "Ograve;": "Ò",
  22657. "ograve;": "ò",
  22658. "ominus;": "⊖",
  22659. "origof;": "⊶",
  22660. "Oslash;": "Ø",
  22661. "oslash;": "ø",
  22662. "Otilde;": "Õ",
  22663. "otilde;": "õ",
  22664. "Otimes;": "⨷",
  22665. "otimes;": "⊗",
  22666. "parsim;": "⫳",
  22667. "percnt;": "%",
  22668. "period;": ".",
  22669. "permil;": "‰",
  22670. "phmmat;": "ℳ",
  22671. "planck;": "ℏ",
  22672. "plankv;": "ℏ",
  22673. "plusdo;": "∔",
  22674. "plusdu;": "⨥",
  22675. "plusmn;": "±",
  22676. "preceq;": "⪯",
  22677. "primes;": "ℙ",
  22678. "prnsim;": "⋨",
  22679. "propto;": "∝",
  22680. "prurel;": "⊰",
  22681. "puncsp;": " ",
  22682. "qprime;": "⁗",
  22683. "Racute;": "Ŕ",
  22684. "racute;": "ŕ",
  22685. "rangle;": "⟩",
  22686. "rarrap;": "⥵",
  22687. "rarrfs;": "⤞",
  22688. "rarrhk;": "↪",
  22689. "rarrlp;": "↬",
  22690. "rarrpl;": "⥅",
  22691. "Rarrtl;": "⤖",
  22692. "rarrtl;": "↣",
  22693. "rAtail;": "⤜",
  22694. "ratail;": "⤚",
  22695. "rbrace;": "}",
  22696. "rbrack;": "]",
  22697. "Rcaron;": "Ř",
  22698. "rcaron;": "ř",
  22699. "Rcedil;": "Ŗ",
  22700. "rcedil;": "ŗ",
  22701. "rdquor;": "”",
  22702. "rfisht;": "⥽",
  22703. "rfloor;": "⌋",
  22704. "rharul;": "⥬",
  22705. "rmoust;": "⎱",
  22706. "roplus;": "⨮",
  22707. "rpargt;": "⦔",
  22708. "rsaquo;": "›",
  22709. "rsquor;": "’",
  22710. "rthree;": "⋌",
  22711. "rtimes;": "⋊",
  22712. "Sacute;": "Ś",
  22713. "sacute;": "ś",
  22714. "Scaron;": "Š",
  22715. "scaron;": "š",
  22716. "Scedil;": "Ş",
  22717. "scedil;": "ş",
  22718. "scnsim;": "⋩",
  22719. "searhk;": "⤥",
  22720. "seswar;": "⤩",
  22721. "sfrown;": "⌢",
  22722. "SHCHcy;": "Щ",
  22723. "shchcy;": "щ",
  22724. "sigmaf;": "ς",
  22725. "sigmav;": "ς",
  22726. "simdot;": "⩪",
  22727. "smashp;": "⨳",
  22728. "SOFTcy;": "Ь",
  22729. "softcy;": "ь",
  22730. "solbar;": "⌿",
  22731. "spades;": "♠",
  22732. "sqcaps;": "⊓︀",
  22733. "sqcups;": "⊔︀",
  22734. "sqsube;": "⊑",
  22735. "sqsupe;": "⊒",
  22736. "Square;": "□",
  22737. "square;": "□",
  22738. "squarf;": "▪",
  22739. "ssetmn;": "∖",
  22740. "ssmile;": "⌣",
  22741. "sstarf;": "⋆",
  22742. "subdot;": "⪽",
  22743. "Subset;": "⋐",
  22744. "subset;": "⊂",
  22745. "subsim;": "⫇",
  22746. "subsub;": "⫕",
  22747. "subsup;": "⫓",
  22748. "succeq;": "⪰",
  22749. "supdot;": "⪾",
  22750. "Supset;": "⋑",
  22751. "supset;": "⊃",
  22752. "supsim;": "⫈",
  22753. "supsub;": "⫔",
  22754. "supsup;": "⫖",
  22755. "swarhk;": "⤦",
  22756. "swnwar;": "⤪",
  22757. "target;": "⌖",
  22758. "Tcaron;": "Ť",
  22759. "tcaron;": "ť",
  22760. "Tcedil;": "Ţ",
  22761. "tcedil;": "ţ",
  22762. "telrec;": "⌕",
  22763. "there4;": "∴",
  22764. "thetav;": "ϑ",
  22765. "thinsp;": " ",
  22766. "thksim;": "∼",
  22767. "timesb;": "⊠",
  22768. "timesd;": "⨰",
  22769. "topbot;": "⌶",
  22770. "topcir;": "⫱",
  22771. "tprime;": "‴",
  22772. "tridot;": "◬",
  22773. "Tstrok;": "Ŧ",
  22774. "tstrok;": "ŧ",
  22775. "Uacute;": "Ú",
  22776. "uacute;": "ú",
  22777. "Ubreve;": "Ŭ",
  22778. "ubreve;": "ŭ",
  22779. "Udblac;": "Ű",
  22780. "udblac;": "ű",
  22781. "ufisht;": "⥾",
  22782. "Ugrave;": "Ù",
  22783. "ugrave;": "ù",
  22784. "ulcorn;": "⌜",
  22785. "ulcrop;": "⌏",
  22786. "urcorn;": "⌝",
  22787. "urcrop;": "⌎",
  22788. "Utilde;": "Ũ",
  22789. "utilde;": "ũ",
  22790. "vangrt;": "⦜",
  22791. "varphi;": "ϕ",
  22792. "varrho;": "ϱ",
  22793. "Vdashl;": "⫦",
  22794. "veebar;": "⊻",
  22795. "vellip;": "⋮",
  22796. "Verbar;": "‖",
  22797. "verbar;": "|",
  22798. "vsubnE;": "⫋︀",
  22799. "vsubne;": "⊊︀",
  22800. "vsupnE;": "⫌︀",
  22801. "vsupne;": "⊋︀",
  22802. "Vvdash;": "⊪",
  22803. "wedbar;": "⩟",
  22804. "wedgeq;": "≙",
  22805. "weierp;": "℘",
  22806. "wreath;": "≀",
  22807. "xoplus;": "⨁",
  22808. "xotime;": "⨂",
  22809. "xsqcup;": "⨆",
  22810. "xuplus;": "⨄",
  22811. "xwedge;": "⋀",
  22812. "Yacute;": "Ý",
  22813. "yacute;": "ý",
  22814. "Zacute;": "Ź",
  22815. "zacute;": "ź",
  22816. "Zcaron;": "Ž",
  22817. "zcaron;": "ž",
  22818. "zeetrf;": "ℨ",
  22819. "alefsym;": "ℵ",
  22820. "angrtvb;": "⊾",
  22821. "angzarr;": "⍼",
  22822. "asympeq;": "≍",
  22823. "backsim;": "∽",
  22824. "Because;": "∵",
  22825. "because;": "∵",
  22826. "bemptyv;": "⦰",
  22827. "between;": "≬",
  22828. "bigcirc;": "◯",
  22829. "bigodot;": "⨀",
  22830. "bigstar;": "★",
  22831. "bnequiv;": "≡⃥",
  22832. "boxplus;": "⊞",
  22833. "Cayleys;": "ℭ",
  22834. "Cconint;": "∰",
  22835. "ccupssm;": "⩐",
  22836. "Cedilla;": "¸",
  22837. "cemptyv;": "⦲",
  22838. "cirscir;": "⧂",
  22839. "coloneq;": "≔",
  22840. "congdot;": "⩭",
  22841. "cudarrl;": "⤸",
  22842. "cudarrr;": "⤵",
  22843. "cularrp;": "⤽",
  22844. "curarrm;": "⤼",
  22845. "dbkarow;": "⤏",
  22846. "ddagger;": "‡",
  22847. "ddotseq;": "⩷",
  22848. "demptyv;": "⦱",
  22849. "Diamond;": "⋄",
  22850. "diamond;": "⋄",
  22851. "digamma;": "ϝ",
  22852. "dotplus;": "∔",
  22853. "DownTee;": "⊤",
  22854. "dwangle;": "⦦",
  22855. "Element;": "∈",
  22856. "Epsilon;": "Ε",
  22857. "epsilon;": "ε",
  22858. "eqcolon;": "≕",
  22859. "equivDD;": "⩸",
  22860. "gesdoto;": "⪂",
  22861. "gtquest;": "⩼",
  22862. "gtrless;": "≷",
  22863. "harrcir;": "⥈",
  22864. "Implies;": "⇒",
  22865. "intprod;": "⨼",
  22866. "isindot;": "⋵",
  22867. "larrbfs;": "⤟",
  22868. "larrsim;": "⥳",
  22869. "lbrksld;": "⦏",
  22870. "lbrkslu;": "⦍",
  22871. "ldrdhar;": "⥧",
  22872. "LeftTee;": "⊣",
  22873. "lesdoto;": "⪁",
  22874. "lessdot;": "⋖",
  22875. "lessgtr;": "≶",
  22876. "lesssim;": "≲",
  22877. "lotimes;": "⨴",
  22878. "lozenge;": "◊",
  22879. "ltquest;": "⩻",
  22880. "luruhar;": "⥦",
  22881. "maltese;": "✠",
  22882. "minusdu;": "⨪",
  22883. "napprox;": "≉",
  22884. "natural;": "♮",
  22885. "nearrow;": "↗",
  22886. "NewLine;": "\n",
  22887. "nexists;": "∄",
  22888. "NoBreak;": "⁠",
  22889. "notinva;": "∉",
  22890. "notinvb;": "⋷",
  22891. "notinvc;": "⋶",
  22892. "NotLess;": "≮",
  22893. "notniva;": "∌",
  22894. "notnivb;": "⋾",
  22895. "notnivc;": "⋽",
  22896. "npolint;": "⨔",
  22897. "npreceq;": "⪯̸",
  22898. "nsqsube;": "⋢",
  22899. "nsqsupe;": "⋣",
  22900. "nsubset;": "⊂⃒",
  22901. "nsucceq;": "⪰̸",
  22902. "nsupset;": "⊃⃒",
  22903. "nvinfin;": "⧞",
  22904. "nvltrie;": "⊴⃒",
  22905. "nvrtrie;": "⊵⃒",
  22906. "nwarrow;": "↖",
  22907. "olcross;": "⦻",
  22908. "Omicron;": "Ο",
  22909. "omicron;": "ο",
  22910. "orderof;": "ℴ",
  22911. "orslope;": "⩗",
  22912. "OverBar;": "‾",
  22913. "pertenk;": "‱",
  22914. "planckh;": "ℎ",
  22915. "pluscir;": "⨢",
  22916. "plussim;": "⨦",
  22917. "plustwo;": "⨧",
  22918. "precsim;": "≾",
  22919. "Product;": "∏",
  22920. "quatint;": "⨖",
  22921. "questeq;": "≟",
  22922. "rarrbfs;": "⤠",
  22923. "rarrsim;": "⥴",
  22924. "rbrksld;": "⦎",
  22925. "rbrkslu;": "⦐",
  22926. "rdldhar;": "⥩",
  22927. "realine;": "ℛ",
  22928. "rotimes;": "⨵",
  22929. "ruluhar;": "⥨",
  22930. "searrow;": "↘",
  22931. "simplus;": "⨤",
  22932. "simrarr;": "⥲",
  22933. "subedot;": "⫃",
  22934. "submult;": "⫁",
  22935. "subplus;": "⪿",
  22936. "subrarr;": "⥹",
  22937. "succsim;": "≿",
  22938. "supdsub;": "⫘",
  22939. "supedot;": "⫄",
  22940. "suphsol;": "⟉",
  22941. "suphsub;": "⫗",
  22942. "suplarr;": "⥻",
  22943. "supmult;": "⫂",
  22944. "supplus;": "⫀",
  22945. "swarrow;": "↙",
  22946. "topfork;": "⫚",
  22947. "triplus;": "⨹",
  22948. "tritime;": "⨻",
  22949. "UpArrow;": "↑",
  22950. "Uparrow;": "⇑",
  22951. "uparrow;": "↑",
  22952. "Upsilon;": "Υ",
  22953. "upsilon;": "υ",
  22954. "uwangle;": "⦧",
  22955. "vzigzag;": "⦚",
  22956. "zigrarr;": "⇝",
  22957. "andslope;": "⩘",
  22958. "angmsdaa;": "⦨",
  22959. "angmsdab;": "⦩",
  22960. "angmsdac;": "⦪",
  22961. "angmsdad;": "⦫",
  22962. "angmsdae;": "⦬",
  22963. "angmsdaf;": "⦭",
  22964. "angmsdag;": "⦮",
  22965. "angmsdah;": "⦯",
  22966. "angrtvbd;": "⦝",
  22967. "approxeq;": "≊",
  22968. "awconint;": "∳",
  22969. "backcong;": "≌",
  22970. "barwedge;": "⌅",
  22971. "bbrktbrk;": "⎶",
  22972. "bigoplus;": "⨁",
  22973. "bigsqcup;": "⨆",
  22974. "biguplus;": "⨄",
  22975. "bigwedge;": "⋀",
  22976. "boxminus;": "⊟",
  22977. "boxtimes;": "⊠",
  22978. "bsolhsub;": "⟈",
  22979. "capbrcup;": "⩉",
  22980. "circledR;": "®",
  22981. "circledS;": "Ⓢ",
  22982. "cirfnint;": "⨐",
  22983. "clubsuit;": "♣",
  22984. "cupbrcap;": "⩈",
  22985. "curlyvee;": "⋎",
  22986. "cwconint;": "∲",
  22987. "DDotrahd;": "⤑",
  22988. "doteqdot;": "≑",
  22989. "DotEqual;": "≐",
  22990. "dotminus;": "∸",
  22991. "drbkarow;": "⤐",
  22992. "dzigrarr;": "⟿",
  22993. "elinters;": "⏧",
  22994. "emptyset;": "∅",
  22995. "eqvparsl;": "⧥",
  22996. "fpartint;": "⨍",
  22997. "geqslant;": "⩾",
  22998. "gesdotol;": "⪄",
  22999. "gnapprox;": "⪊",
  23000. "hksearow;": "⤥",
  23001. "hkswarow;": "⤦",
  23002. "imagline;": "ℐ",
  23003. "imagpart;": "ℑ",
  23004. "infintie;": "⧝",
  23005. "integers;": "ℤ",
  23006. "Integral;": "∫",
  23007. "intercal;": "⊺",
  23008. "intlarhk;": "⨗",
  23009. "laemptyv;": "⦴",
  23010. "ldrushar;": "⥋",
  23011. "leqslant;": "⩽",
  23012. "lesdotor;": "⪃",
  23013. "LessLess;": "⪡",
  23014. "llcorner;": "⌞",
  23015. "lnapprox;": "⪉",
  23016. "lrcorner;": "⌟",
  23017. "lurdshar;": "⥊",
  23018. "mapstoup;": "↥",
  23019. "multimap;": "⊸",
  23020. "naturals;": "ℕ",
  23021. "ncongdot;": "⩭̸",
  23022. "NotEqual;": "≠",
  23023. "notindot;": "⋵̸",
  23024. "NotTilde;": "≁",
  23025. "otimesas;": "⨶",
  23026. "parallel;": "∥",
  23027. "PartialD;": "∂",
  23028. "plusacir;": "⨣",
  23029. "pointint;": "⨕",
  23030. "Precedes;": "≺",
  23031. "precneqq;": "⪵",
  23032. "precnsim;": "⋨",
  23033. "profalar;": "⌮",
  23034. "profline;": "⌒",
  23035. "profsurf;": "⌓",
  23036. "raemptyv;": "⦳",
  23037. "realpart;": "ℜ",
  23038. "RightTee;": "⊢",
  23039. "rppolint;": "⨒",
  23040. "rtriltri;": "⧎",
  23041. "scpolint;": "⨓",
  23042. "setminus;": "∖",
  23043. "shortmid;": "∣",
  23044. "smeparsl;": "⧤",
  23045. "sqsubset;": "⊏",
  23046. "sqsupset;": "⊐",
  23047. "subseteq;": "⊆",
  23048. "Succeeds;": "≻",
  23049. "succneqq;": "⪶",
  23050. "succnsim;": "⋩",
  23051. "SuchThat;": "∋",
  23052. "Superset;": "⊃",
  23053. "supseteq;": "⊇",
  23054. "thetasym;": "ϑ",
  23055. "thicksim;": "∼",
  23056. "timesbar;": "⨱",
  23057. "triangle;": "▵",
  23058. "triminus;": "⨺",
  23059. "trpezium;": "⏢",
  23060. "Uarrocir;": "⥉",
  23061. "ulcorner;": "⌜",
  23062. "UnderBar;": "_",
  23063. "urcorner;": "⌝",
  23064. "varkappa;": "ϰ",
  23065. "varsigma;": "ς",
  23066. "vartheta;": "ϑ",
  23067. "backprime;": "‵",
  23068. "backsimeq;": "⋍",
  23069. "Backslash;": "∖",
  23070. "bigotimes;": "⨂",
  23071. "CenterDot;": "·",
  23072. "centerdot;": "·",
  23073. "checkmark;": "✓",
  23074. "CircleDot;": "⊙",
  23075. "complexes;": "ℂ",
  23076. "Congruent;": "≡",
  23077. "Coproduct;": "∐",
  23078. "dotsquare;": "⊡",
  23079. "DoubleDot;": "¨",
  23080. "DownArrow;": "↓",
  23081. "Downarrow;": "⇓",
  23082. "downarrow;": "↓",
  23083. "DownBreve;": "̑",
  23084. "gtrapprox;": "⪆",
  23085. "gtreqless;": "⋛",
  23086. "gvertneqq;": "≩︀",
  23087. "heartsuit;": "♥",
  23088. "HumpEqual;": "≏",
  23089. "LeftArrow;": "←",
  23090. "Leftarrow;": "⇐",
  23091. "leftarrow;": "←",
  23092. "LeftFloor;": "⌊",
  23093. "lesseqgtr;": "⋚",
  23094. "LessTilde;": "≲",
  23095. "lvertneqq;": "≨︀",
  23096. "Mellintrf;": "ℳ",
  23097. "MinusPlus;": "∓",
  23098. "ngeqslant;": "⩾̸",
  23099. "nleqslant;": "⩽̸",
  23100. "NotCupCap;": "≭",
  23101. "NotExists;": "∄",
  23102. "NotSubset;": "⊂⃒",
  23103. "nparallel;": "∦",
  23104. "nshortmid;": "∤",
  23105. "nsubseteq;": "⊈",
  23106. "nsupseteq;": "⊉",
  23107. "OverBrace;": "⏞",
  23108. "pitchfork;": "⋔",
  23109. "PlusMinus;": "±",
  23110. "rationals;": "ℚ",
  23111. "spadesuit;": "♠",
  23112. "subseteqq;": "⫅",
  23113. "subsetneq;": "⊊",
  23114. "supseteqq;": "⫆",
  23115. "supsetneq;": "⊋",
  23116. "Therefore;": "∴",
  23117. "therefore;": "∴",
  23118. "ThinSpace;": " ",
  23119. "triangleq;": "≜",
  23120. "TripleDot;": "⃛",
  23121. "UnionPlus;": "⊎",
  23122. "varpropto;": "∝",
  23123. "Bernoullis;": "ℬ",
  23124. "circledast;": "⊛",
  23125. "CirclePlus;": "⊕",
  23126. "complement;": "∁",
  23127. "curlywedge;": "⋏",
  23128. "eqslantgtr;": "⪖",
  23129. "EqualTilde;": "≂",
  23130. "Fouriertrf;": "ℱ",
  23131. "gtreqqless;": "⪌",
  23132. "ImaginaryI;": "ⅈ",
  23133. "Laplacetrf;": "ℒ",
  23134. "LeftVector;": "↼",
  23135. "lessapprox;": "⪅",
  23136. "lesseqqgtr;": "⪋",
  23137. "Lleftarrow;": "⇚",
  23138. "lmoustache;": "⎰",
  23139. "longmapsto;": "⟼",
  23140. "mapstodown;": "↧",
  23141. "mapstoleft;": "↤",
  23142. "nLeftarrow;": "⇍",
  23143. "nleftarrow;": "↚",
  23144. "NotElement;": "∉",
  23145. "NotGreater;": "≯",
  23146. "nsubseteqq;": "⫅̸",
  23147. "nsupseteqq;": "⫆̸",
  23148. "precapprox;": "⪷",
  23149. "Proportion;": "∷",
  23150. "RightArrow;": "→",
  23151. "Rightarrow;": "⇒",
  23152. "rightarrow;": "→",
  23153. "RightFloor;": "⌋",
  23154. "rmoustache;": "⎱",
  23155. "sqsubseteq;": "⊑",
  23156. "sqsupseteq;": "⊒",
  23157. "subsetneqq;": "⫋",
  23158. "succapprox;": "⪸",
  23159. "supsetneqq;": "⫌",
  23160. "ThickSpace;": "  ",
  23161. "TildeEqual;": "≃",
  23162. "TildeTilde;": "≈",
  23163. "UnderBrace;": "⏟",
  23164. "UpArrowBar;": "⤒",
  23165. "UpTeeArrow;": "↥",
  23166. "upuparrows;": "⇈",
  23167. "varepsilon;": "ϵ",
  23168. "varnothing;": "∅",
  23169. "backepsilon;": "϶",
  23170. "blacksquare;": "▪",
  23171. "circledcirc;": "⊚",
  23172. "circleddash;": "⊝",
  23173. "CircleMinus;": "⊖",
  23174. "CircleTimes;": "⊗",
  23175. "curlyeqprec;": "⋞",
  23176. "curlyeqsucc;": "⋟",
  23177. "diamondsuit;": "♦",
  23178. "eqslantless;": "⪕",
  23179. "Equilibrium;": "⇌",
  23180. "expectation;": "ℰ",
  23181. "GreaterLess;": "≷",
  23182. "LeftCeiling;": "⌈",
  23183. "LessGreater;": "≶",
  23184. "MediumSpace;": " ",
  23185. "NotLessLess;": "≪̸",
  23186. "NotPrecedes;": "⊀",
  23187. "NotSucceeds;": "⊁",
  23188. "NotSuperset;": "⊃⃒",
  23189. "nRightarrow;": "⇏",
  23190. "nrightarrow;": "↛",
  23191. "OverBracket;": "⎴",
  23192. "preccurlyeq;": "≼",
  23193. "precnapprox;": "⪹",
  23194. "quaternions;": "ℍ",
  23195. "RightVector;": "⇀",
  23196. "Rrightarrow;": "⇛",
  23197. "RuleDelayed;": "⧴",
  23198. "SmallCircle;": "∘",
  23199. "SquareUnion;": "⊔",
  23200. "straightphi;": "ϕ",
  23201. "SubsetEqual;": "⊆",
  23202. "succcurlyeq;": "≽",
  23203. "succnapprox;": "⪺",
  23204. "thickapprox;": "≈",
  23205. "UpDownArrow;": "↕",
  23206. "Updownarrow;": "⇕",
  23207. "updownarrow;": "↕",
  23208. "VerticalBar;": "∣",
  23209. "blacklozenge;": "⧫",
  23210. "DownArrowBar;": "⤓",
  23211. "DownTeeArrow;": "↧",
  23212. "ExponentialE;": "ⅇ",
  23213. "exponentiale;": "ⅇ",
  23214. "GreaterEqual;": "≥",
  23215. "GreaterTilde;": "≳",
  23216. "HilbertSpace;": "ℋ",
  23217. "HumpDownHump;": "≎",
  23218. "Intersection;": "⋂",
  23219. "LeftArrowBar;": "⇤",
  23220. "LeftTeeArrow;": "↤",
  23221. "LeftTriangle;": "⊲",
  23222. "LeftUpVector;": "↿",
  23223. "NotCongruent;": "≢",
  23224. "NotHumpEqual;": "≏̸",
  23225. "NotLessEqual;": "≰",
  23226. "NotLessTilde;": "≴",
  23227. "Proportional;": "∝",
  23228. "RightCeiling;": "⌉",
  23229. "risingdotseq;": "≓",
  23230. "RoundImplies;": "⥰",
  23231. "ShortUpArrow;": "↑",
  23232. "SquareSubset;": "⊏",
  23233. "triangledown;": "▿",
  23234. "triangleleft;": "◃",
  23235. "UnderBracket;": "⎵",
  23236. "varsubsetneq;": "⊊︀",
  23237. "varsupsetneq;": "⊋︀",
  23238. "VerticalLine;": "|",
  23239. "ApplyFunction;": "⁡",
  23240. "bigtriangleup;": "△",
  23241. "blacktriangle;": "▴",
  23242. "DifferentialD;": "ⅆ",
  23243. "divideontimes;": "⋇",
  23244. "DoubleLeftTee;": "⫤",
  23245. "DoubleUpArrow;": "⇑",
  23246. "fallingdotseq;": "≒",
  23247. "hookleftarrow;": "↩",
  23248. "leftarrowtail;": "↢",
  23249. "leftharpoonup;": "↼",
  23250. "LeftTeeVector;": "⥚",
  23251. "LeftVectorBar;": "⥒",
  23252. "LessFullEqual;": "≦",
  23253. "LongLeftArrow;": "⟵",
  23254. "Longleftarrow;": "⟸",
  23255. "longleftarrow;": "⟵",
  23256. "looparrowleft;": "↫",
  23257. "measuredangle;": "∡",
  23258. "NotEqualTilde;": "≂̸",
  23259. "NotTildeEqual;": "≄",
  23260. "NotTildeTilde;": "≉",
  23261. "ntriangleleft;": "⋪",
  23262. "Poincareplane;": "ℌ",
  23263. "PrecedesEqual;": "⪯",
  23264. "PrecedesTilde;": "≾",
  23265. "RightArrowBar;": "⇥",
  23266. "RightTeeArrow;": "↦",
  23267. "RightTriangle;": "⊳",
  23268. "RightUpVector;": "↾",
  23269. "shortparallel;": "∥",
  23270. "smallsetminus;": "∖",
  23271. "SucceedsEqual;": "⪰",
  23272. "SucceedsTilde;": "≿",
  23273. "SupersetEqual;": "⊇",
  23274. "triangleright;": "▹",
  23275. "UpEquilibrium;": "⥮",
  23276. "upharpoonleft;": "↿",
  23277. "varsubsetneqq;": "⫋︀",
  23278. "varsupsetneqq;": "⫌︀",
  23279. "VerticalTilde;": "≀",
  23280. "VeryThinSpace;": " ",
  23281. "curvearrowleft;": "↶",
  23282. "DiacriticalDot;": "˙",
  23283. "doublebarwedge;": "⌆",
  23284. "DoubleRightTee;": "⊨",
  23285. "downdownarrows;": "⇊",
  23286. "DownLeftVector;": "↽",
  23287. "GreaterGreater;": "⪢",
  23288. "hookrightarrow;": "↪",
  23289. "HorizontalLine;": "─",
  23290. "InvisibleComma;": "⁣",
  23291. "InvisibleTimes;": "⁢",
  23292. "LeftDownVector;": "⇃",
  23293. "leftleftarrows;": "⇇",
  23294. "LeftRightArrow;": "↔",
  23295. "Leftrightarrow;": "⇔",
  23296. "leftrightarrow;": "↔",
  23297. "leftthreetimes;": "⋋",
  23298. "LessSlantEqual;": "⩽",
  23299. "LongRightArrow;": "⟶",
  23300. "Longrightarrow;": "⟹",
  23301. "longrightarrow;": "⟶",
  23302. "looparrowright;": "↬",
  23303. "LowerLeftArrow;": "↙",
  23304. "NestedLessLess;": "≪",
  23305. "NotGreaterLess;": "≹",
  23306. "NotLessGreater;": "≸",
  23307. "NotSubsetEqual;": "⊈",
  23308. "NotVerticalBar;": "∤",
  23309. "nshortparallel;": "∦",
  23310. "ntriangleright;": "⋫",
  23311. "OpenCurlyQuote;": "‘",
  23312. "ReverseElement;": "∋",
  23313. "rightarrowtail;": "↣",
  23314. "rightharpoonup;": "⇀",
  23315. "RightTeeVector;": "⥛",
  23316. "RightVectorBar;": "⥓",
  23317. "ShortDownArrow;": "↓",
  23318. "ShortLeftArrow;": "←",
  23319. "SquareSuperset;": "⊐",
  23320. "TildeFullEqual;": "≅",
  23321. "trianglelefteq;": "⊴",
  23322. "upharpoonright;": "↾",
  23323. "UpperLeftArrow;": "↖",
  23324. "ZeroWidthSpace;": "​",
  23325. "bigtriangledown;": "▽",
  23326. "circlearrowleft;": "↺",
  23327. "CloseCurlyQuote;": "’",
  23328. "ContourIntegral;": "∮",
  23329. "curvearrowright;": "↷",
  23330. "DoubleDownArrow;": "⇓",
  23331. "DoubleLeftArrow;": "⇐",
  23332. "downharpoonleft;": "⇃",
  23333. "DownRightVector;": "⇁",
  23334. "leftharpoondown;": "↽",
  23335. "leftrightarrows;": "⇆",
  23336. "LeftRightVector;": "⥎",
  23337. "LeftTriangleBar;": "⧏",
  23338. "LeftUpTeeVector;": "⥠",
  23339. "LeftUpVectorBar;": "⥘",
  23340. "LowerRightArrow;": "↘",
  23341. "nLeftrightarrow;": "⇎",
  23342. "nleftrightarrow;": "↮",
  23343. "NotGreaterEqual;": "≱",
  23344. "NotGreaterTilde;": "≵",
  23345. "NotHumpDownHump;": "≎̸",
  23346. "NotLeftTriangle;": "⋪",
  23347. "NotSquareSubset;": "⊏̸",
  23348. "ntrianglelefteq;": "⋬",
  23349. "OverParenthesis;": "⏜",
  23350. "RightDownVector;": "⇂",
  23351. "rightleftarrows;": "⇄",
  23352. "rightsquigarrow;": "↝",
  23353. "rightthreetimes;": "⋌",
  23354. "ShortRightArrow;": "→",
  23355. "straightepsilon;": "ϵ",
  23356. "trianglerighteq;": "⊵",
  23357. "UpperRightArrow;": "↗",
  23358. "vartriangleleft;": "⊲",
  23359. "circlearrowright;": "↻",
  23360. "DiacriticalAcute;": "´",
  23361. "DiacriticalGrave;": "`",
  23362. "DiacriticalTilde;": "˜",
  23363. "DoubleRightArrow;": "⇒",
  23364. "DownArrowUpArrow;": "⇵",
  23365. "downharpoonright;": "⇂",
  23366. "EmptySmallSquare;": "◻",
  23367. "GreaterEqualLess;": "⋛",
  23368. "GreaterFullEqual;": "≧",
  23369. "LeftAngleBracket;": "⟨",
  23370. "LeftUpDownVector;": "⥑",
  23371. "LessEqualGreater;": "⋚",
  23372. "NonBreakingSpace;": " ",
  23373. "NotPrecedesEqual;": "⪯̸",
  23374. "NotRightTriangle;": "⋫",
  23375. "NotSucceedsEqual;": "⪰̸",
  23376. "NotSucceedsTilde;": "≿̸",
  23377. "NotSupersetEqual;": "⊉",
  23378. "ntrianglerighteq;": "⋭",
  23379. "rightharpoondown;": "⇁",
  23380. "rightrightarrows;": "⇉",
  23381. "RightTriangleBar;": "⧐",
  23382. "RightUpTeeVector;": "⥜",
  23383. "RightUpVectorBar;": "⥔",
  23384. "twoheadleftarrow;": "↞",
  23385. "UnderParenthesis;": "⏝",
  23386. "UpArrowDownArrow;": "⇅",
  23387. "vartriangleright;": "⊳",
  23388. "blacktriangledown;": "▾",
  23389. "blacktriangleleft;": "◂",
  23390. "DoubleUpDownArrow;": "⇕",
  23391. "DoubleVerticalBar;": "∥",
  23392. "DownLeftTeeVector;": "⥞",
  23393. "DownLeftVectorBar;": "⥖",
  23394. "FilledSmallSquare;": "◼",
  23395. "GreaterSlantEqual;": "⩾",
  23396. "LeftDoubleBracket;": "⟦",
  23397. "LeftDownTeeVector;": "⥡",
  23398. "LeftDownVectorBar;": "⥙",
  23399. "leftrightharpoons;": "⇋",
  23400. "LeftTriangleEqual;": "⊴",
  23401. "NegativeThinSpace;": "​",
  23402. "NotGreaterGreater;": "≫̸",
  23403. "NotLessSlantEqual;": "⩽̸",
  23404. "NotNestedLessLess;": "⪡̸",
  23405. "NotReverseElement;": "∌",
  23406. "NotSquareSuperset;": "⊐̸",
  23407. "NotTildeFullEqual;": "≇",
  23408. "RightAngleBracket;": "⟩",
  23409. "rightleftharpoons;": "⇌",
  23410. "RightUpDownVector;": "⥏",
  23411. "SquareSubsetEqual;": "⊑",
  23412. "twoheadrightarrow;": "↠",
  23413. "VerticalSeparator;": "❘",
  23414. "blacktriangleright;": "▸",
  23415. "DownRightTeeVector;": "⥟",
  23416. "DownRightVectorBar;": "⥗",
  23417. "LongLeftRightArrow;": "⟷",
  23418. "Longleftrightarrow;": "⟺",
  23419. "longleftrightarrow;": "⟷",
  23420. "NegativeThickSpace;": "​",
  23421. "NotLeftTriangleBar;": "⧏̸",
  23422. "PrecedesSlantEqual;": "≼",
  23423. "ReverseEquilibrium;": "⇋",
  23424. "RightDoubleBracket;": "⟧",
  23425. "RightDownTeeVector;": "⥝",
  23426. "RightDownVectorBar;": "⥕",
  23427. "RightTriangleEqual;": "⊵",
  23428. "SquareIntersection;": "⊓",
  23429. "SucceedsSlantEqual;": "≽",
  23430. "DoubleLongLeftArrow;": "⟸",
  23431. "DownLeftRightVector;": "⥐",
  23432. "LeftArrowRightArrow;": "⇆",
  23433. "leftrightsquigarrow;": "↭",
  23434. "NegativeMediumSpace;": "​",
  23435. "NotGreaterFullEqual;": "≧̸",
  23436. "NotRightTriangleBar;": "⧐̸",
  23437. "RightArrowLeftArrow;": "⇄",
  23438. "SquareSupersetEqual;": "⊒",
  23439. "CapitalDifferentialD;": "ⅅ",
  23440. "DoubleLeftRightArrow;": "⇔",
  23441. "DoubleLongRightArrow;": "⟹",
  23442. "EmptyVerySmallSquare;": "▫",
  23443. "NestedGreaterGreater;": "≫",
  23444. "NotDoubleVerticalBar;": "∦",
  23445. "NotGreaterSlantEqual;": "⩾̸",
  23446. "NotLeftTriangleEqual;": "⋬",
  23447. "NotSquareSubsetEqual;": "⋢",
  23448. "OpenCurlyDoubleQuote;": "“",
  23449. "ReverseUpEquilibrium;": "⥯",
  23450. "CloseCurlyDoubleQuote;": "”",
  23451. "DoubleContourIntegral;": "∯",
  23452. "FilledVerySmallSquare;": "▪",
  23453. "NegativeVeryThinSpace;": "​",
  23454. "NotPrecedesSlantEqual;": "⋠",
  23455. "NotRightTriangleEqual;": "⋭",
  23456. "NotSucceedsSlantEqual;": "⋡",
  23457. "DiacriticalDoubleAcute;": "˝",
  23458. "NotSquareSupersetEqual;": "⋣",
  23459. "NotNestedGreaterGreater;": "⪢̸",
  23460. "ClockwiseContourIntegral;": "∲",
  23461. "DoubleLongLeftRightArrow;": "⟺",
  23462. "CounterClockwiseContourIntegral;": "∳"
  23463. };
  23464. // lazy compute this to make this file tree-shakable for browser
  23465. let maxCRNameLength;
  23466. const decodeHtml = (rawText, asAttr) => {
  23467. let offset = 0;
  23468. const end = rawText.length;
  23469. let decodedText = '';
  23470. function advance(length) {
  23471. offset += length;
  23472. rawText = rawText.slice(length);
  23473. }
  23474. while (offset < end) {
  23475. const head = /&(?:#x?)?/i.exec(rawText);
  23476. if (!head || offset + head.index >= end) {
  23477. const remaining = end - offset;
  23478. decodedText += rawText.slice(0, remaining);
  23479. advance(remaining);
  23480. break;
  23481. }
  23482. // Advance to the "&".
  23483. decodedText += rawText.slice(0, head.index);
  23484. advance(head.index);
  23485. if (head[0] === '&') {
  23486. // Named character reference.
  23487. let name = '';
  23488. let value = undefined;
  23489. if (/[0-9a-z]/i.test(rawText[1])) {
  23490. if (!maxCRNameLength) {
  23491. maxCRNameLength = Object.keys(namedCharacterReferences).reduce((max, name) => Math.max(max, name.length), 0);
  23492. }
  23493. for (let length = maxCRNameLength; !value && length > 0; --length) {
  23494. name = rawText.slice(1, 1 + length);
  23495. value = namedCharacterReferences[name];
  23496. }
  23497. if (value) {
  23498. const semi = name.endsWith(';');
  23499. if (asAttr &&
  23500. !semi &&
  23501. /[=a-z0-9]/i.test(rawText[name.length + 1] || '')) {
  23502. decodedText += '&' + name;
  23503. advance(1 + name.length);
  23504. }
  23505. else {
  23506. decodedText += value;
  23507. advance(1 + name.length);
  23508. }
  23509. }
  23510. else {
  23511. decodedText += '&' + name;
  23512. advance(1 + name.length);
  23513. }
  23514. }
  23515. else {
  23516. decodedText += '&';
  23517. advance(1);
  23518. }
  23519. }
  23520. else {
  23521. // Numeric character reference.
  23522. const hex = head[0] === '&#x';
  23523. const pattern = hex ? /^&#x([0-9a-f]+);?/i : /^&#([0-9]+);?/;
  23524. const body = pattern.exec(rawText);
  23525. if (!body) {
  23526. decodedText += head[0];
  23527. advance(head[0].length);
  23528. }
  23529. else {
  23530. // https://html.spec.whatwg.org/multipage/parsing.html#numeric-character-reference-end-state
  23531. let cp = Number.parseInt(body[1], hex ? 16 : 10);
  23532. if (cp === 0) {
  23533. cp = 0xfffd;
  23534. }
  23535. else if (cp > 0x10ffff) {
  23536. cp = 0xfffd;
  23537. }
  23538. else if (cp >= 0xd800 && cp <= 0xdfff) {
  23539. cp = 0xfffd;
  23540. }
  23541. else if ((cp >= 0xfdd0 && cp <= 0xfdef) || (cp & 0xfffe) === 0xfffe) ;
  23542. else if ((cp >= 0x01 && cp <= 0x08) ||
  23543. cp === 0x0b ||
  23544. (cp >= 0x0d && cp <= 0x1f) ||
  23545. (cp >= 0x7f && cp <= 0x9f)) {
  23546. cp = CCR_REPLACEMENTS[cp] || cp;
  23547. }
  23548. decodedText += String.fromCodePoint(cp);
  23549. advance(body[0].length);
  23550. }
  23551. }
  23552. }
  23553. return decodedText;
  23554. };
  23555. // https://html.spec.whatwg.org/multipage/parsing.html#numeric-character-reference-end-state
  23556. const CCR_REPLACEMENTS = {
  23557. 0x80: 0x20ac,
  23558. 0x82: 0x201a,
  23559. 0x83: 0x0192,
  23560. 0x84: 0x201e,
  23561. 0x85: 0x2026,
  23562. 0x86: 0x2020,
  23563. 0x87: 0x2021,
  23564. 0x88: 0x02c6,
  23565. 0x89: 0x2030,
  23566. 0x8a: 0x0160,
  23567. 0x8b: 0x2039,
  23568. 0x8c: 0x0152,
  23569. 0x8e: 0x017d,
  23570. 0x91: 0x2018,
  23571. 0x92: 0x2019,
  23572. 0x93: 0x201c,
  23573. 0x94: 0x201d,
  23574. 0x95: 0x2022,
  23575. 0x96: 0x2013,
  23576. 0x97: 0x2014,
  23577. 0x98: 0x02dc,
  23578. 0x99: 0x2122,
  23579. 0x9a: 0x0161,
  23580. 0x9b: 0x203a,
  23581. 0x9c: 0x0153,
  23582. 0x9e: 0x017e,
  23583. 0x9f: 0x0178
  23584. };
  23585. const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
  23586. const parserOptions = {
  23587. isVoidTag,
  23588. isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
  23589. isPreTag: tag => tag === 'pre',
  23590. decodeEntities: decodeHtml,
  23591. isBuiltInComponent: (tag) => {
  23592. if (isBuiltInType(tag, `Transition`)) {
  23593. return TRANSITION;
  23594. }
  23595. else if (isBuiltInType(tag, `TransitionGroup`)) {
  23596. return TRANSITION_GROUP;
  23597. }
  23598. },
  23599. // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
  23600. getNamespace(tag, parent) {
  23601. let ns = parent ? parent.ns : 0 /* HTML */;
  23602. if (parent && ns === 2 /* MATH_ML */) {
  23603. if (parent.tag === 'annotation-xml') {
  23604. if (tag === 'svg') {
  23605. return 1 /* SVG */;
  23606. }
  23607. if (parent.props.some(a => a.type === 6 /* ATTRIBUTE */ &&
  23608. a.name === 'encoding' &&
  23609. a.value != null &&
  23610. (a.value.content === 'text/html' ||
  23611. a.value.content === 'application/xhtml+xml'))) {
  23612. ns = 0 /* HTML */;
  23613. }
  23614. }
  23615. else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
  23616. tag !== 'mglyph' &&
  23617. tag !== 'malignmark') {
  23618. ns = 0 /* HTML */;
  23619. }
  23620. }
  23621. else if (parent && ns === 1 /* SVG */) {
  23622. if (parent.tag === 'foreignObject' ||
  23623. parent.tag === 'desc' ||
  23624. parent.tag === 'title') {
  23625. ns = 0 /* HTML */;
  23626. }
  23627. }
  23628. if (ns === 0 /* HTML */) {
  23629. if (tag === 'svg') {
  23630. return 1 /* SVG */;
  23631. }
  23632. if (tag === 'math') {
  23633. return 2 /* MATH_ML */;
  23634. }
  23635. }
  23636. return ns;
  23637. },
  23638. // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
  23639. getTextMode({ tag, ns }) {
  23640. if (ns === 0 /* HTML */) {
  23641. if (tag === 'textarea' || tag === 'title') {
  23642. return 1 /* RCDATA */;
  23643. }
  23644. if (isRawTextContainer(tag)) {
  23645. return 2 /* RAWTEXT */;
  23646. }
  23647. }
  23648. return 0 /* DATA */;
  23649. }
  23650. };
  23651. // Parse inline CSS strings for static style attributes into an object.
  23652. // This is a NodeTransform since it works on the static `style` attribute and
  23653. // converts it into a dynamic equivalent:
  23654. // style="color: red" -> :style='{ "color": "red" }'
  23655. // It is then processed by `transformElement` and included in the generated
  23656. // props.
  23657. const transformStyle = node => {
  23658. if (node.type === 1 /* ELEMENT */) {
  23659. node.props.forEach((p, i) => {
  23660. if (p.type === 6 /* ATTRIBUTE */ && p.name === 'style' && p.value) {
  23661. // replace p with an expression node
  23662. node.props[i] = {
  23663. type: 7 /* DIRECTIVE */,
  23664. name: `bind`,
  23665. arg: createSimpleExpression(`style`, true, p.loc),
  23666. exp: parseInlineCSS(p.value.content, p.loc),
  23667. modifiers: [],
  23668. loc: p.loc
  23669. };
  23670. }
  23671. });
  23672. }
  23673. };
  23674. const parseInlineCSS = (cssText, loc) => {
  23675. const normalized = parseStringStyle(cssText);
  23676. return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* CAN_STRINGIFY */);
  23677. };
  23678. function createDOMCompilerError(code, loc) {
  23679. return createCompilerError(code, loc, DOMErrorMessages );
  23680. }
  23681. const DOMErrorMessages = {
  23682. [50 /* X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
  23683. [51 /* X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
  23684. [52 /* X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
  23685. [53 /* X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
  23686. [54 /* X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
  23687. [55 /* X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
  23688. [56 /* 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.`,
  23689. [57 /* X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
  23690. [58 /* X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
  23691. [59 /* X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
  23692. [60 /* X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
  23693. };
  23694. const transformVHtml = (dir, node, context) => {
  23695. const { exp, loc } = dir;
  23696. if (!exp) {
  23697. context.onError(createDOMCompilerError(50 /* X_V_HTML_NO_EXPRESSION */, loc));
  23698. }
  23699. if (node.children.length) {
  23700. context.onError(createDOMCompilerError(51 /* X_V_HTML_WITH_CHILDREN */, loc));
  23701. node.children.length = 0;
  23702. }
  23703. return {
  23704. props: [
  23705. createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
  23706. ]
  23707. };
  23708. };
  23709. const transformVText = (dir, node, context) => {
  23710. const { exp, loc } = dir;
  23711. if (!exp) {
  23712. context.onError(createDOMCompilerError(52 /* X_V_TEXT_NO_EXPRESSION */, loc));
  23713. }
  23714. if (node.children.length) {
  23715. context.onError(createDOMCompilerError(53 /* X_V_TEXT_WITH_CHILDREN */, loc));
  23716. node.children.length = 0;
  23717. }
  23718. return {
  23719. props: [
  23720. createObjectProperty(createSimpleExpression(`textContent`, true), exp
  23721. ? createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
  23722. : createSimpleExpression('', true))
  23723. ]
  23724. };
  23725. };
  23726. const transformModel$1 = (dir, node, context) => {
  23727. const baseResult = transformModel(dir, node, context);
  23728. // base transform has errors OR component v-model (only need props)
  23729. if (!baseResult.props.length || node.tagType === 1 /* COMPONENT */) {
  23730. return baseResult;
  23731. }
  23732. if (dir.arg) {
  23733. context.onError(createDOMCompilerError(55 /* X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
  23734. }
  23735. function checkDuplicatedValue() {
  23736. const value = findProp(node, 'value');
  23737. if (value) {
  23738. context.onError(createDOMCompilerError(57 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
  23739. }
  23740. }
  23741. const { tag } = node;
  23742. const isCustomElement = context.isCustomElement(tag);
  23743. if (tag === 'input' ||
  23744. tag === 'textarea' ||
  23745. tag === 'select' ||
  23746. isCustomElement) {
  23747. let directiveToUse = V_MODEL_TEXT;
  23748. let isInvalidType = false;
  23749. if (tag === 'input' || isCustomElement) {
  23750. const type = findProp(node, `type`);
  23751. if (type) {
  23752. if (type.type === 7 /* DIRECTIVE */) {
  23753. // :type="foo"
  23754. directiveToUse = V_MODEL_DYNAMIC;
  23755. }
  23756. else if (type.value) {
  23757. switch (type.value.content) {
  23758. case 'radio':
  23759. directiveToUse = V_MODEL_RADIO;
  23760. break;
  23761. case 'checkbox':
  23762. directiveToUse = V_MODEL_CHECKBOX;
  23763. break;
  23764. case 'file':
  23765. isInvalidType = true;
  23766. context.onError(createDOMCompilerError(56 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
  23767. break;
  23768. default:
  23769. // text type
  23770. checkDuplicatedValue();
  23771. break;
  23772. }
  23773. }
  23774. }
  23775. else if (hasDynamicKeyVBind(node)) {
  23776. // element has bindings with dynamic keys, which can possibly contain
  23777. // "type".
  23778. directiveToUse = V_MODEL_DYNAMIC;
  23779. }
  23780. else {
  23781. // text type
  23782. checkDuplicatedValue();
  23783. }
  23784. }
  23785. else if (tag === 'select') {
  23786. directiveToUse = V_MODEL_SELECT;
  23787. }
  23788. else {
  23789. // textarea
  23790. checkDuplicatedValue();
  23791. }
  23792. // inject runtime directive
  23793. // by returning the helper symbol via needRuntime
  23794. // the import will replaced a resolveDirective call.
  23795. if (!isInvalidType) {
  23796. baseResult.needRuntime = context.helper(directiveToUse);
  23797. }
  23798. }
  23799. else {
  23800. context.onError(createDOMCompilerError(54 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
  23801. }
  23802. // native vmodel doesn't need the `modelValue` props since they are also
  23803. // passed to the runtime as `binding.value`. removing it reduces code size.
  23804. baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
  23805. p.key.content === 'modelValue'));
  23806. return baseResult;
  23807. };
  23808. const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
  23809. const isNonKeyModifier = /*#__PURE__*/ makeMap(
  23810. // event propagation management
  23811. `stop,prevent,self,` +
  23812. // system modifiers + exact
  23813. `ctrl,shift,alt,meta,exact,` +
  23814. // mouse
  23815. `middle`);
  23816. // left & right could be mouse or key modifiers based on event type
  23817. const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
  23818. const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
  23819. const resolveModifiers = (key, modifiers, context, loc) => {
  23820. const keyModifiers = [];
  23821. const nonKeyModifiers = [];
  23822. const eventOptionModifiers = [];
  23823. for (let i = 0; i < modifiers.length; i++) {
  23824. const modifier = modifiers[i];
  23825. if (isEventOptionModifier(modifier)) {
  23826. // eventOptionModifiers: modifiers for addEventListener() options,
  23827. // e.g. .passive & .capture
  23828. eventOptionModifiers.push(modifier);
  23829. }
  23830. else {
  23831. // runtimeModifiers: modifiers that needs runtime guards
  23832. if (maybeKeyModifier(modifier)) {
  23833. if (isStaticExp(key)) {
  23834. if (isKeyboardEvent(key.content)) {
  23835. keyModifiers.push(modifier);
  23836. }
  23837. else {
  23838. nonKeyModifiers.push(modifier);
  23839. }
  23840. }
  23841. else {
  23842. keyModifiers.push(modifier);
  23843. nonKeyModifiers.push(modifier);
  23844. }
  23845. }
  23846. else {
  23847. if (isNonKeyModifier(modifier)) {
  23848. nonKeyModifiers.push(modifier);
  23849. }
  23850. else {
  23851. keyModifiers.push(modifier);
  23852. }
  23853. }
  23854. }
  23855. }
  23856. return {
  23857. keyModifiers,
  23858. nonKeyModifiers,
  23859. eventOptionModifiers
  23860. };
  23861. };
  23862. const transformClick = (key, event) => {
  23863. const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
  23864. return isStaticClick
  23865. ? createSimpleExpression(event, true)
  23866. : key.type !== 4 /* SIMPLE_EXPRESSION */
  23867. ? createCompoundExpression([
  23868. `(`,
  23869. key,
  23870. `) === "onClick" ? "${event}" : (`,
  23871. key,
  23872. `)`
  23873. ])
  23874. : key;
  23875. };
  23876. const transformOn$1 = (dir, node, context) => {
  23877. return transformOn(dir, node, context, baseResult => {
  23878. const { modifiers } = dir;
  23879. if (!modifiers.length)
  23880. return baseResult;
  23881. let { key, value: handlerExp } = baseResult.props[0];
  23882. const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
  23883. // normalize click.right and click.middle since they don't actually fire
  23884. if (nonKeyModifiers.includes('right')) {
  23885. key = transformClick(key, `onContextmenu`);
  23886. }
  23887. if (nonKeyModifiers.includes('middle')) {
  23888. key = transformClick(key, `onMouseup`);
  23889. }
  23890. if (nonKeyModifiers.length) {
  23891. handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
  23892. handlerExp,
  23893. JSON.stringify(nonKeyModifiers)
  23894. ]);
  23895. }
  23896. if (keyModifiers.length &&
  23897. // if event name is dynamic, always wrap with keys guard
  23898. (!isStaticExp(key) || isKeyboardEvent(key.content))) {
  23899. handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
  23900. handlerExp,
  23901. JSON.stringify(keyModifiers)
  23902. ]);
  23903. }
  23904. if (eventOptionModifiers.length) {
  23905. const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
  23906. key = isStaticExp(key)
  23907. ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
  23908. : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
  23909. }
  23910. return {
  23911. props: [createObjectProperty(key, handlerExp)]
  23912. };
  23913. });
  23914. };
  23915. const transformShow = (dir, node, context) => {
  23916. const { exp, loc } = dir;
  23917. if (!exp) {
  23918. context.onError(createDOMCompilerError(58 /* X_V_SHOW_NO_EXPRESSION */, loc));
  23919. }
  23920. return {
  23921. props: [],
  23922. needRuntime: context.helper(V_SHOW)
  23923. };
  23924. };
  23925. const warnTransitionChildren = (node, context) => {
  23926. if (node.type === 1 /* ELEMENT */ &&
  23927. node.tagType === 1 /* COMPONENT */) {
  23928. const component = context.isBuiltInComponent(node.tag);
  23929. if (component === TRANSITION) {
  23930. return () => {
  23931. if (node.children.length && hasMultipleChildren(node)) {
  23932. context.onError(createDOMCompilerError(59 /* X_TRANSITION_INVALID_CHILDREN */, {
  23933. start: node.children[0].loc.start,
  23934. end: node.children[node.children.length - 1].loc.end,
  23935. source: ''
  23936. }));
  23937. }
  23938. };
  23939. }
  23940. }
  23941. };
  23942. function hasMultipleChildren(node) {
  23943. // #1352 filter out potential comment nodes.
  23944. const children = (node.children = node.children.filter(c => c.type !== 3 /* COMMENT */ &&
  23945. !(c.type === 2 /* TEXT */ && !c.content.trim())));
  23946. const child = children[0];
  23947. return (children.length !== 1 ||
  23948. child.type === 11 /* FOR */ ||
  23949. (child.type === 9 /* IF */ && child.branches.some(hasMultipleChildren)));
  23950. }
  23951. /**
  23952. * This module is Node-only.
  23953. */
  23954. /**
  23955. * Regex for replacing placeholders for embedded constant variables
  23956. * (e.g. import URL string constants generated by compiler-sfc)
  23957. */
  23958. const expReplaceRE = /__VUE_EXP_START__(.*?)__VUE_EXP_END__/g;
  23959. /**
  23960. * Turn eligible hoisted static trees into stringified static nodes, e.g.
  23961. *
  23962. * ```js
  23963. * const _hoisted_1 = createStaticVNode(`<div class="foo">bar</div>`)
  23964. * ```
  23965. *
  23966. * A single static vnode can contain stringified content for **multiple**
  23967. * consecutive nodes (element and plain text), called a "chunk".
  23968. * `@vue/runtime-dom` will create the content via innerHTML in a hidden
  23969. * container element and insert all the nodes in place. The call must also
  23970. * provide the number of nodes contained in the chunk so that during hydration
  23971. * we can know how many nodes the static vnode should adopt.
  23972. *
  23973. * The optimization scans a children list that contains hoisted nodes, and
  23974. * tries to find the largest chunk of consecutive hoisted nodes before running
  23975. * into a non-hoisted node or the end of the list. A chunk is then converted
  23976. * into a single static vnode and replaces the hoisted expression of the first
  23977. * node in the chunk. Other nodes in the chunk are considered "merged" and
  23978. * therefore removed from both the hoist list and the children array.
  23979. *
  23980. * This optimization is only performed in Node.js.
  23981. */
  23982. const stringifyStatic = (children, context, parent) => {
  23983. // bail stringification for slot content
  23984. if (context.scopes.vSlot > 0) {
  23985. return;
  23986. }
  23987. let nc = 0; // current node count
  23988. let ec = 0; // current element with binding count
  23989. const currentChunk = [];
  23990. const stringifyCurrentChunk = (currentIndex) => {
  23991. if (nc >= 20 /* NODE_COUNT */ ||
  23992. ec >= 5 /* ELEMENT_WITH_BINDING_COUNT */) {
  23993. // combine all currently eligible nodes into a single static vnode call
  23994. const staticCall = createCallExpression(context.helper(CREATE_STATIC), [
  23995. JSON.stringify(currentChunk.map(node => stringifyNode(node, context)).join('')).replace(expReplaceRE, `" + $1 + "`),
  23996. // the 2nd argument indicates the number of DOM nodes this static vnode
  23997. // will insert / hydrate
  23998. String(currentChunk.length)
  23999. ]);
  24000. // replace the first node's hoisted expression with the static vnode call
  24001. replaceHoist(currentChunk[0], staticCall, context);
  24002. if (currentChunk.length > 1) {
  24003. for (let i = 1; i < currentChunk.length; i++) {
  24004. // for the merged nodes, set their hoisted expression to null
  24005. replaceHoist(currentChunk[i], null, context);
  24006. }
  24007. // also remove merged nodes from children
  24008. const deleteCount = currentChunk.length - 1;
  24009. children.splice(currentIndex - currentChunk.length + 1, deleteCount);
  24010. return deleteCount;
  24011. }
  24012. }
  24013. return 0;
  24014. };
  24015. let i = 0;
  24016. for (; i < children.length; i++) {
  24017. const child = children[i];
  24018. const hoisted = getHoistedNode(child);
  24019. if (hoisted) {
  24020. // presence of hoisted means child must be a stringifiable node
  24021. const node = child;
  24022. const result = analyzeNode(node);
  24023. if (result) {
  24024. // node is stringifiable, record state
  24025. nc += result[0];
  24026. ec += result[1];
  24027. currentChunk.push(node);
  24028. continue;
  24029. }
  24030. }
  24031. // we only reach here if we ran into a node that is not stringifiable
  24032. // check if currently analyzed nodes meet criteria for stringification.
  24033. // adjust iteration index
  24034. i -= stringifyCurrentChunk(i);
  24035. // reset state
  24036. nc = 0;
  24037. ec = 0;
  24038. currentChunk.length = 0;
  24039. }
  24040. // in case the last node was also stringifiable
  24041. stringifyCurrentChunk(i);
  24042. };
  24043. const getHoistedNode = (node) => ((node.type === 1 /* ELEMENT */ && node.tagType === 0 /* ELEMENT */) ||
  24044. node.type == 12 /* TEXT_CALL */) &&
  24045. node.codegenNode &&
  24046. node.codegenNode.type === 4 /* SIMPLE_EXPRESSION */ &&
  24047. node.codegenNode.hoisted;
  24048. const dataAriaRE = /^(data|aria)-/;
  24049. const isStringifiableAttr = (name, ns) => {
  24050. return ((ns === 0 /* HTML */
  24051. ? isKnownHtmlAttr(name)
  24052. : ns === 1 /* SVG */
  24053. ? isKnownSvgAttr(name)
  24054. : false) || dataAriaRE.test(name));
  24055. };
  24056. const replaceHoist = (node, replacement, context) => {
  24057. const hoistToReplace = node.codegenNode.hoisted;
  24058. context.hoists[context.hoists.indexOf(hoistToReplace)] = replacement;
  24059. };
  24060. const isNonStringifiable = /*#__PURE__*/ makeMap(`caption,thead,tr,th,tbody,td,tfoot,colgroup,col`);
  24061. /**
  24062. * for a hoisted node, analyze it and return:
  24063. * - false: bailed (contains non-stringifiable props or runtime constant)
  24064. * - [nc, ec] where
  24065. * - nc is the number of nodes inside
  24066. * - ec is the number of element with bindings inside
  24067. */
  24068. function analyzeNode(node) {
  24069. if (node.type === 1 /* ELEMENT */ && isNonStringifiable(node.tag)) {
  24070. return false;
  24071. }
  24072. if (node.type === 12 /* TEXT_CALL */) {
  24073. return [1, 0];
  24074. }
  24075. let nc = 1; // node count
  24076. let ec = node.props.length > 0 ? 1 : 0; // element w/ binding count
  24077. let bailed = false;
  24078. const bail = () => {
  24079. bailed = true;
  24080. return false;
  24081. };
  24082. // TODO: check for cases where using innerHTML will result in different
  24083. // output compared to imperative node insertions.
  24084. // probably only need to check for most common case
  24085. // i.e. non-phrasing-content tags inside `<p>`
  24086. function walk(node) {
  24087. for (let i = 0; i < node.props.length; i++) {
  24088. const p = node.props[i];
  24089. // bail on non-attr bindings
  24090. if (p.type === 6 /* ATTRIBUTE */ &&
  24091. !isStringifiableAttr(p.name, node.ns)) {
  24092. return bail();
  24093. }
  24094. if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind') {
  24095. // bail on non-attr bindings
  24096. if (p.arg &&
  24097. (p.arg.type === 8 /* COMPOUND_EXPRESSION */ ||
  24098. (p.arg.isStatic && !isStringifiableAttr(p.arg.content, node.ns)))) {
  24099. return bail();
  24100. }
  24101. if (p.exp &&
  24102. (p.exp.type === 8 /* COMPOUND_EXPRESSION */ ||
  24103. p.exp.constType < 3 /* CAN_STRINGIFY */)) {
  24104. return bail();
  24105. }
  24106. }
  24107. }
  24108. for (let i = 0; i < node.children.length; i++) {
  24109. nc++;
  24110. const child = node.children[i];
  24111. if (child.type === 1 /* ELEMENT */) {
  24112. if (child.props.length > 0) {
  24113. ec++;
  24114. }
  24115. walk(child);
  24116. if (bailed) {
  24117. return false;
  24118. }
  24119. }
  24120. }
  24121. return true;
  24122. }
  24123. return walk(node) ? [nc, ec] : false;
  24124. }
  24125. function stringifyNode(node, context) {
  24126. if (isString(node)) {
  24127. return node;
  24128. }
  24129. if (isSymbol(node)) {
  24130. return ``;
  24131. }
  24132. switch (node.type) {
  24133. case 1 /* ELEMENT */:
  24134. return stringifyElement(node, context);
  24135. case 2 /* TEXT */:
  24136. return escapeHtml(node.content);
  24137. case 3 /* COMMENT */:
  24138. return `<!--${escapeHtml(node.content)}-->`;
  24139. case 5 /* INTERPOLATION */:
  24140. return escapeHtml(toDisplayString(evaluateConstant(node.content)));
  24141. case 8 /* COMPOUND_EXPRESSION */:
  24142. return escapeHtml(evaluateConstant(node));
  24143. case 12 /* TEXT_CALL */:
  24144. return stringifyNode(node.content, context);
  24145. default:
  24146. // static trees will not contain if/for nodes
  24147. return '';
  24148. }
  24149. }
  24150. function stringifyElement(node, context) {
  24151. let res = `<${node.tag}`;
  24152. for (let i = 0; i < node.props.length; i++) {
  24153. const p = node.props[i];
  24154. if (p.type === 6 /* ATTRIBUTE */) {
  24155. res += ` ${p.name}`;
  24156. if (p.value) {
  24157. res += `="${escapeHtml(p.value.content)}"`;
  24158. }
  24159. }
  24160. else if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind') {
  24161. const exp = p.exp;
  24162. if (exp.content[0] === '_') {
  24163. // internally generated string constant references
  24164. // e.g. imported URL strings via compiler-sfc transformAssetUrl plugin
  24165. res += ` ${p.arg.content}="__VUE_EXP_START__${exp.content}__VUE_EXP_END__"`;
  24166. continue;
  24167. }
  24168. // constant v-bind, e.g. :foo="1"
  24169. let evaluated = evaluateConstant(exp);
  24170. if (evaluated != null) {
  24171. const arg = p.arg && p.arg.content;
  24172. if (arg === 'class') {
  24173. evaluated = normalizeClass(evaluated);
  24174. }
  24175. else if (arg === 'style') {
  24176. evaluated = stringifyStyle(normalizeStyle(evaluated));
  24177. }
  24178. res += ` ${p.arg.content}="${escapeHtml(evaluated)}"`;
  24179. }
  24180. }
  24181. }
  24182. if (context.scopeId) {
  24183. res += ` ${context.scopeId}`;
  24184. }
  24185. res += `>`;
  24186. for (let i = 0; i < node.children.length; i++) {
  24187. res += stringifyNode(node.children[i], context);
  24188. }
  24189. if (!isVoidTag(node.tag)) {
  24190. res += `</${node.tag}>`;
  24191. }
  24192. return res;
  24193. }
  24194. // __UNSAFE__
  24195. // Reason: eval.
  24196. // It's technically safe to eval because only constant expressions are possible
  24197. // here, e.g. `{{ 1 }}` or `{{ 'foo' }}`
  24198. // in addition, constant exps bail on presence of parens so you can't even
  24199. // run JSFuck in here. But we mark it unsafe for security review purposes.
  24200. // (see compiler-core/src/transformExpressions)
  24201. function evaluateConstant(exp) {
  24202. if (exp.type === 4 /* SIMPLE_EXPRESSION */) {
  24203. return new Function(`return ${exp.content}`)();
  24204. }
  24205. else {
  24206. // compound
  24207. let res = ``;
  24208. exp.children.forEach(c => {
  24209. if (isString(c) || isSymbol(c)) {
  24210. return;
  24211. }
  24212. if (c.type === 2 /* TEXT */) {
  24213. res += c.content;
  24214. }
  24215. else if (c.type === 5 /* INTERPOLATION */) {
  24216. res += toDisplayString(evaluateConstant(c.content));
  24217. }
  24218. else {
  24219. res += evaluateConstant(c);
  24220. }
  24221. });
  24222. return res;
  24223. }
  24224. }
  24225. const ignoreSideEffectTags = (node, context) => {
  24226. if (node.type === 1 /* ELEMENT */ &&
  24227. node.tagType === 0 /* ELEMENT */ &&
  24228. (node.tag === 'script' || node.tag === 'style')) {
  24229. context.onError(createDOMCompilerError(60 /* X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
  24230. context.removeNode();
  24231. }
  24232. };
  24233. const DOMNodeTransforms = [
  24234. transformStyle,
  24235. ...([warnTransitionChildren] )
  24236. ];
  24237. const DOMDirectiveTransforms = {
  24238. cloak: noopDirectiveTransform,
  24239. html: transformVHtml,
  24240. text: transformVText,
  24241. model: transformModel$1,
  24242. on: transformOn$1,
  24243. show: transformShow
  24244. };
  24245. function compile(template, options = {}) {
  24246. return baseCompile(template, extend({}, parserOptions, options, {
  24247. nodeTransforms: [
  24248. // ignore <script> and <tag>
  24249. // this is not put inside DOMNodeTransforms because that list is used
  24250. // by compiler-ssr to generate vnode fallback branches
  24251. ignoreSideEffectTags,
  24252. ...DOMNodeTransforms,
  24253. ...(options.nodeTransforms || [])
  24254. ],
  24255. directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
  24256. transformHoist: stringifyStatic
  24257. }));
  24258. }
  24259. function parse$1(template, options = {}) {
  24260. return baseParse(template, extend({}, parserOptions, options));
  24261. }
  24262. var CompilerDOM = /*#__PURE__*/Object.freeze({
  24263. __proto__: null,
  24264. parserOptions: parserOptions,
  24265. DOMNodeTransforms: DOMNodeTransforms,
  24266. DOMDirectiveTransforms: DOMDirectiveTransforms,
  24267. compile: compile,
  24268. parse: parse$1,
  24269. transformStyle: transformStyle,
  24270. createDOMCompilerError: createDOMCompilerError,
  24271. V_MODEL_RADIO: V_MODEL_RADIO,
  24272. V_MODEL_CHECKBOX: V_MODEL_CHECKBOX,
  24273. V_MODEL_TEXT: V_MODEL_TEXT,
  24274. V_MODEL_SELECT: V_MODEL_SELECT,
  24275. V_MODEL_DYNAMIC: V_MODEL_DYNAMIC,
  24276. V_ON_WITH_MODIFIERS: V_ON_WITH_MODIFIERS,
  24277. V_ON_WITH_KEYS: V_ON_WITH_KEYS,
  24278. V_SHOW: V_SHOW,
  24279. TRANSITION: TRANSITION,
  24280. TRANSITION_GROUP: TRANSITION_GROUP,
  24281. baseCompile: baseCompile,
  24282. baseParse: baseParse,
  24283. transform: transform,
  24284. createTransformContext: createTransformContext,
  24285. traverseNode: traverseNode,
  24286. createStructuralDirectiveTransform: createStructuralDirectiveTransform,
  24287. generate: generate,
  24288. createCompilerError: createCompilerError,
  24289. getBaseTransformPreset: getBaseTransformPreset,
  24290. transformModel: transformModel,
  24291. transformOn: transformOn,
  24292. transformBind: transformBind,
  24293. noopDirectiveTransform: noopDirectiveTransform,
  24294. processIf: processIf,
  24295. processFor: processFor,
  24296. createForLoopParams: createForLoopParams,
  24297. transformExpression: transformExpression,
  24298. processExpression: processExpression,
  24299. buildSlots: buildSlots,
  24300. trackVForSlotScopes: trackVForSlotScopes,
  24301. trackSlotScopes: trackSlotScopes,
  24302. transformElement: transformElement,
  24303. resolveComponentType: resolveComponentType,
  24304. buildProps: buildProps,
  24305. processSlotOutlet: processSlotOutlet,
  24306. generateCodeFrame: generateCodeFrame,
  24307. checkCompatEnabled: checkCompatEnabled,
  24308. warnDeprecation: warnDeprecation,
  24309. locStub: locStub,
  24310. createRoot: createRoot,
  24311. createVNodeCall: createVNodeCall,
  24312. createArrayExpression: createArrayExpression,
  24313. createObjectExpression: createObjectExpression,
  24314. createObjectProperty: createObjectProperty,
  24315. createSimpleExpression: createSimpleExpression,
  24316. createInterpolation: createInterpolation,
  24317. createCompoundExpression: createCompoundExpression,
  24318. createCallExpression: createCallExpression,
  24319. createFunctionExpression: createFunctionExpression,
  24320. createConditionalExpression: createConditionalExpression,
  24321. createCacheExpression: createCacheExpression,
  24322. createBlockStatement: createBlockStatement,
  24323. createTemplateLiteral: createTemplateLiteral,
  24324. createIfStatement: createIfStatement,
  24325. createAssignmentExpression: createAssignmentExpression,
  24326. createSequenceExpression: createSequenceExpression,
  24327. createReturnStatement: createReturnStatement,
  24328. isStaticExp: isStaticExp,
  24329. isBuiltInType: isBuiltInType,
  24330. isCoreComponent: isCoreComponent,
  24331. isSimpleIdentifier: isSimpleIdentifier,
  24332. isMemberExpressionBrowser: isMemberExpressionBrowser,
  24333. isMemberExpressionNode: isMemberExpressionNode,
  24334. isMemberExpression: isMemberExpression,
  24335. getInnerRange: getInnerRange,
  24336. advancePositionWithClone: advancePositionWithClone,
  24337. advancePositionWithMutation: advancePositionWithMutation,
  24338. assert: assert$1,
  24339. findDir: findDir,
  24340. findProp: findProp,
  24341. isStaticArgOf: isStaticArgOf,
  24342. hasDynamicKeyVBind: hasDynamicKeyVBind,
  24343. isText: isText,
  24344. isVSlot: isVSlot,
  24345. isTemplateNode: isTemplateNode,
  24346. isSlotOutlet: isSlotOutlet,
  24347. getVNodeHelper: getVNodeHelper,
  24348. getVNodeBlockHelper: getVNodeBlockHelper,
  24349. injectProp: injectProp,
  24350. toValidAssetId: toValidAssetId,
  24351. hasScopeRef: hasScopeRef,
  24352. getMemoedVNodeCall: getMemoedVNodeCall,
  24353. makeBlock: makeBlock,
  24354. walkIdentifiers: walkIdentifiers,
  24355. isReferencedIdentifier: isReferencedIdentifier,
  24356. isInDestructureAssignment: isInDestructureAssignment,
  24357. walkFunctionParams: walkFunctionParams,
  24358. walkBlockDeclarations: walkBlockDeclarations,
  24359. extractIdentifiers: extractIdentifiers,
  24360. isFunctionType: isFunctionType,
  24361. isStaticProperty: isStaticProperty,
  24362. isStaticPropertyKey: isStaticPropertyKey,
  24363. FRAGMENT: FRAGMENT,
  24364. TELEPORT: TELEPORT,
  24365. SUSPENSE: SUSPENSE,
  24366. KEEP_ALIVE: KEEP_ALIVE,
  24367. BASE_TRANSITION: BASE_TRANSITION,
  24368. OPEN_BLOCK: OPEN_BLOCK,
  24369. CREATE_BLOCK: CREATE_BLOCK,
  24370. CREATE_ELEMENT_BLOCK: CREATE_ELEMENT_BLOCK,
  24371. CREATE_VNODE: CREATE_VNODE,
  24372. CREATE_ELEMENT_VNODE: CREATE_ELEMENT_VNODE,
  24373. CREATE_COMMENT: CREATE_COMMENT,
  24374. CREATE_TEXT: CREATE_TEXT,
  24375. CREATE_STATIC: CREATE_STATIC,
  24376. RESOLVE_COMPONENT: RESOLVE_COMPONENT,
  24377. RESOLVE_DYNAMIC_COMPONENT: RESOLVE_DYNAMIC_COMPONENT,
  24378. RESOLVE_DIRECTIVE: RESOLVE_DIRECTIVE,
  24379. RESOLVE_FILTER: RESOLVE_FILTER,
  24380. WITH_DIRECTIVES: WITH_DIRECTIVES,
  24381. RENDER_LIST: RENDER_LIST,
  24382. RENDER_SLOT: RENDER_SLOT,
  24383. CREATE_SLOTS: CREATE_SLOTS,
  24384. TO_DISPLAY_STRING: TO_DISPLAY_STRING,
  24385. MERGE_PROPS: MERGE_PROPS,
  24386. NORMALIZE_CLASS: NORMALIZE_CLASS,
  24387. NORMALIZE_STYLE: NORMALIZE_STYLE,
  24388. NORMALIZE_PROPS: NORMALIZE_PROPS,
  24389. GUARD_REACTIVE_PROPS: GUARD_REACTIVE_PROPS,
  24390. TO_HANDLERS: TO_HANDLERS,
  24391. CAMELIZE: CAMELIZE,
  24392. CAPITALIZE: CAPITALIZE,
  24393. TO_HANDLER_KEY: TO_HANDLER_KEY,
  24394. SET_BLOCK_TRACKING: SET_BLOCK_TRACKING,
  24395. PUSH_SCOPE_ID: PUSH_SCOPE_ID,
  24396. POP_SCOPE_ID: POP_SCOPE_ID,
  24397. WITH_CTX: WITH_CTX,
  24398. UNREF: UNREF,
  24399. IS_REF: IS_REF,
  24400. WITH_MEMO: WITH_MEMO,
  24401. IS_MEMO_SAME: IS_MEMO_SAME,
  24402. helperNameMap: helperNameMap,
  24403. registerRuntimeHelpers: registerRuntimeHelpers
  24404. });
  24405. function pad (hash, len) {
  24406. while (hash.length < len) {
  24407. hash = '0' + hash;
  24408. }
  24409. return hash;
  24410. }
  24411. function fold (hash, text) {
  24412. var i;
  24413. var chr;
  24414. var len;
  24415. if (text.length === 0) {
  24416. return hash;
  24417. }
  24418. for (i = 0, len = text.length; i < len; i++) {
  24419. chr = text.charCodeAt(i);
  24420. hash = ((hash << 5) - hash) + chr;
  24421. hash |= 0;
  24422. }
  24423. return hash < 0 ? hash * -2 : hash;
  24424. }
  24425. function foldObject (hash, o, seen) {
  24426. return Object.keys(o).sort().reduce(foldKey, hash);
  24427. function foldKey (hash, key) {
  24428. return foldValue(hash, o[key], key, seen);
  24429. }
  24430. }
  24431. function foldValue (input, value, key, seen) {
  24432. var hash = fold(fold(fold(input, key), toString(value)), typeof value);
  24433. if (value === null) {
  24434. return fold(hash, 'null');
  24435. }
  24436. if (value === undefined) {
  24437. return fold(hash, 'undefined');
  24438. }
  24439. if (typeof value === 'object' || typeof value === 'function') {
  24440. if (seen.indexOf(value) !== -1) {
  24441. return fold(hash, '[Circular]' + key);
  24442. }
  24443. seen.push(value);
  24444. var objHash = foldObject(hash, value, seen);
  24445. if (!('valueOf' in value) || typeof value.valueOf !== 'function') {
  24446. return objHash;
  24447. }
  24448. try {
  24449. return fold(objHash, String(value.valueOf()))
  24450. } catch (err) {
  24451. return fold(objHash, '[valueOf exception]' + (err.stack || err.message))
  24452. }
  24453. }
  24454. return fold(hash, value.toString());
  24455. }
  24456. function toString (o) {
  24457. return Object.prototype.toString.call(o);
  24458. }
  24459. function sum (o) {
  24460. return pad(foldValue(0, o, '', []).toString(16), 8);
  24461. }
  24462. var hashSum = sum;
  24463. const CSS_VARS_HELPER = `useCssVars`;
  24464. const cssVarRE = /\bv-bind\(\s*(?:'([^']+)'|"([^"]+)"|([^'"][^)]*))\s*\)/g;
  24465. function genCssVarsFromList(vars, id, isProd) {
  24466. return `{\n ${vars
  24467. .map(key => `"${genVarName(id, key, isProd)}": (${key})`)
  24468. .join(',\n ')}\n}`;
  24469. }
  24470. function genVarName(id, raw, isProd) {
  24471. if (isProd) {
  24472. return hashSum(id + raw);
  24473. }
  24474. else {
  24475. return `${id}-${raw.replace(/([^\w-])/g, '_')}`;
  24476. }
  24477. }
  24478. function parseCssVars(sfc) {
  24479. const vars = [];
  24480. sfc.styles.forEach(style => {
  24481. let match;
  24482. // ignore v-bind() in comments /* ... */
  24483. const content = style.content.replace(/\/\*([\s\S]*?)\*\//g, '');
  24484. while ((match = cssVarRE.exec(content))) {
  24485. const variable = match[1] || match[2] || match[3];
  24486. if (!vars.includes(variable)) {
  24487. vars.push(variable);
  24488. }
  24489. }
  24490. });
  24491. return vars;
  24492. }
  24493. const cssVarsPlugin = opts => {
  24494. const { id, isProd } = opts;
  24495. return {
  24496. postcssPlugin: 'vue-sfc-vars',
  24497. Declaration(decl) {
  24498. // rewrite CSS variables
  24499. if (cssVarRE.test(decl.value)) {
  24500. decl.value = decl.value.replace(cssVarRE, (_, $1, $2, $3) => {
  24501. return `var(--${genVarName(id, $1 || $2 || $3, isProd)})`;
  24502. });
  24503. }
  24504. }
  24505. };
  24506. };
  24507. cssVarsPlugin.postcss = true;
  24508. function genCssVarsCode(vars, bindings, id, isProd) {
  24509. const varsExp = genCssVarsFromList(vars, id, isProd);
  24510. const exp = createSimpleExpression(varsExp, false);
  24511. const context = createTransformContext(createRoot([]), {
  24512. prefixIdentifiers: true,
  24513. inline: true,
  24514. bindingMetadata: bindings.__isScriptSetup === false ? undefined : bindings
  24515. });
  24516. const transformed = processExpression(exp, context);
  24517. const transformedString = transformed.type === 4 /* SIMPLE_EXPRESSION */
  24518. ? transformed.content
  24519. : transformed.children
  24520. .map(c => {
  24521. return typeof c === 'string'
  24522. ? c
  24523. : c.content;
  24524. })
  24525. .join('');
  24526. return `_${CSS_VARS_HELPER}(_ctx => (${transformedString}))`;
  24527. }
  24528. // <script setup> already gets the calls injected as part of the transform
  24529. // this is only for single normal <script>
  24530. function genNormalScriptCssVarsCode(cssVars, bindings, id, isProd) {
  24531. return (`\nimport { ${CSS_VARS_HELPER} as _${CSS_VARS_HELPER} } from 'vue'\n` +
  24532. `const __injectCSSVars__ = () => {\n${genCssVarsCode(cssVars, bindings, id, isProd)}}\n` +
  24533. `const __setup__ = __default__.setup\n` +
  24534. `__default__.setup = __setup__\n` +
  24535. ` ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) }\n` +
  24536. ` : __injectCSSVars__\n`);
  24537. }
  24538. function createCache(size = 500) {
  24539. return new Map()
  24540. ;
  24541. }
  24542. var global = (typeof global !== "undefined" ? global :
  24543. typeof self !== "undefined" ? self :
  24544. typeof window !== "undefined" ? window : {});
  24545. var lookup = [];
  24546. var revLookup = [];
  24547. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
  24548. var inited = false;
  24549. function init () {
  24550. inited = true;
  24551. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  24552. for (var i = 0, len = code.length; i < len; ++i) {
  24553. lookup[i] = code[i];
  24554. revLookup[code.charCodeAt(i)] = i;
  24555. }
  24556. revLookup['-'.charCodeAt(0)] = 62;
  24557. revLookup['_'.charCodeAt(0)] = 63;
  24558. }
  24559. function toByteArray (b64) {
  24560. if (!inited) {
  24561. init();
  24562. }
  24563. var i, j, l, tmp, placeHolders, arr;
  24564. var len = b64.length;
  24565. if (len % 4 > 0) {
  24566. throw new Error('Invalid string. Length must be a multiple of 4')
  24567. }
  24568. // the number of equal signs (place holders)
  24569. // if there are two placeholders, than the two characters before it
  24570. // represent one byte
  24571. // if there is only one, then the three characters before it represent 2 bytes
  24572. // this is just a cheap hack to not do indexOf twice
  24573. placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;
  24574. // base64 is 4/3 + up to two characters of the original data
  24575. arr = new Arr(len * 3 / 4 - placeHolders);
  24576. // if there are placeholders, only get up to the last complete 4 chars
  24577. l = placeHolders > 0 ? len - 4 : len;
  24578. var L = 0;
  24579. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  24580. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)];
  24581. arr[L++] = (tmp >> 16) & 0xFF;
  24582. arr[L++] = (tmp >> 8) & 0xFF;
  24583. arr[L++] = tmp & 0xFF;
  24584. }
  24585. if (placeHolders === 2) {
  24586. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);
  24587. arr[L++] = tmp & 0xFF;
  24588. } else if (placeHolders === 1) {
  24589. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2);
  24590. arr[L++] = (tmp >> 8) & 0xFF;
  24591. arr[L++] = tmp & 0xFF;
  24592. }
  24593. return arr
  24594. }
  24595. function tripletToBase64 (num) {
  24596. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  24597. }
  24598. function encodeChunk (uint8, start, end) {
  24599. var tmp;
  24600. var output = [];
  24601. for (var i = start; i < end; i += 3) {
  24602. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
  24603. output.push(tripletToBase64(tmp));
  24604. }
  24605. return output.join('')
  24606. }
  24607. function fromByteArray (uint8) {
  24608. if (!inited) {
  24609. init();
  24610. }
  24611. var tmp;
  24612. var len = uint8.length;
  24613. var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
  24614. var output = '';
  24615. var parts = [];
  24616. var maxChunkLength = 16383; // must be multiple of 3
  24617. // go through the array every three bytes, we'll deal with trailing stuff later
  24618. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  24619. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));
  24620. }
  24621. // pad the end with zeros, but make sure to not forget the extra bytes
  24622. if (extraBytes === 1) {
  24623. tmp = uint8[len - 1];
  24624. output += lookup[tmp >> 2];
  24625. output += lookup[(tmp << 4) & 0x3F];
  24626. output += '==';
  24627. } else if (extraBytes === 2) {
  24628. tmp = (uint8[len - 2] << 8) + (uint8[len - 1]);
  24629. output += lookup[tmp >> 10];
  24630. output += lookup[(tmp >> 4) & 0x3F];
  24631. output += lookup[(tmp << 2) & 0x3F];
  24632. output += '=';
  24633. }
  24634. parts.push(output);
  24635. return parts.join('')
  24636. }
  24637. function read (buffer, offset, isLE, mLen, nBytes) {
  24638. var e, m;
  24639. var eLen = nBytes * 8 - mLen - 1;
  24640. var eMax = (1 << eLen) - 1;
  24641. var eBias = eMax >> 1;
  24642. var nBits = -7;
  24643. var i = isLE ? (nBytes - 1) : 0;
  24644. var d = isLE ? -1 : 1;
  24645. var s = buffer[offset + i];
  24646. i += d;
  24647. e = s & ((1 << (-nBits)) - 1);
  24648. s >>= (-nBits);
  24649. nBits += eLen;
  24650. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  24651. m = e & ((1 << (-nBits)) - 1);
  24652. e >>= (-nBits);
  24653. nBits += mLen;
  24654. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  24655. if (e === 0) {
  24656. e = 1 - eBias;
  24657. } else if (e === eMax) {
  24658. return m ? NaN : ((s ? -1 : 1) * Infinity)
  24659. } else {
  24660. m = m + Math.pow(2, mLen);
  24661. e = e - eBias;
  24662. }
  24663. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  24664. }
  24665. function write (buffer, value, offset, isLE, mLen, nBytes) {
  24666. var e, m, c;
  24667. var eLen = nBytes * 8 - mLen - 1;
  24668. var eMax = (1 << eLen) - 1;
  24669. var eBias = eMax >> 1;
  24670. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);
  24671. var i = isLE ? 0 : (nBytes - 1);
  24672. var d = isLE ? 1 : -1;
  24673. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
  24674. value = Math.abs(value);
  24675. if (isNaN(value) || value === Infinity) {
  24676. m = isNaN(value) ? 1 : 0;
  24677. e = eMax;
  24678. } else {
  24679. e = Math.floor(Math.log(value) / Math.LN2);
  24680. if (value * (c = Math.pow(2, -e)) < 1) {
  24681. e--;
  24682. c *= 2;
  24683. }
  24684. if (e + eBias >= 1) {
  24685. value += rt / c;
  24686. } else {
  24687. value += rt * Math.pow(2, 1 - eBias);
  24688. }
  24689. if (value * c >= 2) {
  24690. e++;
  24691. c /= 2;
  24692. }
  24693. if (e + eBias >= eMax) {
  24694. m = 0;
  24695. e = eMax;
  24696. } else if (e + eBias >= 1) {
  24697. m = (value * c - 1) * Math.pow(2, mLen);
  24698. e = e + eBias;
  24699. } else {
  24700. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  24701. e = 0;
  24702. }
  24703. }
  24704. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  24705. e = (e << mLen) | m;
  24706. eLen += mLen;
  24707. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  24708. buffer[offset + i - d] |= s * 128;
  24709. }
  24710. var toString$1 = {}.toString;
  24711. var isArray$1 = Array.isArray || function (arr) {
  24712. return toString$1.call(arr) == '[object Array]';
  24713. };
  24714. /*!
  24715. * The buffer module from node.js, for the browser.
  24716. *
  24717. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  24718. * @license MIT
  24719. */
  24720. var INSPECT_MAX_BYTES = 50;
  24721. /**
  24722. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  24723. * === true Use Uint8Array implementation (fastest)
  24724. * === false Use Object implementation (most compatible, even IE6)
  24725. *
  24726. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  24727. * Opera 11.6+, iOS 4.2+.
  24728. *
  24729. * Due to various browser bugs, sometimes the Object implementation will be used even
  24730. * when the browser supports typed arrays.
  24731. *
  24732. * Note:
  24733. *
  24734. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  24735. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  24736. *
  24737. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  24738. *
  24739. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  24740. * incorrect length in some situations.
  24741. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  24742. * get the Object implementation, which is slower but behaves correctly.
  24743. */
  24744. Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  24745. ? global.TYPED_ARRAY_SUPPORT
  24746. : true;
  24747. function kMaxLength () {
  24748. return Buffer.TYPED_ARRAY_SUPPORT
  24749. ? 0x7fffffff
  24750. : 0x3fffffff
  24751. }
  24752. function createBuffer (that, length) {
  24753. if (kMaxLength() < length) {
  24754. throw new RangeError('Invalid typed array length')
  24755. }
  24756. if (Buffer.TYPED_ARRAY_SUPPORT) {
  24757. // Return an augmented `Uint8Array` instance, for best performance
  24758. that = new Uint8Array(length);
  24759. that.__proto__ = Buffer.prototype;
  24760. } else {
  24761. // Fallback: Return an object instance of the Buffer class
  24762. if (that === null) {
  24763. that = new Buffer(length);
  24764. }
  24765. that.length = length;
  24766. }
  24767. return that
  24768. }
  24769. /**
  24770. * The Buffer constructor returns instances of `Uint8Array` that have their
  24771. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  24772. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  24773. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  24774. * returns a single octet.
  24775. *
  24776. * The `Uint8Array` prototype remains unmodified.
  24777. */
  24778. function Buffer (arg, encodingOrOffset, length) {
  24779. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  24780. return new Buffer(arg, encodingOrOffset, length)
  24781. }
  24782. // Common case.
  24783. if (typeof arg === 'number') {
  24784. if (typeof encodingOrOffset === 'string') {
  24785. throw new Error(
  24786. 'If encoding is specified then the first argument must be a string'
  24787. )
  24788. }
  24789. return allocUnsafe(this, arg)
  24790. }
  24791. return from(this, arg, encodingOrOffset, length)
  24792. }
  24793. Buffer.poolSize = 8192; // not used by this implementation
  24794. // TODO: Legacy, not needed anymore. Remove in next major version.
  24795. Buffer._augment = function (arr) {
  24796. arr.__proto__ = Buffer.prototype;
  24797. return arr
  24798. };
  24799. function from (that, value, encodingOrOffset, length) {
  24800. if (typeof value === 'number') {
  24801. throw new TypeError('"value" argument must not be a number')
  24802. }
  24803. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  24804. return fromArrayBuffer(that, value, encodingOrOffset, length)
  24805. }
  24806. if (typeof value === 'string') {
  24807. return fromString(that, value, encodingOrOffset)
  24808. }
  24809. return fromObject(that, value)
  24810. }
  24811. /**
  24812. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  24813. * if value is a number.
  24814. * Buffer.from(str[, encoding])
  24815. * Buffer.from(array)
  24816. * Buffer.from(buffer)
  24817. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  24818. **/
  24819. Buffer.from = function (value, encodingOrOffset, length) {
  24820. return from(null, value, encodingOrOffset, length)
  24821. };
  24822. if (Buffer.TYPED_ARRAY_SUPPORT) {
  24823. Buffer.prototype.__proto__ = Uint8Array.prototype;
  24824. Buffer.__proto__ = Uint8Array;
  24825. }
  24826. function assertSize (size) {
  24827. if (typeof size !== 'number') {
  24828. throw new TypeError('"size" argument must be a number')
  24829. } else if (size < 0) {
  24830. throw new RangeError('"size" argument must not be negative')
  24831. }
  24832. }
  24833. function alloc (that, size, fill, encoding) {
  24834. assertSize(size);
  24835. if (size <= 0) {
  24836. return createBuffer(that, size)
  24837. }
  24838. if (fill !== undefined) {
  24839. // Only pay attention to encoding if it's a string. This
  24840. // prevents accidentally sending in a number that would
  24841. // be interpretted as a start offset.
  24842. return typeof encoding === 'string'
  24843. ? createBuffer(that, size).fill(fill, encoding)
  24844. : createBuffer(that, size).fill(fill)
  24845. }
  24846. return createBuffer(that, size)
  24847. }
  24848. /**
  24849. * Creates a new filled Buffer instance.
  24850. * alloc(size[, fill[, encoding]])
  24851. **/
  24852. Buffer.alloc = function (size, fill, encoding) {
  24853. return alloc(null, size, fill, encoding)
  24854. };
  24855. function allocUnsafe (that, size) {
  24856. assertSize(size);
  24857. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
  24858. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  24859. for (var i = 0; i < size; ++i) {
  24860. that[i] = 0;
  24861. }
  24862. }
  24863. return that
  24864. }
  24865. /**
  24866. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  24867. * */
  24868. Buffer.allocUnsafe = function (size) {
  24869. return allocUnsafe(null, size)
  24870. };
  24871. /**
  24872. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  24873. */
  24874. Buffer.allocUnsafeSlow = function (size) {
  24875. return allocUnsafe(null, size)
  24876. };
  24877. function fromString (that, string, encoding) {
  24878. if (typeof encoding !== 'string' || encoding === '') {
  24879. encoding = 'utf8';
  24880. }
  24881. if (!Buffer.isEncoding(encoding)) {
  24882. throw new TypeError('"encoding" must be a valid string encoding')
  24883. }
  24884. var length = byteLength(string, encoding) | 0;
  24885. that = createBuffer(that, length);
  24886. var actual = that.write(string, encoding);
  24887. if (actual !== length) {
  24888. // Writing a hex string, for example, that contains invalid characters will
  24889. // cause everything after the first invalid character to be ignored. (e.g.
  24890. // 'abxxcd' will be treated as 'ab')
  24891. that = that.slice(0, actual);
  24892. }
  24893. return that
  24894. }
  24895. function fromArrayLike (that, array) {
  24896. var length = array.length < 0 ? 0 : checked(array.length) | 0;
  24897. that = createBuffer(that, length);
  24898. for (var i = 0; i < length; i += 1) {
  24899. that[i] = array[i] & 255;
  24900. }
  24901. return that
  24902. }
  24903. function fromArrayBuffer (that, array, byteOffset, length) {
  24904. array.byteLength; // this throws if `array` is not a valid ArrayBuffer
  24905. if (byteOffset < 0 || array.byteLength < byteOffset) {
  24906. throw new RangeError('\'offset\' is out of bounds')
  24907. }
  24908. if (array.byteLength < byteOffset + (length || 0)) {
  24909. throw new RangeError('\'length\' is out of bounds')
  24910. }
  24911. if (byteOffset === undefined && length === undefined) {
  24912. array = new Uint8Array(array);
  24913. } else if (length === undefined) {
  24914. array = new Uint8Array(array, byteOffset);
  24915. } else {
  24916. array = new Uint8Array(array, byteOffset, length);
  24917. }
  24918. if (Buffer.TYPED_ARRAY_SUPPORT) {
  24919. // Return an augmented `Uint8Array` instance, for best performance
  24920. that = array;
  24921. that.__proto__ = Buffer.prototype;
  24922. } else {
  24923. // Fallback: Return an object instance of the Buffer class
  24924. that = fromArrayLike(that, array);
  24925. }
  24926. return that
  24927. }
  24928. function fromObject (that, obj) {
  24929. if (internalIsBuffer(obj)) {
  24930. var len = checked(obj.length) | 0;
  24931. that = createBuffer(that, len);
  24932. if (that.length === 0) {
  24933. return that
  24934. }
  24935. obj.copy(that, 0, 0, len);
  24936. return that
  24937. }
  24938. if (obj) {
  24939. if ((typeof ArrayBuffer !== 'undefined' &&
  24940. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  24941. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  24942. return createBuffer(that, 0)
  24943. }
  24944. return fromArrayLike(that, obj)
  24945. }
  24946. if (obj.type === 'Buffer' && isArray$1(obj.data)) {
  24947. return fromArrayLike(that, obj.data)
  24948. }
  24949. }
  24950. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  24951. }
  24952. function checked (length) {
  24953. // Note: cannot use `length < kMaxLength()` here because that fails when
  24954. // length is NaN (which is otherwise coerced to zero.)
  24955. if (length >= kMaxLength()) {
  24956. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  24957. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  24958. }
  24959. return length | 0
  24960. }
  24961. Buffer.isBuffer = isBuffer;
  24962. function internalIsBuffer (b) {
  24963. return !!(b != null && b._isBuffer)
  24964. }
  24965. Buffer.compare = function compare (a, b) {
  24966. if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
  24967. throw new TypeError('Arguments must be Buffers')
  24968. }
  24969. if (a === b) return 0
  24970. var x = a.length;
  24971. var y = b.length;
  24972. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  24973. if (a[i] !== b[i]) {
  24974. x = a[i];
  24975. y = b[i];
  24976. break
  24977. }
  24978. }
  24979. if (x < y) return -1
  24980. if (y < x) return 1
  24981. return 0
  24982. };
  24983. Buffer.isEncoding = function isEncoding (encoding) {
  24984. switch (String(encoding).toLowerCase()) {
  24985. case 'hex':
  24986. case 'utf8':
  24987. case 'utf-8':
  24988. case 'ascii':
  24989. case 'latin1':
  24990. case 'binary':
  24991. case 'base64':
  24992. case 'ucs2':
  24993. case 'ucs-2':
  24994. case 'utf16le':
  24995. case 'utf-16le':
  24996. return true
  24997. default:
  24998. return false
  24999. }
  25000. };
  25001. Buffer.concat = function concat (list, length) {
  25002. if (!isArray$1(list)) {
  25003. throw new TypeError('"list" argument must be an Array of Buffers')
  25004. }
  25005. if (list.length === 0) {
  25006. return Buffer.alloc(0)
  25007. }
  25008. var i;
  25009. if (length === undefined) {
  25010. length = 0;
  25011. for (i = 0; i < list.length; ++i) {
  25012. length += list[i].length;
  25013. }
  25014. }
  25015. var buffer = Buffer.allocUnsafe(length);
  25016. var pos = 0;
  25017. for (i = 0; i < list.length; ++i) {
  25018. var buf = list[i];
  25019. if (!internalIsBuffer(buf)) {
  25020. throw new TypeError('"list" argument must be an Array of Buffers')
  25021. }
  25022. buf.copy(buffer, pos);
  25023. pos += buf.length;
  25024. }
  25025. return buffer
  25026. };
  25027. function byteLength (string, encoding) {
  25028. if (internalIsBuffer(string)) {
  25029. return string.length
  25030. }
  25031. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  25032. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  25033. return string.byteLength
  25034. }
  25035. if (typeof string !== 'string') {
  25036. string = '' + string;
  25037. }
  25038. var len = string.length;
  25039. if (len === 0) return 0
  25040. // Use a for loop to avoid recursion
  25041. var loweredCase = false;
  25042. for (;;) {
  25043. switch (encoding) {
  25044. case 'ascii':
  25045. case 'latin1':
  25046. case 'binary':
  25047. return len
  25048. case 'utf8':
  25049. case 'utf-8':
  25050. case undefined:
  25051. return utf8ToBytes(string).length
  25052. case 'ucs2':
  25053. case 'ucs-2':
  25054. case 'utf16le':
  25055. case 'utf-16le':
  25056. return len * 2
  25057. case 'hex':
  25058. return len >>> 1
  25059. case 'base64':
  25060. return base64ToBytes(string).length
  25061. default:
  25062. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  25063. encoding = ('' + encoding).toLowerCase();
  25064. loweredCase = true;
  25065. }
  25066. }
  25067. }
  25068. Buffer.byteLength = byteLength;
  25069. function slowToString (encoding, start, end) {
  25070. var loweredCase = false;
  25071. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  25072. // property of a typed array.
  25073. // This behaves neither like String nor Uint8Array in that we set start/end
  25074. // to their upper/lower bounds if the value passed is out of range.
  25075. // undefined is handled specially as per ECMA-262 6th Edition,
  25076. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  25077. if (start === undefined || start < 0) {
  25078. start = 0;
  25079. }
  25080. // Return early if start > this.length. Done here to prevent potential uint32
  25081. // coercion fail below.
  25082. if (start > this.length) {
  25083. return ''
  25084. }
  25085. if (end === undefined || end > this.length) {
  25086. end = this.length;
  25087. }
  25088. if (end <= 0) {
  25089. return ''
  25090. }
  25091. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  25092. end >>>= 0;
  25093. start >>>= 0;
  25094. if (end <= start) {
  25095. return ''
  25096. }
  25097. if (!encoding) encoding = 'utf8';
  25098. while (true) {
  25099. switch (encoding) {
  25100. case 'hex':
  25101. return hexSlice(this, start, end)
  25102. case 'utf8':
  25103. case 'utf-8':
  25104. return utf8Slice(this, start, end)
  25105. case 'ascii':
  25106. return asciiSlice(this, start, end)
  25107. case 'latin1':
  25108. case 'binary':
  25109. return latin1Slice(this, start, end)
  25110. case 'base64':
  25111. return base64Slice(this, start, end)
  25112. case 'ucs2':
  25113. case 'ucs-2':
  25114. case 'utf16le':
  25115. case 'utf-16le':
  25116. return utf16leSlice(this, start, end)
  25117. default:
  25118. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  25119. encoding = (encoding + '').toLowerCase();
  25120. loweredCase = true;
  25121. }
  25122. }
  25123. }
  25124. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  25125. // Buffer instances.
  25126. Buffer.prototype._isBuffer = true;
  25127. function swap$1 (b, n, m) {
  25128. var i = b[n];
  25129. b[n] = b[m];
  25130. b[m] = i;
  25131. }
  25132. Buffer.prototype.swap16 = function swap16 () {
  25133. var len = this.length;
  25134. if (len % 2 !== 0) {
  25135. throw new RangeError('Buffer size must be a multiple of 16-bits')
  25136. }
  25137. for (var i = 0; i < len; i += 2) {
  25138. swap$1(this, i, i + 1);
  25139. }
  25140. return this
  25141. };
  25142. Buffer.prototype.swap32 = function swap32 () {
  25143. var len = this.length;
  25144. if (len % 4 !== 0) {
  25145. throw new RangeError('Buffer size must be a multiple of 32-bits')
  25146. }
  25147. for (var i = 0; i < len; i += 4) {
  25148. swap$1(this, i, i + 3);
  25149. swap$1(this, i + 1, i + 2);
  25150. }
  25151. return this
  25152. };
  25153. Buffer.prototype.swap64 = function swap64 () {
  25154. var len = this.length;
  25155. if (len % 8 !== 0) {
  25156. throw new RangeError('Buffer size must be a multiple of 64-bits')
  25157. }
  25158. for (var i = 0; i < len; i += 8) {
  25159. swap$1(this, i, i + 7);
  25160. swap$1(this, i + 1, i + 6);
  25161. swap$1(this, i + 2, i + 5);
  25162. swap$1(this, i + 3, i + 4);
  25163. }
  25164. return this
  25165. };
  25166. Buffer.prototype.toString = function toString () {
  25167. var length = this.length | 0;
  25168. if (length === 0) return ''
  25169. if (arguments.length === 0) return utf8Slice(this, 0, length)
  25170. return slowToString.apply(this, arguments)
  25171. };
  25172. Buffer.prototype.equals = function equals (b) {
  25173. if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')
  25174. if (this === b) return true
  25175. return Buffer.compare(this, b) === 0
  25176. };
  25177. Buffer.prototype.inspect = function inspect () {
  25178. var str = '';
  25179. var max = INSPECT_MAX_BYTES;
  25180. if (this.length > 0) {
  25181. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
  25182. if (this.length > max) str += ' ... ';
  25183. }
  25184. return '<Buffer ' + str + '>'
  25185. };
  25186. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  25187. if (!internalIsBuffer(target)) {
  25188. throw new TypeError('Argument must be a Buffer')
  25189. }
  25190. if (start === undefined) {
  25191. start = 0;
  25192. }
  25193. if (end === undefined) {
  25194. end = target ? target.length : 0;
  25195. }
  25196. if (thisStart === undefined) {
  25197. thisStart = 0;
  25198. }
  25199. if (thisEnd === undefined) {
  25200. thisEnd = this.length;
  25201. }
  25202. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  25203. throw new RangeError('out of range index')
  25204. }
  25205. if (thisStart >= thisEnd && start >= end) {
  25206. return 0
  25207. }
  25208. if (thisStart >= thisEnd) {
  25209. return -1
  25210. }
  25211. if (start >= end) {
  25212. return 1
  25213. }
  25214. start >>>= 0;
  25215. end >>>= 0;
  25216. thisStart >>>= 0;
  25217. thisEnd >>>= 0;
  25218. if (this === target) return 0
  25219. var x = thisEnd - thisStart;
  25220. var y = end - start;
  25221. var len = Math.min(x, y);
  25222. var thisCopy = this.slice(thisStart, thisEnd);
  25223. var targetCopy = target.slice(start, end);
  25224. for (var i = 0; i < len; ++i) {
  25225. if (thisCopy[i] !== targetCopy[i]) {
  25226. x = thisCopy[i];
  25227. y = targetCopy[i];
  25228. break
  25229. }
  25230. }
  25231. if (x < y) return -1
  25232. if (y < x) return 1
  25233. return 0
  25234. };
  25235. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  25236. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  25237. //
  25238. // Arguments:
  25239. // - buffer - a Buffer to search
  25240. // - val - a string, Buffer, or number
  25241. // - byteOffset - an index into `buffer`; will be clamped to an int32
  25242. // - encoding - an optional encoding, relevant is val is a string
  25243. // - dir - true for indexOf, false for lastIndexOf
  25244. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  25245. // Empty buffer means no match
  25246. if (buffer.length === 0) return -1
  25247. // Normalize byteOffset
  25248. if (typeof byteOffset === 'string') {
  25249. encoding = byteOffset;
  25250. byteOffset = 0;
  25251. } else if (byteOffset > 0x7fffffff) {
  25252. byteOffset = 0x7fffffff;
  25253. } else if (byteOffset < -0x80000000) {
  25254. byteOffset = -0x80000000;
  25255. }
  25256. byteOffset = +byteOffset; // Coerce to Number.
  25257. if (isNaN(byteOffset)) {
  25258. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  25259. byteOffset = dir ? 0 : (buffer.length - 1);
  25260. }
  25261. // Normalize byteOffset: negative offsets start from the end of the buffer
  25262. if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
  25263. if (byteOffset >= buffer.length) {
  25264. if (dir) return -1
  25265. else byteOffset = buffer.length - 1;
  25266. } else if (byteOffset < 0) {
  25267. if (dir) byteOffset = 0;
  25268. else return -1
  25269. }
  25270. // Normalize val
  25271. if (typeof val === 'string') {
  25272. val = Buffer.from(val, encoding);
  25273. }
  25274. // Finally, search either indexOf (if dir is true) or lastIndexOf
  25275. if (internalIsBuffer(val)) {
  25276. // Special case: looking for empty string/buffer always fails
  25277. if (val.length === 0) {
  25278. return -1
  25279. }
  25280. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  25281. } else if (typeof val === 'number') {
  25282. val = val & 0xFF; // Search for a byte value [0-255]
  25283. if (Buffer.TYPED_ARRAY_SUPPORT &&
  25284. typeof Uint8Array.prototype.indexOf === 'function') {
  25285. if (dir) {
  25286. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  25287. } else {
  25288. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  25289. }
  25290. }
  25291. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  25292. }
  25293. throw new TypeError('val must be string, number or Buffer')
  25294. }
  25295. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  25296. var indexSize = 1;
  25297. var arrLength = arr.length;
  25298. var valLength = val.length;
  25299. if (encoding !== undefined) {
  25300. encoding = String(encoding).toLowerCase();
  25301. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  25302. encoding === 'utf16le' || encoding === 'utf-16le') {
  25303. if (arr.length < 2 || val.length < 2) {
  25304. return -1
  25305. }
  25306. indexSize = 2;
  25307. arrLength /= 2;
  25308. valLength /= 2;
  25309. byteOffset /= 2;
  25310. }
  25311. }
  25312. function read (buf, i) {
  25313. if (indexSize === 1) {
  25314. return buf[i]
  25315. } else {
  25316. return buf.readUInt16BE(i * indexSize)
  25317. }
  25318. }
  25319. var i;
  25320. if (dir) {
  25321. var foundIndex = -1;
  25322. for (i = byteOffset; i < arrLength; i++) {
  25323. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  25324. if (foundIndex === -1) foundIndex = i;
  25325. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  25326. } else {
  25327. if (foundIndex !== -1) i -= i - foundIndex;
  25328. foundIndex = -1;
  25329. }
  25330. }
  25331. } else {
  25332. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
  25333. for (i = byteOffset; i >= 0; i--) {
  25334. var found = true;
  25335. for (var j = 0; j < valLength; j++) {
  25336. if (read(arr, i + j) !== read(val, j)) {
  25337. found = false;
  25338. break
  25339. }
  25340. }
  25341. if (found) return i
  25342. }
  25343. }
  25344. return -1
  25345. }
  25346. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  25347. return this.indexOf(val, byteOffset, encoding) !== -1
  25348. };
  25349. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  25350. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  25351. };
  25352. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  25353. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  25354. };
  25355. function hexWrite (buf, string, offset, length) {
  25356. offset = Number(offset) || 0;
  25357. var remaining = buf.length - offset;
  25358. if (!length) {
  25359. length = remaining;
  25360. } else {
  25361. length = Number(length);
  25362. if (length > remaining) {
  25363. length = remaining;
  25364. }
  25365. }
  25366. // must be an even number of digits
  25367. var strLen = string.length;
  25368. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  25369. if (length > strLen / 2) {
  25370. length = strLen / 2;
  25371. }
  25372. for (var i = 0; i < length; ++i) {
  25373. var parsed = parseInt(string.substr(i * 2, 2), 16);
  25374. if (isNaN(parsed)) return i
  25375. buf[offset + i] = parsed;
  25376. }
  25377. return i
  25378. }
  25379. function utf8Write (buf, string, offset, length) {
  25380. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  25381. }
  25382. function asciiWrite (buf, string, offset, length) {
  25383. return blitBuffer(asciiToBytes(string), buf, offset, length)
  25384. }
  25385. function latin1Write (buf, string, offset, length) {
  25386. return asciiWrite(buf, string, offset, length)
  25387. }
  25388. function base64Write (buf, string, offset, length) {
  25389. return blitBuffer(base64ToBytes(string), buf, offset, length)
  25390. }
  25391. function ucs2Write (buf, string, offset, length) {
  25392. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  25393. }
  25394. Buffer.prototype.write = function write (string, offset, length, encoding) {
  25395. // Buffer#write(string)
  25396. if (offset === undefined) {
  25397. encoding = 'utf8';
  25398. length = this.length;
  25399. offset = 0;
  25400. // Buffer#write(string, encoding)
  25401. } else if (length === undefined && typeof offset === 'string') {
  25402. encoding = offset;
  25403. length = this.length;
  25404. offset = 0;
  25405. // Buffer#write(string, offset[, length][, encoding])
  25406. } else if (isFinite(offset)) {
  25407. offset = offset | 0;
  25408. if (isFinite(length)) {
  25409. length = length | 0;
  25410. if (encoding === undefined) encoding = 'utf8';
  25411. } else {
  25412. encoding = length;
  25413. length = undefined;
  25414. }
  25415. // legacy write(string, encoding, offset, length) - remove in v0.13
  25416. } else {
  25417. throw new Error(
  25418. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  25419. )
  25420. }
  25421. var remaining = this.length - offset;
  25422. if (length === undefined || length > remaining) length = remaining;
  25423. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  25424. throw new RangeError('Attempt to write outside buffer bounds')
  25425. }
  25426. if (!encoding) encoding = 'utf8';
  25427. var loweredCase = false;
  25428. for (;;) {
  25429. switch (encoding) {
  25430. case 'hex':
  25431. return hexWrite(this, string, offset, length)
  25432. case 'utf8':
  25433. case 'utf-8':
  25434. return utf8Write(this, string, offset, length)
  25435. case 'ascii':
  25436. return asciiWrite(this, string, offset, length)
  25437. case 'latin1':
  25438. case 'binary':
  25439. return latin1Write(this, string, offset, length)
  25440. case 'base64':
  25441. // Warning: maxLength not taken into account in base64Write
  25442. return base64Write(this, string, offset, length)
  25443. case 'ucs2':
  25444. case 'ucs-2':
  25445. case 'utf16le':
  25446. case 'utf-16le':
  25447. return ucs2Write(this, string, offset, length)
  25448. default:
  25449. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  25450. encoding = ('' + encoding).toLowerCase();
  25451. loweredCase = true;
  25452. }
  25453. }
  25454. };
  25455. Buffer.prototype.toJSON = function toJSON () {
  25456. return {
  25457. type: 'Buffer',
  25458. data: Array.prototype.slice.call(this._arr || this, 0)
  25459. }
  25460. };
  25461. function base64Slice (buf, start, end) {
  25462. if (start === 0 && end === buf.length) {
  25463. return fromByteArray(buf)
  25464. } else {
  25465. return fromByteArray(buf.slice(start, end))
  25466. }
  25467. }
  25468. function utf8Slice (buf, start, end) {
  25469. end = Math.min(buf.length, end);
  25470. var res = [];
  25471. var i = start;
  25472. while (i < end) {
  25473. var firstByte = buf[i];
  25474. var codePoint = null;
  25475. var bytesPerSequence = (firstByte > 0xEF) ? 4
  25476. : (firstByte > 0xDF) ? 3
  25477. : (firstByte > 0xBF) ? 2
  25478. : 1;
  25479. if (i + bytesPerSequence <= end) {
  25480. var secondByte, thirdByte, fourthByte, tempCodePoint;
  25481. switch (bytesPerSequence) {
  25482. case 1:
  25483. if (firstByte < 0x80) {
  25484. codePoint = firstByte;
  25485. }
  25486. break
  25487. case 2:
  25488. secondByte = buf[i + 1];
  25489. if ((secondByte & 0xC0) === 0x80) {
  25490. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
  25491. if (tempCodePoint > 0x7F) {
  25492. codePoint = tempCodePoint;
  25493. }
  25494. }
  25495. break
  25496. case 3:
  25497. secondByte = buf[i + 1];
  25498. thirdByte = buf[i + 2];
  25499. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  25500. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
  25501. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  25502. codePoint = tempCodePoint;
  25503. }
  25504. }
  25505. break
  25506. case 4:
  25507. secondByte = buf[i + 1];
  25508. thirdByte = buf[i + 2];
  25509. fourthByte = buf[i + 3];
  25510. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  25511. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
  25512. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  25513. codePoint = tempCodePoint;
  25514. }
  25515. }
  25516. }
  25517. }
  25518. if (codePoint === null) {
  25519. // we did not generate a valid codePoint so insert a
  25520. // replacement char (U+FFFD) and advance only 1 byte
  25521. codePoint = 0xFFFD;
  25522. bytesPerSequence = 1;
  25523. } else if (codePoint > 0xFFFF) {
  25524. // encode to utf16 (surrogate pair dance)
  25525. codePoint -= 0x10000;
  25526. res.push(codePoint >>> 10 & 0x3FF | 0xD800);
  25527. codePoint = 0xDC00 | codePoint & 0x3FF;
  25528. }
  25529. res.push(codePoint);
  25530. i += bytesPerSequence;
  25531. }
  25532. return decodeCodePointsArray(res)
  25533. }
  25534. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  25535. // the lowest limit is Chrome, with 0x10000 args.
  25536. // We go 1 magnitude less, for safety
  25537. var MAX_ARGUMENTS_LENGTH = 0x1000;
  25538. function decodeCodePointsArray (codePoints) {
  25539. var len = codePoints.length;
  25540. if (len <= MAX_ARGUMENTS_LENGTH) {
  25541. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  25542. }
  25543. // Decode in chunks to avoid "call stack size exceeded".
  25544. var res = '';
  25545. var i = 0;
  25546. while (i < len) {
  25547. res += String.fromCharCode.apply(
  25548. String,
  25549. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  25550. );
  25551. }
  25552. return res
  25553. }
  25554. function asciiSlice (buf, start, end) {
  25555. var ret = '';
  25556. end = Math.min(buf.length, end);
  25557. for (var i = start; i < end; ++i) {
  25558. ret += String.fromCharCode(buf[i] & 0x7F);
  25559. }
  25560. return ret
  25561. }
  25562. function latin1Slice (buf, start, end) {
  25563. var ret = '';
  25564. end = Math.min(buf.length, end);
  25565. for (var i = start; i < end; ++i) {
  25566. ret += String.fromCharCode(buf[i]);
  25567. }
  25568. return ret
  25569. }
  25570. function hexSlice (buf, start, end) {
  25571. var len = buf.length;
  25572. if (!start || start < 0) start = 0;
  25573. if (!end || end < 0 || end > len) end = len;
  25574. var out = '';
  25575. for (var i = start; i < end; ++i) {
  25576. out += toHex(buf[i]);
  25577. }
  25578. return out
  25579. }
  25580. function utf16leSlice (buf, start, end) {
  25581. var bytes = buf.slice(start, end);
  25582. var res = '';
  25583. for (var i = 0; i < bytes.length; i += 2) {
  25584. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
  25585. }
  25586. return res
  25587. }
  25588. Buffer.prototype.slice = function slice (start, end) {
  25589. var len = this.length;
  25590. start = ~~start;
  25591. end = end === undefined ? len : ~~end;
  25592. if (start < 0) {
  25593. start += len;
  25594. if (start < 0) start = 0;
  25595. } else if (start > len) {
  25596. start = len;
  25597. }
  25598. if (end < 0) {
  25599. end += len;
  25600. if (end < 0) end = 0;
  25601. } else if (end > len) {
  25602. end = len;
  25603. }
  25604. if (end < start) end = start;
  25605. var newBuf;
  25606. if (Buffer.TYPED_ARRAY_SUPPORT) {
  25607. newBuf = this.subarray(start, end);
  25608. newBuf.__proto__ = Buffer.prototype;
  25609. } else {
  25610. var sliceLen = end - start;
  25611. newBuf = new Buffer(sliceLen, undefined);
  25612. for (var i = 0; i < sliceLen; ++i) {
  25613. newBuf[i] = this[i + start];
  25614. }
  25615. }
  25616. return newBuf
  25617. };
  25618. /*
  25619. * Need to make sure that buffer isn't trying to write out of bounds.
  25620. */
  25621. function checkOffset (offset, ext, length) {
  25622. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  25623. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  25624. }
  25625. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  25626. offset = offset | 0;
  25627. byteLength = byteLength | 0;
  25628. if (!noAssert) checkOffset(offset, byteLength, this.length);
  25629. var val = this[offset];
  25630. var mul = 1;
  25631. var i = 0;
  25632. while (++i < byteLength && (mul *= 0x100)) {
  25633. val += this[offset + i] * mul;
  25634. }
  25635. return val
  25636. };
  25637. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  25638. offset = offset | 0;
  25639. byteLength = byteLength | 0;
  25640. if (!noAssert) {
  25641. checkOffset(offset, byteLength, this.length);
  25642. }
  25643. var val = this[offset + --byteLength];
  25644. var mul = 1;
  25645. while (byteLength > 0 && (mul *= 0x100)) {
  25646. val += this[offset + --byteLength] * mul;
  25647. }
  25648. return val
  25649. };
  25650. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  25651. if (!noAssert) checkOffset(offset, 1, this.length);
  25652. return this[offset]
  25653. };
  25654. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  25655. if (!noAssert) checkOffset(offset, 2, this.length);
  25656. return this[offset] | (this[offset + 1] << 8)
  25657. };
  25658. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  25659. if (!noAssert) checkOffset(offset, 2, this.length);
  25660. return (this[offset] << 8) | this[offset + 1]
  25661. };
  25662. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  25663. if (!noAssert) checkOffset(offset, 4, this.length);
  25664. return ((this[offset]) |
  25665. (this[offset + 1] << 8) |
  25666. (this[offset + 2] << 16)) +
  25667. (this[offset + 3] * 0x1000000)
  25668. };
  25669. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  25670. if (!noAssert) checkOffset(offset, 4, this.length);
  25671. return (this[offset] * 0x1000000) +
  25672. ((this[offset + 1] << 16) |
  25673. (this[offset + 2] << 8) |
  25674. this[offset + 3])
  25675. };
  25676. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  25677. offset = offset | 0;
  25678. byteLength = byteLength | 0;
  25679. if (!noAssert) checkOffset(offset, byteLength, this.length);
  25680. var val = this[offset];
  25681. var mul = 1;
  25682. var i = 0;
  25683. while (++i < byteLength && (mul *= 0x100)) {
  25684. val += this[offset + i] * mul;
  25685. }
  25686. mul *= 0x80;
  25687. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  25688. return val
  25689. };
  25690. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  25691. offset = offset | 0;
  25692. byteLength = byteLength | 0;
  25693. if (!noAssert) checkOffset(offset, byteLength, this.length);
  25694. var i = byteLength;
  25695. var mul = 1;
  25696. var val = this[offset + --i];
  25697. while (i > 0 && (mul *= 0x100)) {
  25698. val += this[offset + --i] * mul;
  25699. }
  25700. mul *= 0x80;
  25701. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  25702. return val
  25703. };
  25704. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  25705. if (!noAssert) checkOffset(offset, 1, this.length);
  25706. if (!(this[offset] & 0x80)) return (this[offset])
  25707. return ((0xff - this[offset] + 1) * -1)
  25708. };
  25709. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  25710. if (!noAssert) checkOffset(offset, 2, this.length);
  25711. var val = this[offset] | (this[offset + 1] << 8);
  25712. return (val & 0x8000) ? val | 0xFFFF0000 : val
  25713. };
  25714. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  25715. if (!noAssert) checkOffset(offset, 2, this.length);
  25716. var val = this[offset + 1] | (this[offset] << 8);
  25717. return (val & 0x8000) ? val | 0xFFFF0000 : val
  25718. };
  25719. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  25720. if (!noAssert) checkOffset(offset, 4, this.length);
  25721. return (this[offset]) |
  25722. (this[offset + 1] << 8) |
  25723. (this[offset + 2] << 16) |
  25724. (this[offset + 3] << 24)
  25725. };
  25726. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  25727. if (!noAssert) checkOffset(offset, 4, this.length);
  25728. return (this[offset] << 24) |
  25729. (this[offset + 1] << 16) |
  25730. (this[offset + 2] << 8) |
  25731. (this[offset + 3])
  25732. };
  25733. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  25734. if (!noAssert) checkOffset(offset, 4, this.length);
  25735. return read(this, offset, true, 23, 4)
  25736. };
  25737. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  25738. if (!noAssert) checkOffset(offset, 4, this.length);
  25739. return read(this, offset, false, 23, 4)
  25740. };
  25741. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  25742. if (!noAssert) checkOffset(offset, 8, this.length);
  25743. return read(this, offset, true, 52, 8)
  25744. };
  25745. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  25746. if (!noAssert) checkOffset(offset, 8, this.length);
  25747. return read(this, offset, false, 52, 8)
  25748. };
  25749. function checkInt (buf, value, offset, ext, max, min) {
  25750. if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  25751. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  25752. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  25753. }
  25754. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  25755. value = +value;
  25756. offset = offset | 0;
  25757. byteLength = byteLength | 0;
  25758. if (!noAssert) {
  25759. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  25760. checkInt(this, value, offset, byteLength, maxBytes, 0);
  25761. }
  25762. var mul = 1;
  25763. var i = 0;
  25764. this[offset] = value & 0xFF;
  25765. while (++i < byteLength && (mul *= 0x100)) {
  25766. this[offset + i] = (value / mul) & 0xFF;
  25767. }
  25768. return offset + byteLength
  25769. };
  25770. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  25771. value = +value;
  25772. offset = offset | 0;
  25773. byteLength = byteLength | 0;
  25774. if (!noAssert) {
  25775. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  25776. checkInt(this, value, offset, byteLength, maxBytes, 0);
  25777. }
  25778. var i = byteLength - 1;
  25779. var mul = 1;
  25780. this[offset + i] = value & 0xFF;
  25781. while (--i >= 0 && (mul *= 0x100)) {
  25782. this[offset + i] = (value / mul) & 0xFF;
  25783. }
  25784. return offset + byteLength
  25785. };
  25786. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  25787. value = +value;
  25788. offset = offset | 0;
  25789. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
  25790. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
  25791. this[offset] = (value & 0xff);
  25792. return offset + 1
  25793. };
  25794. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  25795. if (value < 0) value = 0xffff + value + 1;
  25796. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  25797. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  25798. (littleEndian ? i : 1 - i) * 8;
  25799. }
  25800. }
  25801. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  25802. value = +value;
  25803. offset = offset | 0;
  25804. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  25805. if (Buffer.TYPED_ARRAY_SUPPORT) {
  25806. this[offset] = (value & 0xff);
  25807. this[offset + 1] = (value >>> 8);
  25808. } else {
  25809. objectWriteUInt16(this, value, offset, true);
  25810. }
  25811. return offset + 2
  25812. };
  25813. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  25814. value = +value;
  25815. offset = offset | 0;
  25816. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  25817. if (Buffer.TYPED_ARRAY_SUPPORT) {
  25818. this[offset] = (value >>> 8);
  25819. this[offset + 1] = (value & 0xff);
  25820. } else {
  25821. objectWriteUInt16(this, value, offset, false);
  25822. }
  25823. return offset + 2
  25824. };
  25825. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  25826. if (value < 0) value = 0xffffffff + value + 1;
  25827. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  25828. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff;
  25829. }
  25830. }
  25831. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  25832. value = +value;
  25833. offset = offset | 0;
  25834. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  25835. if (Buffer.TYPED_ARRAY_SUPPORT) {
  25836. this[offset + 3] = (value >>> 24);
  25837. this[offset + 2] = (value >>> 16);
  25838. this[offset + 1] = (value >>> 8);
  25839. this[offset] = (value & 0xff);
  25840. } else {
  25841. objectWriteUInt32(this, value, offset, true);
  25842. }
  25843. return offset + 4
  25844. };
  25845. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  25846. value = +value;
  25847. offset = offset | 0;
  25848. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  25849. if (Buffer.TYPED_ARRAY_SUPPORT) {
  25850. this[offset] = (value >>> 24);
  25851. this[offset + 1] = (value >>> 16);
  25852. this[offset + 2] = (value >>> 8);
  25853. this[offset + 3] = (value & 0xff);
  25854. } else {
  25855. objectWriteUInt32(this, value, offset, false);
  25856. }
  25857. return offset + 4
  25858. };
  25859. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  25860. value = +value;
  25861. offset = offset | 0;
  25862. if (!noAssert) {
  25863. var limit = Math.pow(2, 8 * byteLength - 1);
  25864. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  25865. }
  25866. var i = 0;
  25867. var mul = 1;
  25868. var sub = 0;
  25869. this[offset] = value & 0xFF;
  25870. while (++i < byteLength && (mul *= 0x100)) {
  25871. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  25872. sub = 1;
  25873. }
  25874. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  25875. }
  25876. return offset + byteLength
  25877. };
  25878. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  25879. value = +value;
  25880. offset = offset | 0;
  25881. if (!noAssert) {
  25882. var limit = Math.pow(2, 8 * byteLength - 1);
  25883. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  25884. }
  25885. var i = byteLength - 1;
  25886. var mul = 1;
  25887. var sub = 0;
  25888. this[offset + i] = value & 0xFF;
  25889. while (--i >= 0 && (mul *= 0x100)) {
  25890. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  25891. sub = 1;
  25892. }
  25893. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  25894. }
  25895. return offset + byteLength
  25896. };
  25897. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  25898. value = +value;
  25899. offset = offset | 0;
  25900. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
  25901. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
  25902. if (value < 0) value = 0xff + value + 1;
  25903. this[offset] = (value & 0xff);
  25904. return offset + 1
  25905. };
  25906. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  25907. value = +value;
  25908. offset = offset | 0;
  25909. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  25910. if (Buffer.TYPED_ARRAY_SUPPORT) {
  25911. this[offset] = (value & 0xff);
  25912. this[offset + 1] = (value >>> 8);
  25913. } else {
  25914. objectWriteUInt16(this, value, offset, true);
  25915. }
  25916. return offset + 2
  25917. };
  25918. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  25919. value = +value;
  25920. offset = offset | 0;
  25921. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  25922. if (Buffer.TYPED_ARRAY_SUPPORT) {
  25923. this[offset] = (value >>> 8);
  25924. this[offset + 1] = (value & 0xff);
  25925. } else {
  25926. objectWriteUInt16(this, value, offset, false);
  25927. }
  25928. return offset + 2
  25929. };
  25930. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  25931. value = +value;
  25932. offset = offset | 0;
  25933. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  25934. if (Buffer.TYPED_ARRAY_SUPPORT) {
  25935. this[offset] = (value & 0xff);
  25936. this[offset + 1] = (value >>> 8);
  25937. this[offset + 2] = (value >>> 16);
  25938. this[offset + 3] = (value >>> 24);
  25939. } else {
  25940. objectWriteUInt32(this, value, offset, true);
  25941. }
  25942. return offset + 4
  25943. };
  25944. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  25945. value = +value;
  25946. offset = offset | 0;
  25947. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  25948. if (value < 0) value = 0xffffffff + value + 1;
  25949. if (Buffer.TYPED_ARRAY_SUPPORT) {
  25950. this[offset] = (value >>> 24);
  25951. this[offset + 1] = (value >>> 16);
  25952. this[offset + 2] = (value >>> 8);
  25953. this[offset + 3] = (value & 0xff);
  25954. } else {
  25955. objectWriteUInt32(this, value, offset, false);
  25956. }
  25957. return offset + 4
  25958. };
  25959. function checkIEEE754 (buf, value, offset, ext, max, min) {
  25960. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  25961. if (offset < 0) throw new RangeError('Index out of range')
  25962. }
  25963. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  25964. if (!noAssert) {
  25965. checkIEEE754(buf, value, offset, 4);
  25966. }
  25967. write(buf, value, offset, littleEndian, 23, 4);
  25968. return offset + 4
  25969. }
  25970. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  25971. return writeFloat(this, value, offset, true, noAssert)
  25972. };
  25973. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  25974. return writeFloat(this, value, offset, false, noAssert)
  25975. };
  25976. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  25977. if (!noAssert) {
  25978. checkIEEE754(buf, value, offset, 8);
  25979. }
  25980. write(buf, value, offset, littleEndian, 52, 8);
  25981. return offset + 8
  25982. }
  25983. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  25984. return writeDouble(this, value, offset, true, noAssert)
  25985. };
  25986. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  25987. return writeDouble(this, value, offset, false, noAssert)
  25988. };
  25989. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  25990. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  25991. if (!start) start = 0;
  25992. if (!end && end !== 0) end = this.length;
  25993. if (targetStart >= target.length) targetStart = target.length;
  25994. if (!targetStart) targetStart = 0;
  25995. if (end > 0 && end < start) end = start;
  25996. // Copy 0 bytes; we're done
  25997. if (end === start) return 0
  25998. if (target.length === 0 || this.length === 0) return 0
  25999. // Fatal error conditions
  26000. if (targetStart < 0) {
  26001. throw new RangeError('targetStart out of bounds')
  26002. }
  26003. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  26004. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  26005. // Are we oob?
  26006. if (end > this.length) end = this.length;
  26007. if (target.length - targetStart < end - start) {
  26008. end = target.length - targetStart + start;
  26009. }
  26010. var len = end - start;
  26011. var i;
  26012. if (this === target && start < targetStart && targetStart < end) {
  26013. // descending copy from end
  26014. for (i = len - 1; i >= 0; --i) {
  26015. target[i + targetStart] = this[i + start];
  26016. }
  26017. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  26018. // ascending copy from start
  26019. for (i = 0; i < len; ++i) {
  26020. target[i + targetStart] = this[i + start];
  26021. }
  26022. } else {
  26023. Uint8Array.prototype.set.call(
  26024. target,
  26025. this.subarray(start, start + len),
  26026. targetStart
  26027. );
  26028. }
  26029. return len
  26030. };
  26031. // Usage:
  26032. // buffer.fill(number[, offset[, end]])
  26033. // buffer.fill(buffer[, offset[, end]])
  26034. // buffer.fill(string[, offset[, end]][, encoding])
  26035. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  26036. // Handle string cases:
  26037. if (typeof val === 'string') {
  26038. if (typeof start === 'string') {
  26039. encoding = start;
  26040. start = 0;
  26041. end = this.length;
  26042. } else if (typeof end === 'string') {
  26043. encoding = end;
  26044. end = this.length;
  26045. }
  26046. if (val.length === 1) {
  26047. var code = val.charCodeAt(0);
  26048. if (code < 256) {
  26049. val = code;
  26050. }
  26051. }
  26052. if (encoding !== undefined && typeof encoding !== 'string') {
  26053. throw new TypeError('encoding must be a string')
  26054. }
  26055. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  26056. throw new TypeError('Unknown encoding: ' + encoding)
  26057. }
  26058. } else if (typeof val === 'number') {
  26059. val = val & 255;
  26060. }
  26061. // Invalid ranges are not set to a default, so can range check early.
  26062. if (start < 0 || this.length < start || this.length < end) {
  26063. throw new RangeError('Out of range index')
  26064. }
  26065. if (end <= start) {
  26066. return this
  26067. }
  26068. start = start >>> 0;
  26069. end = end === undefined ? this.length : end >>> 0;
  26070. if (!val) val = 0;
  26071. var i;
  26072. if (typeof val === 'number') {
  26073. for (i = start; i < end; ++i) {
  26074. this[i] = val;
  26075. }
  26076. } else {
  26077. var bytes = internalIsBuffer(val)
  26078. ? val
  26079. : utf8ToBytes(new Buffer(val, encoding).toString());
  26080. var len = bytes.length;
  26081. for (i = 0; i < end - start; ++i) {
  26082. this[i + start] = bytes[i % len];
  26083. }
  26084. }
  26085. return this
  26086. };
  26087. // HELPER FUNCTIONS
  26088. // ================
  26089. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
  26090. function base64clean (str) {
  26091. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  26092. str = stringtrim(str).replace(INVALID_BASE64_RE, '');
  26093. // Node converts strings with length < 2 to ''
  26094. if (str.length < 2) return ''
  26095. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  26096. while (str.length % 4 !== 0) {
  26097. str = str + '=';
  26098. }
  26099. return str
  26100. }
  26101. function stringtrim (str) {
  26102. if (str.trim) return str.trim()
  26103. return str.replace(/^\s+|\s+$/g, '')
  26104. }
  26105. function toHex (n) {
  26106. if (n < 16) return '0' + n.toString(16)
  26107. return n.toString(16)
  26108. }
  26109. function utf8ToBytes (string, units) {
  26110. units = units || Infinity;
  26111. var codePoint;
  26112. var length = string.length;
  26113. var leadSurrogate = null;
  26114. var bytes = [];
  26115. for (var i = 0; i < length; ++i) {
  26116. codePoint = string.charCodeAt(i);
  26117. // is surrogate component
  26118. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  26119. // last char was a lead
  26120. if (!leadSurrogate) {
  26121. // no lead yet
  26122. if (codePoint > 0xDBFF) {
  26123. // unexpected trail
  26124. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  26125. continue
  26126. } else if (i + 1 === length) {
  26127. // unpaired lead
  26128. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  26129. continue
  26130. }
  26131. // valid lead
  26132. leadSurrogate = codePoint;
  26133. continue
  26134. }
  26135. // 2 leads in a row
  26136. if (codePoint < 0xDC00) {
  26137. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  26138. leadSurrogate = codePoint;
  26139. continue
  26140. }
  26141. // valid surrogate pair
  26142. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
  26143. } else if (leadSurrogate) {
  26144. // valid bmp char, but last char was a lead
  26145. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  26146. }
  26147. leadSurrogate = null;
  26148. // encode utf8
  26149. if (codePoint < 0x80) {
  26150. if ((units -= 1) < 0) break
  26151. bytes.push(codePoint);
  26152. } else if (codePoint < 0x800) {
  26153. if ((units -= 2) < 0) break
  26154. bytes.push(
  26155. codePoint >> 0x6 | 0xC0,
  26156. codePoint & 0x3F | 0x80
  26157. );
  26158. } else if (codePoint < 0x10000) {
  26159. if ((units -= 3) < 0) break
  26160. bytes.push(
  26161. codePoint >> 0xC | 0xE0,
  26162. codePoint >> 0x6 & 0x3F | 0x80,
  26163. codePoint & 0x3F | 0x80
  26164. );
  26165. } else if (codePoint < 0x110000) {
  26166. if ((units -= 4) < 0) break
  26167. bytes.push(
  26168. codePoint >> 0x12 | 0xF0,
  26169. codePoint >> 0xC & 0x3F | 0x80,
  26170. codePoint >> 0x6 & 0x3F | 0x80,
  26171. codePoint & 0x3F | 0x80
  26172. );
  26173. } else {
  26174. throw new Error('Invalid code point')
  26175. }
  26176. }
  26177. return bytes
  26178. }
  26179. function asciiToBytes (str) {
  26180. var byteArray = [];
  26181. for (var i = 0; i < str.length; ++i) {
  26182. // Node's code seems to be doing this and not & 0x7F..
  26183. byteArray.push(str.charCodeAt(i) & 0xFF);
  26184. }
  26185. return byteArray
  26186. }
  26187. function utf16leToBytes (str, units) {
  26188. var c, hi, lo;
  26189. var byteArray = [];
  26190. for (var i = 0; i < str.length; ++i) {
  26191. if ((units -= 2) < 0) break
  26192. c = str.charCodeAt(i);
  26193. hi = c >> 8;
  26194. lo = c % 256;
  26195. byteArray.push(lo);
  26196. byteArray.push(hi);
  26197. }
  26198. return byteArray
  26199. }
  26200. function base64ToBytes (str) {
  26201. return toByteArray(base64clean(str))
  26202. }
  26203. function blitBuffer (src, dst, offset, length) {
  26204. for (var i = 0; i < length; ++i) {
  26205. if ((i + offset >= dst.length) || (i >= src.length)) break
  26206. dst[i + offset] = src[i];
  26207. }
  26208. return i
  26209. }
  26210. function isnan (val) {
  26211. return val !== val // eslint-disable-line no-self-compare
  26212. }
  26213. // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
  26214. // The _isBuffer check is for Safari 5-7 support, because it's missing
  26215. // Object.prototype.constructor. Remove this eventually
  26216. function isBuffer(obj) {
  26217. return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))
  26218. }
  26219. function isFastBuffer (obj) {
  26220. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  26221. }
  26222. // For Node v0.10 support. Remove this eventually.
  26223. function isSlowBuffer (obj) {
  26224. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))
  26225. }
  26226. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  26227. function encode$2(decoded) {
  26228. var sourceFileIndex = 0; // second field
  26229. var sourceCodeLine = 0; // third field
  26230. var sourceCodeColumn = 0; // fourth field
  26231. var nameIndex = 0; // fifth field
  26232. var mappings = '';
  26233. for (var i = 0; i < decoded.length; i++) {
  26234. var line = decoded[i];
  26235. if (i > 0)
  26236. mappings += ';';
  26237. if (line.length === 0)
  26238. continue;
  26239. var generatedCodeColumn = 0; // first field
  26240. var lineMappings = [];
  26241. for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
  26242. var segment = line_1[_i];
  26243. var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
  26244. generatedCodeColumn = segment[0];
  26245. if (segment.length > 1) {
  26246. segmentMappings +=
  26247. encodeInteger(segment[1] - sourceFileIndex) +
  26248. encodeInteger(segment[2] - sourceCodeLine) +
  26249. encodeInteger(segment[3] - sourceCodeColumn);
  26250. sourceFileIndex = segment[1];
  26251. sourceCodeLine = segment[2];
  26252. sourceCodeColumn = segment[3];
  26253. }
  26254. if (segment.length === 5) {
  26255. segmentMappings += encodeInteger(segment[4] - nameIndex);
  26256. nameIndex = segment[4];
  26257. }
  26258. lineMappings.push(segmentMappings);
  26259. }
  26260. mappings += lineMappings.join(',');
  26261. }
  26262. return mappings;
  26263. }
  26264. function encodeInteger(num) {
  26265. var result = '';
  26266. num = num < 0 ? (-num << 1) | 1 : num << 1;
  26267. do {
  26268. var clamped = num & 31;
  26269. num >>>= 5;
  26270. if (num > 0) {
  26271. clamped |= 32;
  26272. }
  26273. result += chars[clamped];
  26274. } while (num > 0);
  26275. return result;
  26276. }
  26277. var BitSet = function BitSet(arg) {
  26278. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  26279. };
  26280. BitSet.prototype.add = function add (n) {
  26281. this.bits[n >> 5] |= 1 << (n & 31);
  26282. };
  26283. BitSet.prototype.has = function has (n) {
  26284. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  26285. };
  26286. var Chunk = function Chunk(start, end, content) {
  26287. this.start = start;
  26288. this.end = end;
  26289. this.original = content;
  26290. this.intro = '';
  26291. this.outro = '';
  26292. this.content = content;
  26293. this.storeName = false;
  26294. this.edited = false;
  26295. // we make these non-enumerable, for sanity while debugging
  26296. Object.defineProperties(this, {
  26297. previous: { writable: true, value: null },
  26298. next: { writable: true, value: null }
  26299. });
  26300. };
  26301. Chunk.prototype.appendLeft = function appendLeft (content) {
  26302. this.outro += content;
  26303. };
  26304. Chunk.prototype.appendRight = function appendRight (content) {
  26305. this.intro = this.intro + content;
  26306. };
  26307. Chunk.prototype.clone = function clone () {
  26308. var chunk = new Chunk(this.start, this.end, this.original);
  26309. chunk.intro = this.intro;
  26310. chunk.outro = this.outro;
  26311. chunk.content = this.content;
  26312. chunk.storeName = this.storeName;
  26313. chunk.edited = this.edited;
  26314. return chunk;
  26315. };
  26316. Chunk.prototype.contains = function contains (index) {
  26317. return this.start < index && index < this.end;
  26318. };
  26319. Chunk.prototype.eachNext = function eachNext (fn) {
  26320. var chunk = this;
  26321. while (chunk) {
  26322. fn(chunk);
  26323. chunk = chunk.next;
  26324. }
  26325. };
  26326. Chunk.prototype.eachPrevious = function eachPrevious (fn) {
  26327. var chunk = this;
  26328. while (chunk) {
  26329. fn(chunk);
  26330. chunk = chunk.previous;
  26331. }
  26332. };
  26333. Chunk.prototype.edit = function edit (content, storeName, contentOnly) {
  26334. this.content = content;
  26335. if (!contentOnly) {
  26336. this.intro = '';
  26337. this.outro = '';
  26338. }
  26339. this.storeName = storeName;
  26340. this.edited = true;
  26341. return this;
  26342. };
  26343. Chunk.prototype.prependLeft = function prependLeft (content) {
  26344. this.outro = content + this.outro;
  26345. };
  26346. Chunk.prototype.prependRight = function prependRight (content) {
  26347. this.intro = content + this.intro;
  26348. };
  26349. Chunk.prototype.split = function split (index) {
  26350. var sliceIndex = index - this.start;
  26351. var originalBefore = this.original.slice(0, sliceIndex);
  26352. var originalAfter = this.original.slice(sliceIndex);
  26353. this.original = originalBefore;
  26354. var newChunk = new Chunk(index, this.end, originalAfter);
  26355. newChunk.outro = this.outro;
  26356. this.outro = '';
  26357. this.end = index;
  26358. if (this.edited) {
  26359. // TODO is this block necessary?...
  26360. newChunk.edit('', false);
  26361. this.content = '';
  26362. } else {
  26363. this.content = originalBefore;
  26364. }
  26365. newChunk.next = this.next;
  26366. if (newChunk.next) { newChunk.next.previous = newChunk; }
  26367. newChunk.previous = this;
  26368. this.next = newChunk;
  26369. return newChunk;
  26370. };
  26371. Chunk.prototype.toString = function toString () {
  26372. return this.intro + this.content + this.outro;
  26373. };
  26374. Chunk.prototype.trimEnd = function trimEnd (rx) {
  26375. this.outro = this.outro.replace(rx, '');
  26376. if (this.outro.length) { return true; }
  26377. var trimmed = this.content.replace(rx, '');
  26378. if (trimmed.length) {
  26379. if (trimmed !== this.content) {
  26380. this.split(this.start + trimmed.length).edit('', undefined, true);
  26381. }
  26382. return true;
  26383. } else {
  26384. this.edit('', undefined, true);
  26385. this.intro = this.intro.replace(rx, '');
  26386. if (this.intro.length) { return true; }
  26387. }
  26388. };
  26389. Chunk.prototype.trimStart = function trimStart (rx) {
  26390. this.intro = this.intro.replace(rx, '');
  26391. if (this.intro.length) { return true; }
  26392. var trimmed = this.content.replace(rx, '');
  26393. if (trimmed.length) {
  26394. if (trimmed !== this.content) {
  26395. this.split(this.end - trimmed.length);
  26396. this.edit('', undefined, true);
  26397. }
  26398. return true;
  26399. } else {
  26400. this.edit('', undefined, true);
  26401. this.outro = this.outro.replace(rx, '');
  26402. if (this.outro.length) { return true; }
  26403. }
  26404. };
  26405. var btoa = function () {
  26406. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  26407. };
  26408. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  26409. btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
  26410. } else if (typeof Buffer === 'function') {
  26411. btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
  26412. }
  26413. var SourceMap = function SourceMap(properties) {
  26414. this.version = 3;
  26415. this.file = properties.file;
  26416. this.sources = properties.sources;
  26417. this.sourcesContent = properties.sourcesContent;
  26418. this.names = properties.names;
  26419. this.mappings = encode$2(properties.mappings);
  26420. };
  26421. SourceMap.prototype.toString = function toString () {
  26422. return JSON.stringify(this);
  26423. };
  26424. SourceMap.prototype.toUrl = function toUrl () {
  26425. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  26426. };
  26427. function guessIndent(code) {
  26428. var lines = code.split('\n');
  26429. var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
  26430. var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
  26431. if (tabbed.length === 0 && spaced.length === 0) {
  26432. return null;
  26433. }
  26434. // More lines tabbed than spaced? Assume tabs, and
  26435. // default to tabs in the case of a tie (or nothing
  26436. // to go on)
  26437. if (tabbed.length >= spaced.length) {
  26438. return '\t';
  26439. }
  26440. // Otherwise, we need to guess the multiple
  26441. var min = spaced.reduce(function (previous, current) {
  26442. var numSpaces = /^ +/.exec(current)[0].length;
  26443. return Math.min(numSpaces, previous);
  26444. }, Infinity);
  26445. return new Array(min + 1).join(' ');
  26446. }
  26447. function getRelativePath(from, to) {
  26448. var fromParts = from.split(/[/\\]/);
  26449. var toParts = to.split(/[/\\]/);
  26450. fromParts.pop(); // get dirname
  26451. while (fromParts[0] === toParts[0]) {
  26452. fromParts.shift();
  26453. toParts.shift();
  26454. }
  26455. if (fromParts.length) {
  26456. var i = fromParts.length;
  26457. while (i--) { fromParts[i] = '..'; }
  26458. }
  26459. return fromParts.concat(toParts).join('/');
  26460. }
  26461. var toString$2 = Object.prototype.toString;
  26462. function isObject$1(thing) {
  26463. return toString$2.call(thing) === '[object Object]';
  26464. }
  26465. function getLocator(source) {
  26466. var originalLines = source.split('\n');
  26467. var lineOffsets = [];
  26468. for (var i = 0, pos = 0; i < originalLines.length; i++) {
  26469. lineOffsets.push(pos);
  26470. pos += originalLines[i].length + 1;
  26471. }
  26472. return function locate(index) {
  26473. var i = 0;
  26474. var j = lineOffsets.length;
  26475. while (i < j) {
  26476. var m = (i + j) >> 1;
  26477. if (index < lineOffsets[m]) {
  26478. j = m;
  26479. } else {
  26480. i = m + 1;
  26481. }
  26482. }
  26483. var line = i - 1;
  26484. var column = index - lineOffsets[line];
  26485. return { line: line, column: column };
  26486. };
  26487. }
  26488. var Mappings = function Mappings(hires) {
  26489. this.hires = hires;
  26490. this.generatedCodeLine = 0;
  26491. this.generatedCodeColumn = 0;
  26492. this.raw = [];
  26493. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  26494. this.pending = null;
  26495. };
  26496. Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) {
  26497. if (content.length) {
  26498. var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  26499. if (nameIndex >= 0) {
  26500. segment.push(nameIndex);
  26501. }
  26502. this.rawSegments.push(segment);
  26503. } else if (this.pending) {
  26504. this.rawSegments.push(this.pending);
  26505. }
  26506. this.advance(content);
  26507. this.pending = null;
  26508. };
  26509. Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) {
  26510. var originalCharIndex = chunk.start;
  26511. var first = true;
  26512. while (originalCharIndex < chunk.end) {
  26513. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  26514. this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
  26515. }
  26516. if (original[originalCharIndex] === '\n') {
  26517. loc.line += 1;
  26518. loc.column = 0;
  26519. this.generatedCodeLine += 1;
  26520. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  26521. this.generatedCodeColumn = 0;
  26522. first = true;
  26523. } else {
  26524. loc.column += 1;
  26525. this.generatedCodeColumn += 1;
  26526. first = false;
  26527. }
  26528. originalCharIndex += 1;
  26529. }
  26530. this.pending = null;
  26531. };
  26532. Mappings.prototype.advance = function advance (str) {
  26533. if (!str) { return; }
  26534. var lines = str.split('\n');
  26535. if (lines.length > 1) {
  26536. for (var i = 0; i < lines.length - 1; i++) {
  26537. this.generatedCodeLine++;
  26538. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  26539. }
  26540. this.generatedCodeColumn = 0;
  26541. }
  26542. this.generatedCodeColumn += lines[lines.length - 1].length;
  26543. };
  26544. var n = '\n';
  26545. var warned = {
  26546. insertLeft: false,
  26547. insertRight: false,
  26548. storeName: false
  26549. };
  26550. var MagicString = function MagicString(string, options) {
  26551. if ( options === void 0 ) options = {};
  26552. var chunk = new Chunk(0, string.length, string);
  26553. Object.defineProperties(this, {
  26554. original: { writable: true, value: string },
  26555. outro: { writable: true, value: '' },
  26556. intro: { writable: true, value: '' },
  26557. firstChunk: { writable: true, value: chunk },
  26558. lastChunk: { writable: true, value: chunk },
  26559. lastSearchedChunk: { writable: true, value: chunk },
  26560. byStart: { writable: true, value: {} },
  26561. byEnd: { writable: true, value: {} },
  26562. filename: { writable: true, value: options.filename },
  26563. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  26564. sourcemapLocations: { writable: true, value: new BitSet() },
  26565. storedNames: { writable: true, value: {} },
  26566. indentStr: { writable: true, value: guessIndent(string) }
  26567. });
  26568. this.byStart[0] = chunk;
  26569. this.byEnd[string.length] = chunk;
  26570. };
  26571. MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) {
  26572. this.sourcemapLocations.add(char);
  26573. };
  26574. MagicString.prototype.append = function append (content) {
  26575. if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
  26576. this.outro += content;
  26577. return this;
  26578. };
  26579. MagicString.prototype.appendLeft = function appendLeft (index, content) {
  26580. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  26581. this._split(index);
  26582. var chunk = this.byEnd[index];
  26583. if (chunk) {
  26584. chunk.appendLeft(content);
  26585. } else {
  26586. this.intro += content;
  26587. }
  26588. return this;
  26589. };
  26590. MagicString.prototype.appendRight = function appendRight (index, content) {
  26591. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  26592. this._split(index);
  26593. var chunk = this.byStart[index];
  26594. if (chunk) {
  26595. chunk.appendRight(content);
  26596. } else {
  26597. this.outro += content;
  26598. }
  26599. return this;
  26600. };
  26601. MagicString.prototype.clone = function clone () {
  26602. var cloned = new MagicString(this.original, { filename: this.filename });
  26603. var originalChunk = this.firstChunk;
  26604. var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  26605. while (originalChunk) {
  26606. cloned.byStart[clonedChunk.start] = clonedChunk;
  26607. cloned.byEnd[clonedChunk.end] = clonedChunk;
  26608. var nextOriginalChunk = originalChunk.next;
  26609. var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  26610. if (nextClonedChunk) {
  26611. clonedChunk.next = nextClonedChunk;
  26612. nextClonedChunk.previous = clonedChunk;
  26613. clonedChunk = nextClonedChunk;
  26614. }
  26615. originalChunk = nextOriginalChunk;
  26616. }
  26617. cloned.lastChunk = clonedChunk;
  26618. if (this.indentExclusionRanges) {
  26619. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  26620. }
  26621. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  26622. cloned.intro = this.intro;
  26623. cloned.outro = this.outro;
  26624. return cloned;
  26625. };
  26626. MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) {
  26627. var this$1 = this;
  26628. options = options || {};
  26629. var sourceIndex = 0;
  26630. var names = Object.keys(this.storedNames);
  26631. var mappings = new Mappings(options.hires);
  26632. var locate = getLocator(this.original);
  26633. if (this.intro) {
  26634. mappings.advance(this.intro);
  26635. }
  26636. this.firstChunk.eachNext(function (chunk) {
  26637. var loc = locate(chunk.start);
  26638. if (chunk.intro.length) { mappings.advance(chunk.intro); }
  26639. if (chunk.edited) {
  26640. mappings.addEdit(
  26641. sourceIndex,
  26642. chunk.content,
  26643. loc,
  26644. chunk.storeName ? names.indexOf(chunk.original) : -1
  26645. );
  26646. } else {
  26647. mappings.addUneditedChunk(sourceIndex, chunk, this$1.original, loc, this$1.sourcemapLocations);
  26648. }
  26649. if (chunk.outro.length) { mappings.advance(chunk.outro); }
  26650. });
  26651. return {
  26652. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  26653. sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
  26654. sourcesContent: options.includeContent ? [this.original] : [null],
  26655. names: names,
  26656. mappings: mappings.raw
  26657. };
  26658. };
  26659. MagicString.prototype.generateMap = function generateMap (options) {
  26660. return new SourceMap(this.generateDecodedMap(options));
  26661. };
  26662. MagicString.prototype.getIndentString = function getIndentString () {
  26663. return this.indentStr === null ? '\t' : this.indentStr;
  26664. };
  26665. MagicString.prototype.indent = function indent (indentStr, options) {
  26666. var pattern = /^[^\r\n]/gm;
  26667. if (isObject$1(indentStr)) {
  26668. options = indentStr;
  26669. indentStr = undefined;
  26670. }
  26671. indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
  26672. if (indentStr === '') { return this; } // noop
  26673. options = options || {};
  26674. // Process exclusion ranges
  26675. var isExcluded = {};
  26676. if (options.exclude) {
  26677. var exclusions =
  26678. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  26679. exclusions.forEach(function (exclusion) {
  26680. for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
  26681. isExcluded[i] = true;
  26682. }
  26683. });
  26684. }
  26685. var shouldIndentNextCharacter = options.indentStart !== false;
  26686. var replacer = function (match) {
  26687. if (shouldIndentNextCharacter) { return ("" + indentStr + match); }
  26688. shouldIndentNextCharacter = true;
  26689. return match;
  26690. };
  26691. this.intro = this.intro.replace(pattern, replacer);
  26692. var charIndex = 0;
  26693. var chunk = this.firstChunk;
  26694. while (chunk) {
  26695. var end = chunk.end;
  26696. if (chunk.edited) {
  26697. if (!isExcluded[charIndex]) {
  26698. chunk.content = chunk.content.replace(pattern, replacer);
  26699. if (chunk.content.length) {
  26700. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  26701. }
  26702. }
  26703. } else {
  26704. charIndex = chunk.start;
  26705. while (charIndex < end) {
  26706. if (!isExcluded[charIndex]) {
  26707. var char = this.original[charIndex];
  26708. if (char === '\n') {
  26709. shouldIndentNextCharacter = true;
  26710. } else if (char !== '\r' && shouldIndentNextCharacter) {
  26711. shouldIndentNextCharacter = false;
  26712. if (charIndex === chunk.start) {
  26713. chunk.prependRight(indentStr);
  26714. } else {
  26715. this._splitChunk(chunk, charIndex);
  26716. chunk = chunk.next;
  26717. chunk.prependRight(indentStr);
  26718. }
  26719. }
  26720. }
  26721. charIndex += 1;
  26722. }
  26723. }
  26724. charIndex = chunk.end;
  26725. chunk = chunk.next;
  26726. }
  26727. this.outro = this.outro.replace(pattern, replacer);
  26728. return this;
  26729. };
  26730. MagicString.prototype.insert = function insert () {
  26731. throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
  26732. };
  26733. MagicString.prototype.insertLeft = function insertLeft (index, content) {
  26734. if (!warned.insertLeft) {
  26735. console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console
  26736. warned.insertLeft = true;
  26737. }
  26738. return this.appendLeft(index, content);
  26739. };
  26740. MagicString.prototype.insertRight = function insertRight (index, content) {
  26741. if (!warned.insertRight) {
  26742. console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console
  26743. warned.insertRight = true;
  26744. }
  26745. return this.prependRight(index, content);
  26746. };
  26747. MagicString.prototype.move = function move (start, end, index) {
  26748. if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); }
  26749. this._split(start);
  26750. this._split(end);
  26751. this._split(index);
  26752. var first = this.byStart[start];
  26753. var last = this.byEnd[end];
  26754. var oldLeft = first.previous;
  26755. var oldRight = last.next;
  26756. var newRight = this.byStart[index];
  26757. if (!newRight && last === this.lastChunk) { return this; }
  26758. var newLeft = newRight ? newRight.previous : this.lastChunk;
  26759. if (oldLeft) { oldLeft.next = oldRight; }
  26760. if (oldRight) { oldRight.previous = oldLeft; }
  26761. if (newLeft) { newLeft.next = first; }
  26762. if (newRight) { newRight.previous = last; }
  26763. if (!first.previous) { this.firstChunk = last.next; }
  26764. if (!last.next) {
  26765. this.lastChunk = first.previous;
  26766. this.lastChunk.next = null;
  26767. }
  26768. first.previous = newLeft;
  26769. last.next = newRight || null;
  26770. if (!newLeft) { this.firstChunk = first; }
  26771. if (!newRight) { this.lastChunk = last; }
  26772. return this;
  26773. };
  26774. MagicString.prototype.overwrite = function overwrite (start, end, content, options) {
  26775. if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); }
  26776. while (start < 0) { start += this.original.length; }
  26777. while (end < 0) { end += this.original.length; }
  26778. if (end > this.original.length) { throw new Error('end is out of bounds'); }
  26779. if (start === end)
  26780. { throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead'); }
  26781. this._split(start);
  26782. this._split(end);
  26783. if (options === true) {
  26784. if (!warned.storeName) {
  26785. 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
  26786. warned.storeName = true;
  26787. }
  26788. options = { storeName: true };
  26789. }
  26790. var storeName = options !== undefined ? options.storeName : false;
  26791. var contentOnly = options !== undefined ? options.contentOnly : false;
  26792. if (storeName) {
  26793. var original = this.original.slice(start, end);
  26794. this.storedNames[original] = true;
  26795. }
  26796. var first = this.byStart[start];
  26797. var last = this.byEnd[end];
  26798. if (first) {
  26799. if (end > first.end && first.next !== this.byStart[first.end]) {
  26800. throw new Error('Cannot overwrite across a split point');
  26801. }
  26802. first.edit(content, storeName, contentOnly);
  26803. if (first !== last) {
  26804. var chunk = first.next;
  26805. while (chunk !== last) {
  26806. chunk.edit('', false);
  26807. chunk = chunk.next;
  26808. }
  26809. chunk.edit('', false);
  26810. }
  26811. } else {
  26812. // must be inserting at the end
  26813. var newChunk = new Chunk(start, end, '').edit(content, storeName);
  26814. // TODO last chunk in the array may not be the last chunk, if it's moved...
  26815. last.next = newChunk;
  26816. newChunk.previous = last;
  26817. }
  26818. return this;
  26819. };
  26820. MagicString.prototype.prepend = function prepend (content) {
  26821. if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
  26822. this.intro = content + this.intro;
  26823. return this;
  26824. };
  26825. MagicString.prototype.prependLeft = function prependLeft (index, content) {
  26826. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  26827. this._split(index);
  26828. var chunk = this.byEnd[index];
  26829. if (chunk) {
  26830. chunk.prependLeft(content);
  26831. } else {
  26832. this.intro = content + this.intro;
  26833. }
  26834. return this;
  26835. };
  26836. MagicString.prototype.prependRight = function prependRight (index, content) {
  26837. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  26838. this._split(index);
  26839. var chunk = this.byStart[index];
  26840. if (chunk) {
  26841. chunk.prependRight(content);
  26842. } else {
  26843. this.outro = content + this.outro;
  26844. }
  26845. return this;
  26846. };
  26847. MagicString.prototype.remove = function remove (start, end) {
  26848. while (start < 0) { start += this.original.length; }
  26849. while (end < 0) { end += this.original.length; }
  26850. if (start === end) { return this; }
  26851. if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); }
  26852. if (start > end) { throw new Error('end must be greater than start'); }
  26853. this._split(start);
  26854. this._split(end);
  26855. var chunk = this.byStart[start];
  26856. while (chunk) {
  26857. chunk.intro = '';
  26858. chunk.outro = '';
  26859. chunk.edit('');
  26860. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  26861. }
  26862. return this;
  26863. };
  26864. MagicString.prototype.lastChar = function lastChar () {
  26865. if (this.outro.length)
  26866. { return this.outro[this.outro.length - 1]; }
  26867. var chunk = this.lastChunk;
  26868. do {
  26869. if (chunk.outro.length)
  26870. { return chunk.outro[chunk.outro.length - 1]; }
  26871. if (chunk.content.length)
  26872. { return chunk.content[chunk.content.length - 1]; }
  26873. if (chunk.intro.length)
  26874. { return chunk.intro[chunk.intro.length - 1]; }
  26875. } while (chunk = chunk.previous);
  26876. if (this.intro.length)
  26877. { return this.intro[this.intro.length - 1]; }
  26878. return '';
  26879. };
  26880. MagicString.prototype.lastLine = function lastLine () {
  26881. var lineIndex = this.outro.lastIndexOf(n);
  26882. if (lineIndex !== -1)
  26883. { return this.outro.substr(lineIndex + 1); }
  26884. var lineStr = this.outro;
  26885. var chunk = this.lastChunk;
  26886. do {
  26887. if (chunk.outro.length > 0) {
  26888. lineIndex = chunk.outro.lastIndexOf(n);
  26889. if (lineIndex !== -1)
  26890. { return chunk.outro.substr(lineIndex + 1) + lineStr; }
  26891. lineStr = chunk.outro + lineStr;
  26892. }
  26893. if (chunk.content.length > 0) {
  26894. lineIndex = chunk.content.lastIndexOf(n);
  26895. if (lineIndex !== -1)
  26896. { return chunk.content.substr(lineIndex + 1) + lineStr; }
  26897. lineStr = chunk.content + lineStr;
  26898. }
  26899. if (chunk.intro.length > 0) {
  26900. lineIndex = chunk.intro.lastIndexOf(n);
  26901. if (lineIndex !== -1)
  26902. { return chunk.intro.substr(lineIndex + 1) + lineStr; }
  26903. lineStr = chunk.intro + lineStr;
  26904. }
  26905. } while (chunk = chunk.previous);
  26906. lineIndex = this.intro.lastIndexOf(n);
  26907. if (lineIndex !== -1)
  26908. { return this.intro.substr(lineIndex + 1) + lineStr; }
  26909. return this.intro + lineStr;
  26910. };
  26911. MagicString.prototype.slice = function slice (start, end) {
  26912. if ( start === void 0 ) start = 0;
  26913. if ( end === void 0 ) end = this.original.length;
  26914. while (start < 0) { start += this.original.length; }
  26915. while (end < 0) { end += this.original.length; }
  26916. var result = '';
  26917. // find start chunk
  26918. var chunk = this.firstChunk;
  26919. while (chunk && (chunk.start > start || chunk.end <= start)) {
  26920. // found end chunk before start
  26921. if (chunk.start < end && chunk.end >= end) {
  26922. return result;
  26923. }
  26924. chunk = chunk.next;
  26925. }
  26926. if (chunk && chunk.edited && chunk.start !== start)
  26927. { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
  26928. var startChunk = chunk;
  26929. while (chunk) {
  26930. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  26931. result += chunk.intro;
  26932. }
  26933. var containsEnd = chunk.start < end && chunk.end >= end;
  26934. if (containsEnd && chunk.edited && chunk.end !== end)
  26935. { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
  26936. var sliceStart = startChunk === chunk ? start - chunk.start : 0;
  26937. var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  26938. result += chunk.content.slice(sliceStart, sliceEnd);
  26939. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  26940. result += chunk.outro;
  26941. }
  26942. if (containsEnd) {
  26943. break;
  26944. }
  26945. chunk = chunk.next;
  26946. }
  26947. return result;
  26948. };
  26949. // TODO deprecate this? not really very useful
  26950. MagicString.prototype.snip = function snip (start, end) {
  26951. var clone = this.clone();
  26952. clone.remove(0, start);
  26953. clone.remove(end, clone.original.length);
  26954. return clone;
  26955. };
  26956. MagicString.prototype._split = function _split (index) {
  26957. if (this.byStart[index] || this.byEnd[index]) { return; }
  26958. var chunk = this.lastSearchedChunk;
  26959. var searchForward = index > chunk.end;
  26960. while (chunk) {
  26961. if (chunk.contains(index)) { return this._splitChunk(chunk, index); }
  26962. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  26963. }
  26964. };
  26965. MagicString.prototype._splitChunk = function _splitChunk (chunk, index) {
  26966. if (chunk.edited && chunk.content.length) {
  26967. // zero-length edited chunks are a special case (overlapping replacements)
  26968. var loc = getLocator(this.original)(index);
  26969. throw new Error(
  26970. ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")")
  26971. );
  26972. }
  26973. var newChunk = chunk.split(index);
  26974. this.byEnd[index] = chunk;
  26975. this.byStart[index] = newChunk;
  26976. this.byEnd[newChunk.end] = newChunk;
  26977. if (chunk === this.lastChunk) { this.lastChunk = newChunk; }
  26978. this.lastSearchedChunk = chunk;
  26979. return true;
  26980. };
  26981. MagicString.prototype.toString = function toString () {
  26982. var str = this.intro;
  26983. var chunk = this.firstChunk;
  26984. while (chunk) {
  26985. str += chunk.toString();
  26986. chunk = chunk.next;
  26987. }
  26988. return str + this.outro;
  26989. };
  26990. MagicString.prototype.isEmpty = function isEmpty () {
  26991. var chunk = this.firstChunk;
  26992. do {
  26993. if (chunk.intro.length && chunk.intro.trim() ||
  26994. chunk.content.length && chunk.content.trim() ||
  26995. chunk.outro.length && chunk.outro.trim())
  26996. { return false; }
  26997. } while (chunk = chunk.next);
  26998. return true;
  26999. };
  27000. MagicString.prototype.length = function length () {
  27001. var chunk = this.firstChunk;
  27002. var length = 0;
  27003. do {
  27004. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  27005. } while (chunk = chunk.next);
  27006. return length;
  27007. };
  27008. MagicString.prototype.trimLines = function trimLines () {
  27009. return this.trim('[\\r\\n]');
  27010. };
  27011. MagicString.prototype.trim = function trim (charType) {
  27012. return this.trimStart(charType).trimEnd(charType);
  27013. };
  27014. MagicString.prototype.trimEndAborted = function trimEndAborted (charType) {
  27015. var rx = new RegExp((charType || '\\s') + '+$');
  27016. this.outro = this.outro.replace(rx, '');
  27017. if (this.outro.length) { return true; }
  27018. var chunk = this.lastChunk;
  27019. do {
  27020. var end = chunk.end;
  27021. var aborted = chunk.trimEnd(rx);
  27022. // if chunk was trimmed, we have a new lastChunk
  27023. if (chunk.end !== end) {
  27024. if (this.lastChunk === chunk) {
  27025. this.lastChunk = chunk.next;
  27026. }
  27027. this.byEnd[chunk.end] = chunk;
  27028. this.byStart[chunk.next.start] = chunk.next;
  27029. this.byEnd[chunk.next.end] = chunk.next;
  27030. }
  27031. if (aborted) { return true; }
  27032. chunk = chunk.previous;
  27033. } while (chunk);
  27034. return false;
  27035. };
  27036. MagicString.prototype.trimEnd = function trimEnd (charType) {
  27037. this.trimEndAborted(charType);
  27038. return this;
  27039. };
  27040. MagicString.prototype.trimStartAborted = function trimStartAborted (charType) {
  27041. var rx = new RegExp('^' + (charType || '\\s') + '+');
  27042. this.intro = this.intro.replace(rx, '');
  27043. if (this.intro.length) { return true; }
  27044. var chunk = this.firstChunk;
  27045. do {
  27046. var end = chunk.end;
  27047. var aborted = chunk.trimStart(rx);
  27048. if (chunk.end !== end) {
  27049. // special case...
  27050. if (chunk === this.lastChunk) { this.lastChunk = chunk.next; }
  27051. this.byEnd[chunk.end] = chunk;
  27052. this.byStart[chunk.next.start] = chunk.next;
  27053. this.byEnd[chunk.next.end] = chunk.next;
  27054. }
  27055. if (aborted) { return true; }
  27056. chunk = chunk.next;
  27057. } while (chunk);
  27058. return false;
  27059. };
  27060. MagicString.prototype.trimStart = function trimStart (charType) {
  27061. this.trimStartAborted(charType);
  27062. return this;
  27063. };
  27064. // Copyright Joyent, Inc. and other Node contributors.
  27065. //
  27066. // Permission is hereby granted, free of charge, to any person obtaining a
  27067. // copy of this software and associated documentation files (the
  27068. // "Software"), to deal in the Software without restriction, including
  27069. // without limitation the rights to use, copy, modify, merge, publish,
  27070. // distribute, sublicense, and/or sell copies of the Software, and to permit
  27071. // persons to whom the Software is furnished to do so, subject to the
  27072. // following conditions:
  27073. //
  27074. // The above copyright notice and this permission notice shall be included
  27075. // in all copies or substantial portions of the Software.
  27076. //
  27077. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  27078. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27079. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  27080. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  27081. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  27082. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  27083. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  27084. // resolves . and .. elements in a path array with directory names there
  27085. // must be no slashes, empty elements, or device names (c:\) in the array
  27086. // (so also no leading and trailing slashes - it does not distinguish
  27087. // relative and absolute paths)
  27088. function normalizeArray(parts, allowAboveRoot) {
  27089. // if the path tries to go above the root, `up` ends up > 0
  27090. var up = 0;
  27091. for (var i = parts.length - 1; i >= 0; i--) {
  27092. var last = parts[i];
  27093. if (last === '.') {
  27094. parts.splice(i, 1);
  27095. } else if (last === '..') {
  27096. parts.splice(i, 1);
  27097. up++;
  27098. } else if (up) {
  27099. parts.splice(i, 1);
  27100. up--;
  27101. }
  27102. }
  27103. // if the path is allowed to go above the root, restore leading ..s
  27104. if (allowAboveRoot) {
  27105. for (; up--; up) {
  27106. parts.unshift('..');
  27107. }
  27108. }
  27109. return parts;
  27110. }
  27111. // Split a filename into [root, dir, basename, ext], unix version
  27112. // 'root' is just a slash, or nothing.
  27113. var splitPathRe =
  27114. /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
  27115. var splitPath = function(filename) {
  27116. return splitPathRe.exec(filename).slice(1);
  27117. };
  27118. // path.resolve([from ...], to)
  27119. // posix version
  27120. function resolve() {
  27121. var resolvedPath = '',
  27122. resolvedAbsolute = false;
  27123. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  27124. var path = (i >= 0) ? arguments[i] : '/';
  27125. // Skip empty and invalid entries
  27126. if (typeof path !== 'string') {
  27127. throw new TypeError('Arguments to path.resolve must be strings');
  27128. } else if (!path) {
  27129. continue;
  27130. }
  27131. resolvedPath = path + '/' + resolvedPath;
  27132. resolvedAbsolute = path.charAt(0) === '/';
  27133. }
  27134. // At this point the path should be resolved to a full absolute path, but
  27135. // handle relative paths to be safe (might happen when process.cwd() fails)
  27136. // Normalize the path
  27137. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  27138. return !!p;
  27139. }), !resolvedAbsolute).join('/');
  27140. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  27141. }
  27142. // path.normalize(path)
  27143. // posix version
  27144. function normalize(path) {
  27145. var isPathAbsolute = isAbsolute(path),
  27146. trailingSlash = substr(path, -1) === '/';
  27147. // Normalize the path
  27148. path = normalizeArray(filter(path.split('/'), function(p) {
  27149. return !!p;
  27150. }), !isPathAbsolute).join('/');
  27151. if (!path && !isPathAbsolute) {
  27152. path = '.';
  27153. }
  27154. if (path && trailingSlash) {
  27155. path += '/';
  27156. }
  27157. return (isPathAbsolute ? '/' : '') + path;
  27158. }
  27159. // posix version
  27160. function isAbsolute(path) {
  27161. return path.charAt(0) === '/';
  27162. }
  27163. // posix version
  27164. function join() {
  27165. var paths = Array.prototype.slice.call(arguments, 0);
  27166. return normalize(filter(paths, function(p, index) {
  27167. if (typeof p !== 'string') {
  27168. throw new TypeError('Arguments to path.join must be strings');
  27169. }
  27170. return p;
  27171. }).join('/'));
  27172. }
  27173. // path.relative(from, to)
  27174. // posix version
  27175. function relative(from, to) {
  27176. from = resolve(from).substr(1);
  27177. to = resolve(to).substr(1);
  27178. function trim(arr) {
  27179. var start = 0;
  27180. for (; start < arr.length; start++) {
  27181. if (arr[start] !== '') break;
  27182. }
  27183. var end = arr.length - 1;
  27184. for (; end >= 0; end--) {
  27185. if (arr[end] !== '') break;
  27186. }
  27187. if (start > end) return [];
  27188. return arr.slice(start, end - start + 1);
  27189. }
  27190. var fromParts = trim(from.split('/'));
  27191. var toParts = trim(to.split('/'));
  27192. var length = Math.min(fromParts.length, toParts.length);
  27193. var samePartsLength = length;
  27194. for (var i = 0; i < length; i++) {
  27195. if (fromParts[i] !== toParts[i]) {
  27196. samePartsLength = i;
  27197. break;
  27198. }
  27199. }
  27200. var outputParts = [];
  27201. for (var i = samePartsLength; i < fromParts.length; i++) {
  27202. outputParts.push('..');
  27203. }
  27204. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  27205. return outputParts.join('/');
  27206. }
  27207. var sep = '/';
  27208. var delimiter = ':';
  27209. function dirname(path) {
  27210. var result = splitPath(path),
  27211. root = result[0],
  27212. dir = result[1];
  27213. if (!root && !dir) {
  27214. // No dirname whatsoever
  27215. return '.';
  27216. }
  27217. if (dir) {
  27218. // It has a dirname, strip trailing slash
  27219. dir = dir.substr(0, dir.length - 1);
  27220. }
  27221. return root + dir;
  27222. }
  27223. function basename(path, ext) {
  27224. var f = splitPath(path)[2];
  27225. // TODO: make this comparison case-insensitive on windows?
  27226. if (ext && f.substr(-1 * ext.length) === ext) {
  27227. f = f.substr(0, f.length - ext.length);
  27228. }
  27229. return f;
  27230. }
  27231. function extname(path) {
  27232. return splitPath(path)[3];
  27233. }
  27234. var path = {
  27235. extname: extname,
  27236. basename: basename,
  27237. dirname: dirname,
  27238. sep: sep,
  27239. delimiter: delimiter,
  27240. relative: relative,
  27241. join: join,
  27242. isAbsolute: isAbsolute,
  27243. normalize: normalize,
  27244. resolve: resolve
  27245. };
  27246. function filter (xs, f) {
  27247. if (xs.filter) return xs.filter(f);
  27248. var res = [];
  27249. for (var i = 0; i < xs.length; i++) {
  27250. if (f(xs[i], i, xs)) res.push(xs[i]);
  27251. }
  27252. return res;
  27253. }
  27254. // String.prototype.substr - negative index don't work in IE8
  27255. var substr = 'ab'.substr(-1) === 'b' ?
  27256. function (str, start, len) { return str.substr(start, len) } :
  27257. function (str, start, len) {
  27258. if (start < 0) start = str.length + start;
  27259. return str.substr(start, len);
  27260. }
  27261. ;
  27262. var _polyfillNode_path = /*#__PURE__*/Object.freeze({
  27263. __proto__: null,
  27264. resolve: resolve,
  27265. normalize: normalize,
  27266. isAbsolute: isAbsolute,
  27267. join: join,
  27268. relative: relative,
  27269. sep: sep,
  27270. delimiter: delimiter,
  27271. dirname: dirname,
  27272. basename: basename,
  27273. extname: extname,
  27274. 'default': path
  27275. });
  27276. /*! https://mths.be/punycode v1.4.1 by @mathias */
  27277. /** Highest positive signed 32-bit float value */
  27278. var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
  27279. /** Bootstring parameters */
  27280. var base = 36;
  27281. var tMin = 1;
  27282. var tMax = 26;
  27283. var skew = 38;
  27284. var damp = 700;
  27285. var initialBias = 72;
  27286. var initialN = 128; // 0x80
  27287. var delimiter$1 = '-'; // '\x2D'
  27288. var regexNonASCII = /[^\x20-\x7E]/; // unprintable ASCII chars + non-ASCII chars
  27289. var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
  27290. /** Error messages */
  27291. var errors = {
  27292. 'overflow': 'Overflow: input needs wider integers to process',
  27293. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  27294. 'invalid-input': 'Invalid input'
  27295. };
  27296. /** Convenience shortcuts */
  27297. var baseMinusTMin = base - tMin;
  27298. var floor = Math.floor;
  27299. var stringFromCharCode = String.fromCharCode;
  27300. /*--------------------------------------------------------------------------*/
  27301. /**
  27302. * A generic error utility function.
  27303. * @private
  27304. * @param {String} type The error type.
  27305. * @returns {Error} Throws a `RangeError` with the applicable error message.
  27306. */
  27307. function error(type) {
  27308. throw new RangeError(errors[type]);
  27309. }
  27310. /**
  27311. * A generic `Array#map` utility function.
  27312. * @private
  27313. * @param {Array} array The array to iterate over.
  27314. * @param {Function} callback The function that gets called for every array
  27315. * item.
  27316. * @returns {Array} A new array of values returned by the callback function.
  27317. */
  27318. function map(array, fn) {
  27319. var length = array.length;
  27320. var result = [];
  27321. while (length--) {
  27322. result[length] = fn(array[length]);
  27323. }
  27324. return result;
  27325. }
  27326. /**
  27327. * A simple `Array#map`-like wrapper to work with domain name strings or email
  27328. * addresses.
  27329. * @private
  27330. * @param {String} domain The domain name or email address.
  27331. * @param {Function} callback The function that gets called for every
  27332. * character.
  27333. * @returns {Array} A new string of characters returned by the callback
  27334. * function.
  27335. */
  27336. function mapDomain(string, fn) {
  27337. var parts = string.split('@');
  27338. var result = '';
  27339. if (parts.length > 1) {
  27340. // In email addresses, only the domain name should be punycoded. Leave
  27341. // the local part (i.e. everything up to `@`) intact.
  27342. result = parts[0] + '@';
  27343. string = parts[1];
  27344. }
  27345. // Avoid `split(regex)` for IE8 compatibility. See #17.
  27346. string = string.replace(regexSeparators, '\x2E');
  27347. var labels = string.split('.');
  27348. var encoded = map(labels, fn).join('.');
  27349. return result + encoded;
  27350. }
  27351. /**
  27352. * Creates an array containing the numeric code points of each Unicode
  27353. * character in the string. While JavaScript uses UCS-2 internally,
  27354. * this function will convert a pair of surrogate halves (each of which
  27355. * UCS-2 exposes as separate characters) into a single code point,
  27356. * matching UTF-16.
  27357. * @see `punycode.ucs2.encode`
  27358. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  27359. * @memberOf punycode.ucs2
  27360. * @name decode
  27361. * @param {String} string The Unicode input string (UCS-2).
  27362. * @returns {Array} The new array of code points.
  27363. */
  27364. function ucs2decode(string) {
  27365. var output = [],
  27366. counter = 0,
  27367. length = string.length,
  27368. value,
  27369. extra;
  27370. while (counter < length) {
  27371. value = string.charCodeAt(counter++);
  27372. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  27373. // high surrogate, and there is a next character
  27374. extra = string.charCodeAt(counter++);
  27375. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  27376. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  27377. } else {
  27378. // unmatched surrogate; only append this code unit, in case the next
  27379. // code unit is the high surrogate of a surrogate pair
  27380. output.push(value);
  27381. counter--;
  27382. }
  27383. } else {
  27384. output.push(value);
  27385. }
  27386. }
  27387. return output;
  27388. }
  27389. /**
  27390. * Converts a digit/integer into a basic code point.
  27391. * @see `basicToDigit()`
  27392. * @private
  27393. * @param {Number} digit The numeric value of a basic code point.
  27394. * @returns {Number} The basic code point whose value (when used for
  27395. * representing integers) is `digit`, which needs to be in the range
  27396. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  27397. * used; else, the lowercase form is used. The behavior is undefined
  27398. * if `flag` is non-zero and `digit` has no uppercase form.
  27399. */
  27400. function digitToBasic(digit, flag) {
  27401. // 0..25 map to ASCII a..z or A..Z
  27402. // 26..35 map to ASCII 0..9
  27403. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  27404. }
  27405. /**
  27406. * Bias adaptation function as per section 3.4 of RFC 3492.
  27407. * https://tools.ietf.org/html/rfc3492#section-3.4
  27408. * @private
  27409. */
  27410. function adapt(delta, numPoints, firstTime) {
  27411. var k = 0;
  27412. delta = firstTime ? floor(delta / damp) : delta >> 1;
  27413. delta += floor(delta / numPoints);
  27414. for ( /* no initialization */ ; delta > baseMinusTMin * tMax >> 1; k += base) {
  27415. delta = floor(delta / baseMinusTMin);
  27416. }
  27417. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  27418. }
  27419. /**
  27420. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  27421. * Punycode string of ASCII-only symbols.
  27422. * @memberOf punycode
  27423. * @param {String} input The string of Unicode symbols.
  27424. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  27425. */
  27426. function encode$3(input) {
  27427. var n,
  27428. delta,
  27429. handledCPCount,
  27430. basicLength,
  27431. bias,
  27432. j,
  27433. m,
  27434. q,
  27435. k,
  27436. t,
  27437. currentValue,
  27438. output = [],
  27439. /** `inputLength` will hold the number of code points in `input`. */
  27440. inputLength,
  27441. /** Cached calculation results */
  27442. handledCPCountPlusOne,
  27443. baseMinusT,
  27444. qMinusT;
  27445. // Convert the input in UCS-2 to Unicode
  27446. input = ucs2decode(input);
  27447. // Cache the length
  27448. inputLength = input.length;
  27449. // Initialize the state
  27450. n = initialN;
  27451. delta = 0;
  27452. bias = initialBias;
  27453. // Handle the basic code points
  27454. for (j = 0; j < inputLength; ++j) {
  27455. currentValue = input[j];
  27456. if (currentValue < 0x80) {
  27457. output.push(stringFromCharCode(currentValue));
  27458. }
  27459. }
  27460. handledCPCount = basicLength = output.length;
  27461. // `handledCPCount` is the number of code points that have been handled;
  27462. // `basicLength` is the number of basic code points.
  27463. // Finish the basic string - if it is not empty - with a delimiter
  27464. if (basicLength) {
  27465. output.push(delimiter$1);
  27466. }
  27467. // Main encoding loop:
  27468. while (handledCPCount < inputLength) {
  27469. // All non-basic code points < n have been handled already. Find the next
  27470. // larger one:
  27471. for (m = maxInt, j = 0; j < inputLength; ++j) {
  27472. currentValue = input[j];
  27473. if (currentValue >= n && currentValue < m) {
  27474. m = currentValue;
  27475. }
  27476. }
  27477. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  27478. // but guard against overflow
  27479. handledCPCountPlusOne = handledCPCount + 1;
  27480. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  27481. error('overflow');
  27482. }
  27483. delta += (m - n) * handledCPCountPlusOne;
  27484. n = m;
  27485. for (j = 0; j < inputLength; ++j) {
  27486. currentValue = input[j];
  27487. if (currentValue < n && ++delta > maxInt) {
  27488. error('overflow');
  27489. }
  27490. if (currentValue == n) {
  27491. // Represent delta as a generalized variable-length integer
  27492. for (q = delta, k = base; /* no condition */ ; k += base) {
  27493. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  27494. if (q < t) {
  27495. break;
  27496. }
  27497. qMinusT = q - t;
  27498. baseMinusT = base - t;
  27499. output.push(
  27500. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  27501. );
  27502. q = floor(qMinusT / baseMinusT);
  27503. }
  27504. output.push(stringFromCharCode(digitToBasic(q, 0)));
  27505. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  27506. delta = 0;
  27507. ++handledCPCount;
  27508. }
  27509. }
  27510. ++delta;
  27511. ++n;
  27512. }
  27513. return output.join('');
  27514. }
  27515. /**
  27516. * Converts a Unicode string representing a domain name or an email address to
  27517. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  27518. * i.e. it doesn't matter if you call it with a domain that's already in
  27519. * ASCII.
  27520. * @memberOf punycode
  27521. * @param {String} input The domain name or email address to convert, as a
  27522. * Unicode string.
  27523. * @returns {String} The Punycode representation of the given domain name or
  27524. * email address.
  27525. */
  27526. function toASCII(input) {
  27527. return mapDomain(input, function(string) {
  27528. return regexNonASCII.test(string) ?
  27529. 'xn--' + encode$3(string) :
  27530. string;
  27531. });
  27532. }
  27533. // shim for using process in browser
  27534. // based off https://github.com/defunctzombie/node-process/blob/master/browser.js
  27535. function defaultSetTimout() {
  27536. throw new Error('setTimeout has not been defined');
  27537. }
  27538. function defaultClearTimeout () {
  27539. throw new Error('clearTimeout has not been defined');
  27540. }
  27541. var cachedSetTimeout = defaultSetTimout;
  27542. var cachedClearTimeout = defaultClearTimeout;
  27543. if (typeof global.setTimeout === 'function') {
  27544. cachedSetTimeout = setTimeout;
  27545. }
  27546. if (typeof global.clearTimeout === 'function') {
  27547. cachedClearTimeout = clearTimeout;
  27548. }
  27549. function runTimeout(fun) {
  27550. if (cachedSetTimeout === setTimeout) {
  27551. //normal enviroments in sane situations
  27552. return setTimeout(fun, 0);
  27553. }
  27554. // if setTimeout wasn't available but was latter defined
  27555. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  27556. cachedSetTimeout = setTimeout;
  27557. return setTimeout(fun, 0);
  27558. }
  27559. try {
  27560. // when when somebody has screwed with setTimeout but no I.E. maddness
  27561. return cachedSetTimeout(fun, 0);
  27562. } catch(e){
  27563. try {
  27564. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  27565. return cachedSetTimeout.call(null, fun, 0);
  27566. } catch(e){
  27567. // 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
  27568. return cachedSetTimeout.call(this, fun, 0);
  27569. }
  27570. }
  27571. }
  27572. function runClearTimeout(marker) {
  27573. if (cachedClearTimeout === clearTimeout) {
  27574. //normal enviroments in sane situations
  27575. return clearTimeout(marker);
  27576. }
  27577. // if clearTimeout wasn't available but was latter defined
  27578. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  27579. cachedClearTimeout = clearTimeout;
  27580. return clearTimeout(marker);
  27581. }
  27582. try {
  27583. // when when somebody has screwed with setTimeout but no I.E. maddness
  27584. return cachedClearTimeout(marker);
  27585. } catch (e){
  27586. try {
  27587. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  27588. return cachedClearTimeout.call(null, marker);
  27589. } catch (e){
  27590. // 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.
  27591. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  27592. return cachedClearTimeout.call(this, marker);
  27593. }
  27594. }
  27595. }
  27596. var queue = [];
  27597. var draining = false;
  27598. var currentQueue;
  27599. var queueIndex = -1;
  27600. function cleanUpNextTick() {
  27601. if (!draining || !currentQueue) {
  27602. return;
  27603. }
  27604. draining = false;
  27605. if (currentQueue.length) {
  27606. queue = currentQueue.concat(queue);
  27607. } else {
  27608. queueIndex = -1;
  27609. }
  27610. if (queue.length) {
  27611. drainQueue();
  27612. }
  27613. }
  27614. function drainQueue() {
  27615. if (draining) {
  27616. return;
  27617. }
  27618. var timeout = runTimeout(cleanUpNextTick);
  27619. draining = true;
  27620. var len = queue.length;
  27621. while(len) {
  27622. currentQueue = queue;
  27623. queue = [];
  27624. while (++queueIndex < len) {
  27625. if (currentQueue) {
  27626. currentQueue[queueIndex].run();
  27627. }
  27628. }
  27629. queueIndex = -1;
  27630. len = queue.length;
  27631. }
  27632. currentQueue = null;
  27633. draining = false;
  27634. runClearTimeout(timeout);
  27635. }
  27636. function nextTick(fun) {
  27637. var args = new Array(arguments.length - 1);
  27638. if (arguments.length > 1) {
  27639. for (var i = 1; i < arguments.length; i++) {
  27640. args[i - 1] = arguments[i];
  27641. }
  27642. }
  27643. queue.push(new Item(fun, args));
  27644. if (queue.length === 1 && !draining) {
  27645. runTimeout(drainQueue);
  27646. }
  27647. }
  27648. // v8 likes predictible objects
  27649. function Item(fun, array) {
  27650. this.fun = fun;
  27651. this.array = array;
  27652. }
  27653. Item.prototype.run = function () {
  27654. this.fun.apply(null, this.array);
  27655. };
  27656. var title = 'browser';
  27657. var platform = 'browser';
  27658. var browser = true;
  27659. var env = {};
  27660. var argv = [];
  27661. var version = ''; // empty string to avoid regexp issues
  27662. var versions = {};
  27663. var release = {};
  27664. var config = {};
  27665. function noop() {}
  27666. var on = noop;
  27667. var addListener = noop;
  27668. var once = noop;
  27669. var off = noop;
  27670. var removeListener = noop;
  27671. var removeAllListeners = noop;
  27672. var emit = noop;
  27673. function binding(name) {
  27674. throw new Error('process.binding is not supported');
  27675. }
  27676. function cwd () { return '/' }
  27677. function chdir (dir) {
  27678. throw new Error('process.chdir is not supported');
  27679. }function umask() { return 0; }
  27680. // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
  27681. var performance = global.performance || {};
  27682. var performanceNow =
  27683. performance.now ||
  27684. performance.mozNow ||
  27685. performance.msNow ||
  27686. performance.oNow ||
  27687. performance.webkitNow ||
  27688. function(){ return (new Date()).getTime() };
  27689. // generate timestamp or delta
  27690. // see http://nodejs.org/api/process.html#process_process_hrtime
  27691. function hrtime(previousTimestamp){
  27692. var clocktime = performanceNow.call(performance)*1e-3;
  27693. var seconds = Math.floor(clocktime);
  27694. var nanoseconds = Math.floor((clocktime%1)*1e9);
  27695. if (previousTimestamp) {
  27696. seconds = seconds - previousTimestamp[0];
  27697. nanoseconds = nanoseconds - previousTimestamp[1];
  27698. if (nanoseconds<0) {
  27699. seconds--;
  27700. nanoseconds += 1e9;
  27701. }
  27702. }
  27703. return [seconds,nanoseconds]
  27704. }
  27705. var startTime = new Date();
  27706. function uptime() {
  27707. var currentTime = new Date();
  27708. var dif = currentTime - startTime;
  27709. return dif / 1000;
  27710. }
  27711. var browser$1 = {
  27712. nextTick: nextTick,
  27713. title: title,
  27714. browser: browser,
  27715. env: env,
  27716. argv: argv,
  27717. version: version,
  27718. versions: versions,
  27719. on: on,
  27720. addListener: addListener,
  27721. once: once,
  27722. off: off,
  27723. removeListener: removeListener,
  27724. removeAllListeners: removeAllListeners,
  27725. emit: emit,
  27726. binding: binding,
  27727. cwd: cwd,
  27728. chdir: chdir,
  27729. umask: umask,
  27730. hrtime: hrtime,
  27731. platform: platform,
  27732. release: release,
  27733. config: config,
  27734. uptime: uptime
  27735. };
  27736. var inherits;
  27737. if (typeof Object.create === 'function'){
  27738. inherits = function inherits(ctor, superCtor) {
  27739. // implementation from standard node.js 'util' module
  27740. ctor.super_ = superCtor;
  27741. ctor.prototype = Object.create(superCtor.prototype, {
  27742. constructor: {
  27743. value: ctor,
  27744. enumerable: false,
  27745. writable: true,
  27746. configurable: true
  27747. }
  27748. });
  27749. };
  27750. } else {
  27751. inherits = function inherits(ctor, superCtor) {
  27752. ctor.super_ = superCtor;
  27753. var TempCtor = function () {};
  27754. TempCtor.prototype = superCtor.prototype;
  27755. ctor.prototype = new TempCtor();
  27756. ctor.prototype.constructor = ctor;
  27757. };
  27758. }
  27759. var inherits$1 = inherits;
  27760. var formatRegExp = /%[sdj%]/g;
  27761. function format(f) {
  27762. if (!isString$1(f)) {
  27763. var objects = [];
  27764. for (var i = 0; i < arguments.length; i++) {
  27765. objects.push(inspect(arguments[i]));
  27766. }
  27767. return objects.join(' ');
  27768. }
  27769. var i = 1;
  27770. var args = arguments;
  27771. var len = args.length;
  27772. var str = String(f).replace(formatRegExp, function(x) {
  27773. if (x === '%%') return '%';
  27774. if (i >= len) return x;
  27775. switch (x) {
  27776. case '%s': return String(args[i++]);
  27777. case '%d': return Number(args[i++]);
  27778. case '%j':
  27779. try {
  27780. return JSON.stringify(args[i++]);
  27781. } catch (_) {
  27782. return '[Circular]';
  27783. }
  27784. default:
  27785. return x;
  27786. }
  27787. });
  27788. for (var x = args[i]; i < len; x = args[++i]) {
  27789. if (isNull(x) || !isObject$2(x)) {
  27790. str += ' ' + x;
  27791. } else {
  27792. str += ' ' + inspect(x);
  27793. }
  27794. }
  27795. return str;
  27796. }
  27797. // Mark that a method should not be used.
  27798. // Returns a modified function which warns once by default.
  27799. // If --no-deprecation is set, then it is a no-op.
  27800. function deprecate(fn, msg) {
  27801. // Allow for deprecating things in the process of starting up.
  27802. if (isUndefined(global.process)) {
  27803. return function() {
  27804. return deprecate(fn, msg).apply(this, arguments);
  27805. };
  27806. }
  27807. if (browser$1.noDeprecation === true) {
  27808. return fn;
  27809. }
  27810. var warned = false;
  27811. function deprecated() {
  27812. if (!warned) {
  27813. if (browser$1.throwDeprecation) {
  27814. throw new Error(msg);
  27815. } else if (browser$1.traceDeprecation) {
  27816. console.trace(msg);
  27817. } else {
  27818. console.error(msg);
  27819. }
  27820. warned = true;
  27821. }
  27822. return fn.apply(this, arguments);
  27823. }
  27824. return deprecated;
  27825. }
  27826. var debugs = {};
  27827. var debugEnviron;
  27828. function debuglog(set) {
  27829. if (isUndefined(debugEnviron))
  27830. debugEnviron = browser$1.env.NODE_DEBUG || '';
  27831. set = set.toUpperCase();
  27832. if (!debugs[set]) {
  27833. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  27834. var pid = 0;
  27835. debugs[set] = function() {
  27836. var msg = format.apply(null, arguments);
  27837. console.error('%s %d: %s', set, pid, msg);
  27838. };
  27839. } else {
  27840. debugs[set] = function() {};
  27841. }
  27842. }
  27843. return debugs[set];
  27844. }
  27845. /**
  27846. * Echos the value of a value. Trys to print the value out
  27847. * in the best way possible given the different types.
  27848. *
  27849. * @param {Object} obj The object to print out.
  27850. * @param {Object} opts Optional options object that alters the output.
  27851. */
  27852. /* legacy: obj, showHidden, depth, colors*/
  27853. function inspect(obj, opts) {
  27854. // default options
  27855. var ctx = {
  27856. seen: [],
  27857. stylize: stylizeNoColor
  27858. };
  27859. // legacy...
  27860. if (arguments.length >= 3) ctx.depth = arguments[2];
  27861. if (arguments.length >= 4) ctx.colors = arguments[3];
  27862. if (isBoolean(opts)) {
  27863. // legacy...
  27864. ctx.showHidden = opts;
  27865. } else if (opts) {
  27866. // got an "options" object
  27867. _extend(ctx, opts);
  27868. }
  27869. // set default options
  27870. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  27871. if (isUndefined(ctx.depth)) ctx.depth = 2;
  27872. if (isUndefined(ctx.colors)) ctx.colors = false;
  27873. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  27874. if (ctx.colors) ctx.stylize = stylizeWithColor;
  27875. return formatValue(ctx, obj, ctx.depth);
  27876. }
  27877. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  27878. inspect.colors = {
  27879. 'bold' : [1, 22],
  27880. 'italic' : [3, 23],
  27881. 'underline' : [4, 24],
  27882. 'inverse' : [7, 27],
  27883. 'white' : [37, 39],
  27884. 'grey' : [90, 39],
  27885. 'black' : [30, 39],
  27886. 'blue' : [34, 39],
  27887. 'cyan' : [36, 39],
  27888. 'green' : [32, 39],
  27889. 'magenta' : [35, 39],
  27890. 'red' : [31, 39],
  27891. 'yellow' : [33, 39]
  27892. };
  27893. // Don't use 'blue' not visible on cmd.exe
  27894. inspect.styles = {
  27895. 'special': 'cyan',
  27896. 'number': 'yellow',
  27897. 'boolean': 'yellow',
  27898. 'undefined': 'grey',
  27899. 'null': 'bold',
  27900. 'string': 'green',
  27901. 'date': 'magenta',
  27902. // "name": intentionally not styling
  27903. 'regexp': 'red'
  27904. };
  27905. function stylizeWithColor(str, styleType) {
  27906. var style = inspect.styles[styleType];
  27907. if (style) {
  27908. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  27909. '\u001b[' + inspect.colors[style][1] + 'm';
  27910. } else {
  27911. return str;
  27912. }
  27913. }
  27914. function stylizeNoColor(str, styleType) {
  27915. return str;
  27916. }
  27917. function arrayToHash(array) {
  27918. var hash = {};
  27919. array.forEach(function(val, idx) {
  27920. hash[val] = true;
  27921. });
  27922. return hash;
  27923. }
  27924. function formatValue(ctx, value, recurseTimes) {
  27925. // Provide a hook for user-specified inspect functions.
  27926. // Check that value is an object with an inspect function on it
  27927. if (ctx.customInspect &&
  27928. value &&
  27929. isFunction$1(value.inspect) &&
  27930. // Filter out the util module, it's inspect function is special
  27931. value.inspect !== inspect &&
  27932. // Also filter out any prototype objects using the circular check.
  27933. !(value.constructor && value.constructor.prototype === value)) {
  27934. var ret = value.inspect(recurseTimes, ctx);
  27935. if (!isString$1(ret)) {
  27936. ret = formatValue(ctx, ret, recurseTimes);
  27937. }
  27938. return ret;
  27939. }
  27940. // Primitive types cannot have properties
  27941. var primitive = formatPrimitive(ctx, value);
  27942. if (primitive) {
  27943. return primitive;
  27944. }
  27945. // Look up the keys of the object.
  27946. var keys = Object.keys(value);
  27947. var visibleKeys = arrayToHash(keys);
  27948. if (ctx.showHidden) {
  27949. keys = Object.getOwnPropertyNames(value);
  27950. }
  27951. // IE doesn't make error fields non-enumerable
  27952. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  27953. if (isError(value)
  27954. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  27955. return formatError(value);
  27956. }
  27957. // Some type of object without properties can be shortcutted.
  27958. if (keys.length === 0) {
  27959. if (isFunction$1(value)) {
  27960. var name = value.name ? ': ' + value.name : '';
  27961. return ctx.stylize('[Function' + name + ']', 'special');
  27962. }
  27963. if (isRegExp(value)) {
  27964. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  27965. }
  27966. if (isDate(value)) {
  27967. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  27968. }
  27969. if (isError(value)) {
  27970. return formatError(value);
  27971. }
  27972. }
  27973. var base = '', array = false, braces = ['{', '}'];
  27974. // Make Array say that they are Array
  27975. if (isArray$2(value)) {
  27976. array = true;
  27977. braces = ['[', ']'];
  27978. }
  27979. // Make functions say that they are functions
  27980. if (isFunction$1(value)) {
  27981. var n = value.name ? ': ' + value.name : '';
  27982. base = ' [Function' + n + ']';
  27983. }
  27984. // Make RegExps say that they are RegExps
  27985. if (isRegExp(value)) {
  27986. base = ' ' + RegExp.prototype.toString.call(value);
  27987. }
  27988. // Make dates with properties first say the date
  27989. if (isDate(value)) {
  27990. base = ' ' + Date.prototype.toUTCString.call(value);
  27991. }
  27992. // Make error with message first say the error
  27993. if (isError(value)) {
  27994. base = ' ' + formatError(value);
  27995. }
  27996. if (keys.length === 0 && (!array || value.length == 0)) {
  27997. return braces[0] + base + braces[1];
  27998. }
  27999. if (recurseTimes < 0) {
  28000. if (isRegExp(value)) {
  28001. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  28002. } else {
  28003. return ctx.stylize('[Object]', 'special');
  28004. }
  28005. }
  28006. ctx.seen.push(value);
  28007. var output;
  28008. if (array) {
  28009. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  28010. } else {
  28011. output = keys.map(function(key) {
  28012. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  28013. });
  28014. }
  28015. ctx.seen.pop();
  28016. return reduceToSingleString(output, base, braces);
  28017. }
  28018. function formatPrimitive(ctx, value) {
  28019. if (isUndefined(value))
  28020. return ctx.stylize('undefined', 'undefined');
  28021. if (isString$1(value)) {
  28022. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  28023. .replace(/'/g, "\\'")
  28024. .replace(/\\"/g, '"') + '\'';
  28025. return ctx.stylize(simple, 'string');
  28026. }
  28027. if (isNumber(value))
  28028. return ctx.stylize('' + value, 'number');
  28029. if (isBoolean(value))
  28030. return ctx.stylize('' + value, 'boolean');
  28031. // For some reason typeof null is "object", so special case here.
  28032. if (isNull(value))
  28033. return ctx.stylize('null', 'null');
  28034. }
  28035. function formatError(value) {
  28036. return '[' + Error.prototype.toString.call(value) + ']';
  28037. }
  28038. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  28039. var output = [];
  28040. for (var i = 0, l = value.length; i < l; ++i) {
  28041. if (hasOwnProperty$1(value, String(i))) {
  28042. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  28043. String(i), true));
  28044. } else {
  28045. output.push('');
  28046. }
  28047. }
  28048. keys.forEach(function(key) {
  28049. if (!key.match(/^\d+$/)) {
  28050. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  28051. key, true));
  28052. }
  28053. });
  28054. return output;
  28055. }
  28056. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  28057. var name, str, desc;
  28058. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  28059. if (desc.get) {
  28060. if (desc.set) {
  28061. str = ctx.stylize('[Getter/Setter]', 'special');
  28062. } else {
  28063. str = ctx.stylize('[Getter]', 'special');
  28064. }
  28065. } else {
  28066. if (desc.set) {
  28067. str = ctx.stylize('[Setter]', 'special');
  28068. }
  28069. }
  28070. if (!hasOwnProperty$1(visibleKeys, key)) {
  28071. name = '[' + key + ']';
  28072. }
  28073. if (!str) {
  28074. if (ctx.seen.indexOf(desc.value) < 0) {
  28075. if (isNull(recurseTimes)) {
  28076. str = formatValue(ctx, desc.value, null);
  28077. } else {
  28078. str = formatValue(ctx, desc.value, recurseTimes - 1);
  28079. }
  28080. if (str.indexOf('\n') > -1) {
  28081. if (array) {
  28082. str = str.split('\n').map(function(line) {
  28083. return ' ' + line;
  28084. }).join('\n').substr(2);
  28085. } else {
  28086. str = '\n' + str.split('\n').map(function(line) {
  28087. return ' ' + line;
  28088. }).join('\n');
  28089. }
  28090. }
  28091. } else {
  28092. str = ctx.stylize('[Circular]', 'special');
  28093. }
  28094. }
  28095. if (isUndefined(name)) {
  28096. if (array && key.match(/^\d+$/)) {
  28097. return str;
  28098. }
  28099. name = JSON.stringify('' + key);
  28100. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  28101. name = name.substr(1, name.length - 2);
  28102. name = ctx.stylize(name, 'name');
  28103. } else {
  28104. name = name.replace(/'/g, "\\'")
  28105. .replace(/\\"/g, '"')
  28106. .replace(/(^"|"$)/g, "'");
  28107. name = ctx.stylize(name, 'string');
  28108. }
  28109. }
  28110. return name + ': ' + str;
  28111. }
  28112. function reduceToSingleString(output, base, braces) {
  28113. var length = output.reduce(function(prev, cur) {
  28114. if (cur.indexOf('\n') >= 0) ;
  28115. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  28116. }, 0);
  28117. if (length > 60) {
  28118. return braces[0] +
  28119. (base === '' ? '' : base + '\n ') +
  28120. ' ' +
  28121. output.join(',\n ') +
  28122. ' ' +
  28123. braces[1];
  28124. }
  28125. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  28126. }
  28127. // NOTE: These type checking functions intentionally don't use `instanceof`
  28128. // because it is fragile and can be easily faked with `Object.create()`.
  28129. function isArray$2(ar) {
  28130. return Array.isArray(ar);
  28131. }
  28132. function isBoolean(arg) {
  28133. return typeof arg === 'boolean';
  28134. }
  28135. function isNull(arg) {
  28136. return arg === null;
  28137. }
  28138. function isNullOrUndefined(arg) {
  28139. return arg == null;
  28140. }
  28141. function isNumber(arg) {
  28142. return typeof arg === 'number';
  28143. }
  28144. function isString$1(arg) {
  28145. return typeof arg === 'string';
  28146. }
  28147. function isSymbol$1(arg) {
  28148. return typeof arg === 'symbol';
  28149. }
  28150. function isUndefined(arg) {
  28151. return arg === void 0;
  28152. }
  28153. function isRegExp(re) {
  28154. return isObject$2(re) && objectToString$1(re) === '[object RegExp]';
  28155. }
  28156. function isObject$2(arg) {
  28157. return typeof arg === 'object' && arg !== null;
  28158. }
  28159. function isDate(d) {
  28160. return isObject$2(d) && objectToString$1(d) === '[object Date]';
  28161. }
  28162. function isError(e) {
  28163. return isObject$2(e) &&
  28164. (objectToString$1(e) === '[object Error]' || e instanceof Error);
  28165. }
  28166. function isFunction$1(arg) {
  28167. return typeof arg === 'function';
  28168. }
  28169. function isPrimitive(arg) {
  28170. return arg === null ||
  28171. typeof arg === 'boolean' ||
  28172. typeof arg === 'number' ||
  28173. typeof arg === 'string' ||
  28174. typeof arg === 'symbol' || // ES6 symbol
  28175. typeof arg === 'undefined';
  28176. }
  28177. function isBuffer$1(maybeBuf) {
  28178. return Buffer.isBuffer(maybeBuf);
  28179. }
  28180. function objectToString$1(o) {
  28181. return Object.prototype.toString.call(o);
  28182. }
  28183. function pad$1(n) {
  28184. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  28185. }
  28186. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  28187. 'Oct', 'Nov', 'Dec'];
  28188. // 26 Feb 16:19:34
  28189. function timestamp() {
  28190. var d = new Date();
  28191. var time = [pad$1(d.getHours()),
  28192. pad$1(d.getMinutes()),
  28193. pad$1(d.getSeconds())].join(':');
  28194. return [d.getDate(), months[d.getMonth()], time].join(' ');
  28195. }
  28196. // log is just a thin wrapper to console.log that prepends a timestamp
  28197. function log() {
  28198. console.log('%s - %s', timestamp(), format.apply(null, arguments));
  28199. }
  28200. function _extend(origin, add) {
  28201. // Don't do anything if add isn't an object
  28202. if (!add || !isObject$2(add)) return origin;
  28203. var keys = Object.keys(add);
  28204. var i = keys.length;
  28205. while (i--) {
  28206. origin[keys[i]] = add[keys[i]];
  28207. }
  28208. return origin;
  28209. }
  28210. function hasOwnProperty$1(obj, prop) {
  28211. return Object.prototype.hasOwnProperty.call(obj, prop);
  28212. }
  28213. var _polyfillNode_util = {
  28214. inherits: inherits$1,
  28215. _extend: _extend,
  28216. log: log,
  28217. isBuffer: isBuffer$1,
  28218. isPrimitive: isPrimitive,
  28219. isFunction: isFunction$1,
  28220. isError: isError,
  28221. isDate: isDate,
  28222. isObject: isObject$2,
  28223. isRegExp: isRegExp,
  28224. isUndefined: isUndefined,
  28225. isSymbol: isSymbol$1,
  28226. isString: isString$1,
  28227. isNumber: isNumber,
  28228. isNullOrUndefined: isNullOrUndefined,
  28229. isNull: isNull,
  28230. isBoolean: isBoolean,
  28231. isArray: isArray$2,
  28232. inspect: inspect,
  28233. deprecate: deprecate,
  28234. format: format,
  28235. debuglog: debuglog
  28236. };
  28237. var _polyfillNode_util$1 = /*#__PURE__*/Object.freeze({
  28238. __proto__: null,
  28239. format: format,
  28240. deprecate: deprecate,
  28241. debuglog: debuglog,
  28242. inspect: inspect,
  28243. isArray: isArray$2,
  28244. isBoolean: isBoolean,
  28245. isNull: isNull,
  28246. isNullOrUndefined: isNullOrUndefined,
  28247. isNumber: isNumber,
  28248. isString: isString$1,
  28249. isSymbol: isSymbol$1,
  28250. isUndefined: isUndefined,
  28251. isRegExp: isRegExp,
  28252. isObject: isObject$2,
  28253. isDate: isDate,
  28254. isError: isError,
  28255. isFunction: isFunction$1,
  28256. isPrimitive: isPrimitive,
  28257. isBuffer: isBuffer$1,
  28258. log: log,
  28259. inherits: inherits$1,
  28260. _extend: _extend,
  28261. 'default': _polyfillNode_util
  28262. });
  28263. // Copyright Joyent, Inc. and other Node contributors.
  28264. //
  28265. // Permission is hereby granted, free of charge, to any person obtaining a
  28266. // copy of this software and associated documentation files (the
  28267. // "Software"), to deal in the Software without restriction, including
  28268. // without limitation the rights to use, copy, modify, merge, publish,
  28269. // distribute, sublicense, and/or sell copies of the Software, and to permit
  28270. // persons to whom the Software is furnished to do so, subject to the
  28271. // following conditions:
  28272. //
  28273. // The above copyright notice and this permission notice shall be included
  28274. // in all copies or substantial portions of the Software.
  28275. //
  28276. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  28277. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  28278. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  28279. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  28280. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  28281. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  28282. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  28283. // If obj.hasOwnProperty has been overridden, then calling
  28284. // obj.hasOwnProperty(prop) will break.
  28285. // See: https://github.com/joyent/node/issues/1707
  28286. function hasOwnProperty$2(obj, prop) {
  28287. return Object.prototype.hasOwnProperty.call(obj, prop);
  28288. }
  28289. var isArray$3 = Array.isArray || function (xs) {
  28290. return Object.prototype.toString.call(xs) === '[object Array]';
  28291. };
  28292. function stringifyPrimitive(v) {
  28293. switch (typeof v) {
  28294. case 'string':
  28295. return v;
  28296. case 'boolean':
  28297. return v ? 'true' : 'false';
  28298. case 'number':
  28299. return isFinite(v) ? v : '';
  28300. default:
  28301. return '';
  28302. }
  28303. }
  28304. function stringify (obj, sep, eq, name) {
  28305. sep = sep || '&';
  28306. eq = eq || '=';
  28307. if (obj === null) {
  28308. obj = undefined;
  28309. }
  28310. if (typeof obj === 'object') {
  28311. return map$1(objectKeys(obj), function(k) {
  28312. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  28313. if (isArray$3(obj[k])) {
  28314. return map$1(obj[k], function(v) {
  28315. return ks + encodeURIComponent(stringifyPrimitive(v));
  28316. }).join(sep);
  28317. } else {
  28318. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  28319. }
  28320. }).join(sep);
  28321. }
  28322. if (!name) return '';
  28323. return encodeURIComponent(stringifyPrimitive(name)) + eq +
  28324. encodeURIComponent(stringifyPrimitive(obj));
  28325. }
  28326. function map$1 (xs, f) {
  28327. if (xs.map) return xs.map(f);
  28328. var res = [];
  28329. for (var i = 0; i < xs.length; i++) {
  28330. res.push(f(xs[i], i));
  28331. }
  28332. return res;
  28333. }
  28334. var objectKeys = Object.keys || function (obj) {
  28335. var res = [];
  28336. for (var key in obj) {
  28337. if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
  28338. }
  28339. return res;
  28340. };
  28341. function parse$2(qs, sep, eq, options) {
  28342. sep = sep || '&';
  28343. eq = eq || '=';
  28344. var obj = {};
  28345. if (typeof qs !== 'string' || qs.length === 0) {
  28346. return obj;
  28347. }
  28348. var regexp = /\+/g;
  28349. qs = qs.split(sep);
  28350. var maxKeys = 1000;
  28351. if (options && typeof options.maxKeys === 'number') {
  28352. maxKeys = options.maxKeys;
  28353. }
  28354. var len = qs.length;
  28355. // maxKeys <= 0 means that we should not limit keys count
  28356. if (maxKeys > 0 && len > maxKeys) {
  28357. len = maxKeys;
  28358. }
  28359. for (var i = 0; i < len; ++i) {
  28360. var x = qs[i].replace(regexp, '%20'),
  28361. idx = x.indexOf(eq),
  28362. kstr, vstr, k, v;
  28363. if (idx >= 0) {
  28364. kstr = x.substr(0, idx);
  28365. vstr = x.substr(idx + 1);
  28366. } else {
  28367. kstr = x;
  28368. vstr = '';
  28369. }
  28370. k = decodeURIComponent(kstr);
  28371. v = decodeURIComponent(vstr);
  28372. if (!hasOwnProperty$2(obj, k)) {
  28373. obj[k] = v;
  28374. } else if (isArray$3(obj[k])) {
  28375. obj[k].push(v);
  28376. } else {
  28377. obj[k] = [obj[k], v];
  28378. }
  28379. }
  28380. return obj;
  28381. }
  28382. // Copyright Joyent, Inc. and other Node contributors.
  28383. var _polyfillNode_url = {
  28384. parse: urlParse,
  28385. resolve: urlResolve,
  28386. resolveObject: urlResolveObject,
  28387. format: urlFormat,
  28388. Url: Url
  28389. };
  28390. function Url() {
  28391. this.protocol = null;
  28392. this.slashes = null;
  28393. this.auth = null;
  28394. this.host = null;
  28395. this.port = null;
  28396. this.hostname = null;
  28397. this.hash = null;
  28398. this.search = null;
  28399. this.query = null;
  28400. this.pathname = null;
  28401. this.path = null;
  28402. this.href = null;
  28403. }
  28404. // Reference: RFC 3986, RFC 1808, RFC 2396
  28405. // define these here so at least they only have to be
  28406. // compiled once on the first module load.
  28407. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  28408. portPattern = /:[0-9]*$/,
  28409. // Special case for a simple path URL
  28410. simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
  28411. // RFC 2396: characters reserved for delimiting URLs.
  28412. // We actually just auto-escape these.
  28413. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  28414. // RFC 2396: characters not allowed for various reasons.
  28415. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  28416. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  28417. autoEscape = ['\''].concat(unwise),
  28418. // Characters that are never ever allowed in a hostname.
  28419. // Note that any invalid chars are also handled, but these
  28420. // are the ones that are *expected* to be seen, so we fast-path
  28421. // them.
  28422. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  28423. hostEndingChars = ['/', '?', '#'],
  28424. hostnameMaxLen = 255,
  28425. hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
  28426. hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
  28427. // protocols that can allow "unsafe" and "unwise" chars.
  28428. unsafeProtocol = {
  28429. 'javascript': true,
  28430. 'javascript:': true
  28431. },
  28432. // protocols that never have a hostname.
  28433. hostlessProtocol = {
  28434. 'javascript': true,
  28435. 'javascript:': true
  28436. },
  28437. // protocols that always contain a // bit.
  28438. slashedProtocol = {
  28439. 'http': true,
  28440. 'https': true,
  28441. 'ftp': true,
  28442. 'gopher': true,
  28443. 'file': true,
  28444. 'http:': true,
  28445. 'https:': true,
  28446. 'ftp:': true,
  28447. 'gopher:': true,
  28448. 'file:': true
  28449. };
  28450. function urlParse(url, parseQueryString, slashesDenoteHost) {
  28451. if (url && isObject$2(url) && url instanceof Url) return url;
  28452. var u = new Url;
  28453. u.parse(url, parseQueryString, slashesDenoteHost);
  28454. return u;
  28455. }
  28456. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  28457. return parse$3(this, url, parseQueryString, slashesDenoteHost);
  28458. };
  28459. function parse$3(self, url, parseQueryString, slashesDenoteHost) {
  28460. if (!isString$1(url)) {
  28461. throw new TypeError('Parameter \'url\' must be a string, not ' + typeof url);
  28462. }
  28463. // Copy chrome, IE, opera backslash-handling behavior.
  28464. // Back slashes before the query string get converted to forward slashes
  28465. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  28466. var queryIndex = url.indexOf('?'),
  28467. splitter =
  28468. (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
  28469. uSplit = url.split(splitter),
  28470. slashRegex = /\\/g;
  28471. uSplit[0] = uSplit[0].replace(slashRegex, '/');
  28472. url = uSplit.join(splitter);
  28473. var rest = url;
  28474. // trim before proceeding.
  28475. // This is to support parse stuff like " http://foo.com \n"
  28476. rest = rest.trim();
  28477. if (!slashesDenoteHost && url.split('#').length === 1) {
  28478. // Try fast path regexp
  28479. var simplePath = simplePathPattern.exec(rest);
  28480. if (simplePath) {
  28481. self.path = rest;
  28482. self.href = rest;
  28483. self.pathname = simplePath[1];
  28484. if (simplePath[2]) {
  28485. self.search = simplePath[2];
  28486. if (parseQueryString) {
  28487. self.query = parse$2(self.search.substr(1));
  28488. } else {
  28489. self.query = self.search.substr(1);
  28490. }
  28491. } else if (parseQueryString) {
  28492. self.search = '';
  28493. self.query = {};
  28494. }
  28495. return self;
  28496. }
  28497. }
  28498. var proto = protocolPattern.exec(rest);
  28499. if (proto) {
  28500. proto = proto[0];
  28501. var lowerProto = proto.toLowerCase();
  28502. self.protocol = lowerProto;
  28503. rest = rest.substr(proto.length);
  28504. }
  28505. // figure out if it's got a host
  28506. // user@server is *always* interpreted as a hostname, and url
  28507. // resolution will treat //foo/bar as host=foo,path=bar because that's
  28508. // how the browser resolves relative URLs.
  28509. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  28510. var slashes = rest.substr(0, 2) === '//';
  28511. if (slashes && !(proto && hostlessProtocol[proto])) {
  28512. rest = rest.substr(2);
  28513. self.slashes = true;
  28514. }
  28515. }
  28516. var i, hec, l, p;
  28517. if (!hostlessProtocol[proto] &&
  28518. (slashes || (proto && !slashedProtocol[proto]))) {
  28519. // there's a hostname.
  28520. // the first instance of /, ?, ;, or # ends the host.
  28521. //
  28522. // If there is an @ in the hostname, then non-host chars *are* allowed
  28523. // to the left of the last @ sign, unless some host-ending character
  28524. // comes *before* the @-sign.
  28525. // URLs are obnoxious.
  28526. //
  28527. // ex:
  28528. // http://a@b@c/ => user:a@b host:c
  28529. // http://a@b?@c => user:a host:c path:/?@c
  28530. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  28531. // Review our test case against browsers more comprehensively.
  28532. // find the first instance of any hostEndingChars
  28533. var hostEnd = -1;
  28534. for (i = 0; i < hostEndingChars.length; i++) {
  28535. hec = rest.indexOf(hostEndingChars[i]);
  28536. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  28537. hostEnd = hec;
  28538. }
  28539. // at this point, either we have an explicit point where the
  28540. // auth portion cannot go past, or the last @ char is the decider.
  28541. var auth, atSign;
  28542. if (hostEnd === -1) {
  28543. // atSign can be anywhere.
  28544. atSign = rest.lastIndexOf('@');
  28545. } else {
  28546. // atSign must be in auth portion.
  28547. // http://a@b/c@d => host:b auth:a path:/c@d
  28548. atSign = rest.lastIndexOf('@', hostEnd);
  28549. }
  28550. // Now we have a portion which is definitely the auth.
  28551. // Pull that off.
  28552. if (atSign !== -1) {
  28553. auth = rest.slice(0, atSign);
  28554. rest = rest.slice(atSign + 1);
  28555. self.auth = decodeURIComponent(auth);
  28556. }
  28557. // the host is the remaining to the left of the first non-host char
  28558. hostEnd = -1;
  28559. for (i = 0; i < nonHostChars.length; i++) {
  28560. hec = rest.indexOf(nonHostChars[i]);
  28561. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  28562. hostEnd = hec;
  28563. }
  28564. // if we still have not hit it, then the entire thing is a host.
  28565. if (hostEnd === -1)
  28566. hostEnd = rest.length;
  28567. self.host = rest.slice(0, hostEnd);
  28568. rest = rest.slice(hostEnd);
  28569. // pull out port.
  28570. parseHost(self);
  28571. // we've indicated that there is a hostname,
  28572. // so even if it's empty, it has to be present.
  28573. self.hostname = self.hostname || '';
  28574. // if hostname begins with [ and ends with ]
  28575. // assume that it's an IPv6 address.
  28576. var ipv6Hostname = self.hostname[0] === '[' &&
  28577. self.hostname[self.hostname.length - 1] === ']';
  28578. // validate a little.
  28579. if (!ipv6Hostname) {
  28580. var hostparts = self.hostname.split(/\./);
  28581. for (i = 0, l = hostparts.length; i < l; i++) {
  28582. var part = hostparts[i];
  28583. if (!part) continue;
  28584. if (!part.match(hostnamePartPattern)) {
  28585. var newpart = '';
  28586. for (var j = 0, k = part.length; j < k; j++) {
  28587. if (part.charCodeAt(j) > 127) {
  28588. // we replace non-ASCII char with a temporary placeholder
  28589. // we need this to make sure size of hostname is not
  28590. // broken by replacing non-ASCII by nothing
  28591. newpart += 'x';
  28592. } else {
  28593. newpart += part[j];
  28594. }
  28595. }
  28596. // we test again with ASCII char only
  28597. if (!newpart.match(hostnamePartPattern)) {
  28598. var validParts = hostparts.slice(0, i);
  28599. var notHost = hostparts.slice(i + 1);
  28600. var bit = part.match(hostnamePartStart);
  28601. if (bit) {
  28602. validParts.push(bit[1]);
  28603. notHost.unshift(bit[2]);
  28604. }
  28605. if (notHost.length) {
  28606. rest = '/' + notHost.join('.') + rest;
  28607. }
  28608. self.hostname = validParts.join('.');
  28609. break;
  28610. }
  28611. }
  28612. }
  28613. }
  28614. if (self.hostname.length > hostnameMaxLen) {
  28615. self.hostname = '';
  28616. } else {
  28617. // hostnames are always lower case.
  28618. self.hostname = self.hostname.toLowerCase();
  28619. }
  28620. if (!ipv6Hostname) {
  28621. // IDNA Support: Returns a punycoded representation of "domain".
  28622. // It only converts parts of the domain name that
  28623. // have non-ASCII characters, i.e. it doesn't matter if
  28624. // you call it with a domain that already is ASCII-only.
  28625. self.hostname = toASCII(self.hostname);
  28626. }
  28627. p = self.port ? ':' + self.port : '';
  28628. var h = self.hostname || '';
  28629. self.host = h + p;
  28630. self.href += self.host;
  28631. // strip [ and ] from the hostname
  28632. // the host field still retains them, though
  28633. if (ipv6Hostname) {
  28634. self.hostname = self.hostname.substr(1, self.hostname.length - 2);
  28635. if (rest[0] !== '/') {
  28636. rest = '/' + rest;
  28637. }
  28638. }
  28639. }
  28640. // now rest is set to the post-host stuff.
  28641. // chop off any delim chars.
  28642. if (!unsafeProtocol[lowerProto]) {
  28643. // First, make 100% sure that any "autoEscape" chars get
  28644. // escaped, even if encodeURIComponent doesn't think they
  28645. // need to be.
  28646. for (i = 0, l = autoEscape.length; i < l; i++) {
  28647. var ae = autoEscape[i];
  28648. if (rest.indexOf(ae) === -1)
  28649. continue;
  28650. var esc = encodeURIComponent(ae);
  28651. if (esc === ae) {
  28652. esc = escape(ae);
  28653. }
  28654. rest = rest.split(ae).join(esc);
  28655. }
  28656. }
  28657. // chop off from the tail first.
  28658. var hash = rest.indexOf('#');
  28659. if (hash !== -1) {
  28660. // got a fragment string.
  28661. self.hash = rest.substr(hash);
  28662. rest = rest.slice(0, hash);
  28663. }
  28664. var qm = rest.indexOf('?');
  28665. if (qm !== -1) {
  28666. self.search = rest.substr(qm);
  28667. self.query = rest.substr(qm + 1);
  28668. if (parseQueryString) {
  28669. self.query = parse$2(self.query);
  28670. }
  28671. rest = rest.slice(0, qm);
  28672. } else if (parseQueryString) {
  28673. // no query string, but parseQueryString still requested
  28674. self.search = '';
  28675. self.query = {};
  28676. }
  28677. if (rest) self.pathname = rest;
  28678. if (slashedProtocol[lowerProto] &&
  28679. self.hostname && !self.pathname) {
  28680. self.pathname = '/';
  28681. }
  28682. //to support http.request
  28683. if (self.pathname || self.search) {
  28684. p = self.pathname || '';
  28685. var s = self.search || '';
  28686. self.path = p + s;
  28687. }
  28688. // finally, reconstruct the href based on what has been validated.
  28689. self.href = format$1(self);
  28690. return self;
  28691. }
  28692. // format a parsed object into a url string
  28693. function urlFormat(obj) {
  28694. // ensure it's an object, and not a string url.
  28695. // If it's an obj, this is a no-op.
  28696. // this way, you can call url_format() on strings
  28697. // to clean up potentially wonky urls.
  28698. if (isString$1(obj)) obj = parse$3({}, obj);
  28699. return format$1(obj);
  28700. }
  28701. function format$1(self) {
  28702. var auth = self.auth || '';
  28703. if (auth) {
  28704. auth = encodeURIComponent(auth);
  28705. auth = auth.replace(/%3A/i, ':');
  28706. auth += '@';
  28707. }
  28708. var protocol = self.protocol || '',
  28709. pathname = self.pathname || '',
  28710. hash = self.hash || '',
  28711. host = false,
  28712. query = '';
  28713. if (self.host) {
  28714. host = auth + self.host;
  28715. } else if (self.hostname) {
  28716. host = auth + (self.hostname.indexOf(':') === -1 ?
  28717. self.hostname :
  28718. '[' + this.hostname + ']');
  28719. if (self.port) {
  28720. host += ':' + self.port;
  28721. }
  28722. }
  28723. if (self.query &&
  28724. isObject$2(self.query) &&
  28725. Object.keys(self.query).length) {
  28726. query = stringify(self.query);
  28727. }
  28728. var search = self.search || (query && ('?' + query)) || '';
  28729. if (protocol && protocol.substr(-1) !== ':') protocol += ':';
  28730. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  28731. // unless they had them to begin with.
  28732. if (self.slashes ||
  28733. (!protocol || slashedProtocol[protocol]) && host !== false) {
  28734. host = '//' + (host || '');
  28735. if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  28736. } else if (!host) {
  28737. host = '';
  28738. }
  28739. if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  28740. if (search && search.charAt(0) !== '?') search = '?' + search;
  28741. pathname = pathname.replace(/[?#]/g, function(match) {
  28742. return encodeURIComponent(match);
  28743. });
  28744. search = search.replace('#', '%23');
  28745. return protocol + host + pathname + search + hash;
  28746. }
  28747. Url.prototype.format = function() {
  28748. return format$1(this);
  28749. };
  28750. function urlResolve(source, relative) {
  28751. return urlParse(source, false, true).resolve(relative);
  28752. }
  28753. Url.prototype.resolve = function(relative) {
  28754. return this.resolveObject(urlParse(relative, false, true)).format();
  28755. };
  28756. function urlResolveObject(source, relative) {
  28757. if (!source) return relative;
  28758. return urlParse(source, false, true).resolveObject(relative);
  28759. }
  28760. Url.prototype.resolveObject = function(relative) {
  28761. if (isString$1(relative)) {
  28762. var rel = new Url();
  28763. rel.parse(relative, false, true);
  28764. relative = rel;
  28765. }
  28766. var result = new Url();
  28767. var tkeys = Object.keys(this);
  28768. for (var tk = 0; tk < tkeys.length; tk++) {
  28769. var tkey = tkeys[tk];
  28770. result[tkey] = this[tkey];
  28771. }
  28772. // hash is always overridden, no matter what.
  28773. // even href="" will remove it.
  28774. result.hash = relative.hash;
  28775. // if the relative url is empty, then there's nothing left to do here.
  28776. if (relative.href === '') {
  28777. result.href = result.format();
  28778. return result;
  28779. }
  28780. // hrefs like //foo/bar always cut to the protocol.
  28781. if (relative.slashes && !relative.protocol) {
  28782. // take everything except the protocol from relative
  28783. var rkeys = Object.keys(relative);
  28784. for (var rk = 0; rk < rkeys.length; rk++) {
  28785. var rkey = rkeys[rk];
  28786. if (rkey !== 'protocol')
  28787. result[rkey] = relative[rkey];
  28788. }
  28789. //urlParse appends trailing / to urls like http://www.example.com
  28790. if (slashedProtocol[result.protocol] &&
  28791. result.hostname && !result.pathname) {
  28792. result.path = result.pathname = '/';
  28793. }
  28794. result.href = result.format();
  28795. return result;
  28796. }
  28797. var relPath;
  28798. if (relative.protocol && relative.protocol !== result.protocol) {
  28799. // if it's a known url protocol, then changing
  28800. // the protocol does weird things
  28801. // first, if it's not file:, then we MUST have a host,
  28802. // and if there was a path
  28803. // to begin with, then we MUST have a path.
  28804. // if it is file:, then the host is dropped,
  28805. // because that's known to be hostless.
  28806. // anything else is assumed to be absolute.
  28807. if (!slashedProtocol[relative.protocol]) {
  28808. var keys = Object.keys(relative);
  28809. for (var v = 0; v < keys.length; v++) {
  28810. var k = keys[v];
  28811. result[k] = relative[k];
  28812. }
  28813. result.href = result.format();
  28814. return result;
  28815. }
  28816. result.protocol = relative.protocol;
  28817. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  28818. relPath = (relative.pathname || '').split('/');
  28819. while (relPath.length && !(relative.host = relPath.shift()));
  28820. if (!relative.host) relative.host = '';
  28821. if (!relative.hostname) relative.hostname = '';
  28822. if (relPath[0] !== '') relPath.unshift('');
  28823. if (relPath.length < 2) relPath.unshift('');
  28824. result.pathname = relPath.join('/');
  28825. } else {
  28826. result.pathname = relative.pathname;
  28827. }
  28828. result.search = relative.search;
  28829. result.query = relative.query;
  28830. result.host = relative.host || '';
  28831. result.auth = relative.auth;
  28832. result.hostname = relative.hostname || relative.host;
  28833. result.port = relative.port;
  28834. // to support http.request
  28835. if (result.pathname || result.search) {
  28836. var p = result.pathname || '';
  28837. var s = result.search || '';
  28838. result.path = p + s;
  28839. }
  28840. result.slashes = result.slashes || relative.slashes;
  28841. result.href = result.format();
  28842. return result;
  28843. }
  28844. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  28845. isRelAbs = (
  28846. relative.host ||
  28847. relative.pathname && relative.pathname.charAt(0) === '/'
  28848. ),
  28849. mustEndAbs = (isRelAbs || isSourceAbs ||
  28850. (result.host && relative.pathname)),
  28851. removeAllDots = mustEndAbs,
  28852. srcPath = result.pathname && result.pathname.split('/') || [],
  28853. psychotic = result.protocol && !slashedProtocol[result.protocol];
  28854. relPath = relative.pathname && relative.pathname.split('/') || [];
  28855. // if the url is a non-slashed url, then relative
  28856. // links like ../.. should be able
  28857. // to crawl up to the hostname, as well. This is strange.
  28858. // result.protocol has already been set by now.
  28859. // Later on, put the first path part into the host field.
  28860. if (psychotic) {
  28861. result.hostname = '';
  28862. result.port = null;
  28863. if (result.host) {
  28864. if (srcPath[0] === '') srcPath[0] = result.host;
  28865. else srcPath.unshift(result.host);
  28866. }
  28867. result.host = '';
  28868. if (relative.protocol) {
  28869. relative.hostname = null;
  28870. relative.port = null;
  28871. if (relative.host) {
  28872. if (relPath[0] === '') relPath[0] = relative.host;
  28873. else relPath.unshift(relative.host);
  28874. }
  28875. relative.host = null;
  28876. }
  28877. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  28878. }
  28879. var authInHost;
  28880. if (isRelAbs) {
  28881. // it's absolute.
  28882. result.host = (relative.host || relative.host === '') ?
  28883. relative.host : result.host;
  28884. result.hostname = (relative.hostname || relative.hostname === '') ?
  28885. relative.hostname : result.hostname;
  28886. result.search = relative.search;
  28887. result.query = relative.query;
  28888. srcPath = relPath;
  28889. // fall through to the dot-handling below.
  28890. } else if (relPath.length) {
  28891. // it's relative
  28892. // throw away the existing file, and take the new path instead.
  28893. if (!srcPath) srcPath = [];
  28894. srcPath.pop();
  28895. srcPath = srcPath.concat(relPath);
  28896. result.search = relative.search;
  28897. result.query = relative.query;
  28898. } else if (!isNullOrUndefined(relative.search)) {
  28899. // just pull out the search.
  28900. // like href='?foo'.
  28901. // Put this after the other two cases because it simplifies the booleans
  28902. if (psychotic) {
  28903. result.hostname = result.host = srcPath.shift();
  28904. //occationaly the auth can get stuck only in host
  28905. //this especially happens in cases like
  28906. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  28907. authInHost = result.host && result.host.indexOf('@') > 0 ?
  28908. result.host.split('@') : false;
  28909. if (authInHost) {
  28910. result.auth = authInHost.shift();
  28911. result.host = result.hostname = authInHost.shift();
  28912. }
  28913. }
  28914. result.search = relative.search;
  28915. result.query = relative.query;
  28916. //to support http.request
  28917. if (!isNull(result.pathname) || !isNull(result.search)) {
  28918. result.path = (result.pathname ? result.pathname : '') +
  28919. (result.search ? result.search : '');
  28920. }
  28921. result.href = result.format();
  28922. return result;
  28923. }
  28924. if (!srcPath.length) {
  28925. // no path at all. easy.
  28926. // we've already handled the other stuff above.
  28927. result.pathname = null;
  28928. //to support http.request
  28929. if (result.search) {
  28930. result.path = '/' + result.search;
  28931. } else {
  28932. result.path = null;
  28933. }
  28934. result.href = result.format();
  28935. return result;
  28936. }
  28937. // if a url ENDs in . or .., then it must get a trailing slash.
  28938. // however, if it ends in anything else non-slashy,
  28939. // then it must NOT get a trailing slash.
  28940. var last = srcPath.slice(-1)[0];
  28941. var hasTrailingSlash = (
  28942. (result.host || relative.host || srcPath.length > 1) &&
  28943. (last === '.' || last === '..') || last === '');
  28944. // strip single dots, resolve double dots to parent dir
  28945. // if the path tries to go above the root, `up` ends up > 0
  28946. var up = 0;
  28947. for (var i = srcPath.length; i >= 0; i--) {
  28948. last = srcPath[i];
  28949. if (last === '.') {
  28950. srcPath.splice(i, 1);
  28951. } else if (last === '..') {
  28952. srcPath.splice(i, 1);
  28953. up++;
  28954. } else if (up) {
  28955. srcPath.splice(i, 1);
  28956. up--;
  28957. }
  28958. }
  28959. // if the path is allowed to go above the root, restore leading ..s
  28960. if (!mustEndAbs && !removeAllDots) {
  28961. for (; up--; up) {
  28962. srcPath.unshift('..');
  28963. }
  28964. }
  28965. if (mustEndAbs && srcPath[0] !== '' &&
  28966. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  28967. srcPath.unshift('');
  28968. }
  28969. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  28970. srcPath.push('');
  28971. }
  28972. var isAbsolute = srcPath[0] === '' ||
  28973. (srcPath[0] && srcPath[0].charAt(0) === '/');
  28974. // put the host back
  28975. if (psychotic) {
  28976. result.hostname = result.host = isAbsolute ? '' :
  28977. srcPath.length ? srcPath.shift() : '';
  28978. //occationaly the auth can get stuck only in host
  28979. //this especially happens in cases like
  28980. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  28981. authInHost = result.host && result.host.indexOf('@') > 0 ?
  28982. result.host.split('@') : false;
  28983. if (authInHost) {
  28984. result.auth = authInHost.shift();
  28985. result.host = result.hostname = authInHost.shift();
  28986. }
  28987. }
  28988. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  28989. if (mustEndAbs && !isAbsolute) {
  28990. srcPath.unshift('');
  28991. }
  28992. if (!srcPath.length) {
  28993. result.pathname = null;
  28994. result.path = null;
  28995. } else {
  28996. result.pathname = srcPath.join('/');
  28997. }
  28998. //to support request.http
  28999. if (!isNull(result.pathname) || !isNull(result.search)) {
  29000. result.path = (result.pathname ? result.pathname : '') +
  29001. (result.search ? result.search : '');
  29002. }
  29003. result.auth = relative.auth || result.auth;
  29004. result.slashes = result.slashes || relative.slashes;
  29005. result.href = result.format();
  29006. return result;
  29007. };
  29008. Url.prototype.parseHost = function() {
  29009. return parseHost(this);
  29010. };
  29011. function parseHost(self) {
  29012. var host = self.host;
  29013. var port = portPattern.exec(host);
  29014. if (port) {
  29015. port = port[0];
  29016. if (port !== ':') {
  29017. self.port = port.substr(1);
  29018. }
  29019. host = host.substr(0, host.length - port.length);
  29020. }
  29021. if (host) self.hostname = host;
  29022. }
  29023. var _polyfillNode_url$1 = /*#__PURE__*/Object.freeze({
  29024. __proto__: null,
  29025. parse: urlParse,
  29026. resolve: urlResolve,
  29027. resolveObject: urlResolveObject,
  29028. format: urlFormat,
  29029. 'default': _polyfillNode_url,
  29030. Url: Url
  29031. });
  29032. function isRelativeUrl(url) {
  29033. const firstChar = url.charAt(0);
  29034. return firstChar === '.' || firstChar === '~' || firstChar === '@';
  29035. }
  29036. const externalRE = /^(https?:)?\/\//;
  29037. function isExternalUrl(url) {
  29038. return externalRE.test(url);
  29039. }
  29040. const dataUrlRE = /^\s*data:/i;
  29041. function isDataUrl(url) {
  29042. return dataUrlRE.test(url);
  29043. }
  29044. /**
  29045. * Parses string url into URL object.
  29046. */
  29047. function parseUrl(url) {
  29048. const firstChar = url.charAt(0);
  29049. if (firstChar === '~') {
  29050. const secondChar = url.charAt(1);
  29051. url = url.slice(secondChar === '/' ? 2 : 1);
  29052. }
  29053. return parseUriParts(url);
  29054. }
  29055. /**
  29056. * vuejs/component-compiler-utils#22 Support uri fragment in transformed require
  29057. * @param urlString an url as a string
  29058. */
  29059. function parseUriParts(urlString) {
  29060. // A TypeError is thrown if urlString is not a string
  29061. // @see https://nodejs.org/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost
  29062. return urlParse(isString(urlString) ? urlString : '', false, true);
  29063. }
  29064. const defaultAssetUrlOptions = {
  29065. base: null,
  29066. includeAbsolute: false,
  29067. tags: {
  29068. video: ['src', 'poster'],
  29069. source: ['src'],
  29070. img: ['src'],
  29071. image: ['xlink:href', 'href'],
  29072. use: ['xlink:href', 'href']
  29073. }
  29074. };
  29075. const normalizeOptions = (options) => {
  29076. if (Object.keys(options).some(key => isArray(options[key]))) {
  29077. // legacy option format which directly passes in tags config
  29078. return Object.assign(Object.assign({}, defaultAssetUrlOptions), { tags: options });
  29079. }
  29080. return Object.assign(Object.assign({}, defaultAssetUrlOptions), options);
  29081. };
  29082. const createAssetUrlTransformWithOptions = (options) => {
  29083. return (node, context) => transformAssetUrl(node, context, options);
  29084. };
  29085. /**
  29086. * A `@vue/compiler-core` plugin that transforms relative asset urls into
  29087. * either imports or absolute urls.
  29088. *
  29089. * ``` js
  29090. * // Before
  29091. * createVNode('img', { src: './logo.png' })
  29092. *
  29093. * // After
  29094. * import _imports_0 from './logo.png'
  29095. * createVNode('img', { src: _imports_0 })
  29096. * ```
  29097. */
  29098. const transformAssetUrl = (node, context, options = defaultAssetUrlOptions) => {
  29099. if (node.type === 1 /* ELEMENT */) {
  29100. if (!node.props.length) {
  29101. return;
  29102. }
  29103. const tags = options.tags || defaultAssetUrlOptions.tags;
  29104. const attrs = tags[node.tag];
  29105. const wildCardAttrs = tags['*'];
  29106. if (!attrs && !wildCardAttrs) {
  29107. return;
  29108. }
  29109. const assetAttrs = (attrs || []).concat(wildCardAttrs || []);
  29110. node.props.forEach((attr, index) => {
  29111. if (attr.type !== 6 /* ATTRIBUTE */ ||
  29112. !assetAttrs.includes(attr.name) ||
  29113. !attr.value ||
  29114. isExternalUrl(attr.value.content) ||
  29115. isDataUrl(attr.value.content) ||
  29116. attr.value.content[0] === '#' ||
  29117. (!options.includeAbsolute && !isRelativeUrl(attr.value.content))) {
  29118. return;
  29119. }
  29120. const url = parseUrl(attr.value.content);
  29121. if (options.base && attr.value.content[0] === '.') {
  29122. // explicit base - directly rewrite relative urls into absolute url
  29123. // to avoid generating extra imports
  29124. // Allow for full hostnames provided in options.base
  29125. const base = parseUrl(options.base);
  29126. const protocol = base.protocol || '';
  29127. const host = base.host ? protocol + '//' + base.host : '';
  29128. const basePath = base.path || '/';
  29129. // when packaged in the browser, path will be using the posix-
  29130. // only version provided by rollup-plugin-node-builtins.
  29131. attr.value.content =
  29132. host +
  29133. (path.posix || path).join(basePath, url.path + (url.hash || ''));
  29134. return;
  29135. }
  29136. // otherwise, transform the url into an import.
  29137. // this assumes a bundler will resolve the import into the correct
  29138. // absolute url (e.g. webpack file-loader)
  29139. const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context);
  29140. node.props[index] = {
  29141. type: 7 /* DIRECTIVE */,
  29142. name: 'bind',
  29143. arg: createSimpleExpression(attr.name, true, attr.loc),
  29144. exp,
  29145. modifiers: [],
  29146. loc: attr.loc
  29147. };
  29148. });
  29149. }
  29150. };
  29151. function getImportsExpressionExp(path, hash, loc, context) {
  29152. if (path) {
  29153. let name;
  29154. let exp;
  29155. const existingIndex = context.imports.findIndex(i => i.path === path);
  29156. if (existingIndex > -1) {
  29157. name = `_imports_${existingIndex}`;
  29158. exp = context.imports[existingIndex].exp;
  29159. }
  29160. else {
  29161. name = `_imports_${context.imports.length}`;
  29162. exp = createSimpleExpression(name, false, loc, 3 /* CAN_STRINGIFY */);
  29163. context.imports.push({ exp, path });
  29164. }
  29165. if (!hash) {
  29166. return exp;
  29167. }
  29168. const hashExp = `${name} + '${hash}'`;
  29169. const existingHoistIndex = context.hoists.findIndex(h => {
  29170. return (h &&
  29171. h.type === 4 /* SIMPLE_EXPRESSION */ &&
  29172. !h.isStatic &&
  29173. h.content === hashExp);
  29174. });
  29175. if (existingHoistIndex > -1) {
  29176. return createSimpleExpression(`_hoisted_${existingHoistIndex + 1}`, false, loc, 3 /* CAN_STRINGIFY */);
  29177. }
  29178. return context.hoist(createSimpleExpression(hashExp, false, loc, 3 /* CAN_STRINGIFY */));
  29179. }
  29180. else {
  29181. return createSimpleExpression(`''`, false, loc, 3 /* CAN_STRINGIFY */);
  29182. }
  29183. }
  29184. const srcsetTags = ['img', 'source'];
  29185. // http://w3c.github.io/html/semantics-embedded-content.html#ref-for-image-candidate-string-5
  29186. const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
  29187. const createSrcsetTransformWithOptions = (options) => {
  29188. return (node, context) => transformSrcset(node, context, options);
  29189. };
  29190. const transformSrcset = (node, context, options = defaultAssetUrlOptions) => {
  29191. if (node.type === 1 /* ELEMENT */) {
  29192. if (srcsetTags.includes(node.tag) && node.props.length) {
  29193. node.props.forEach((attr, index) => {
  29194. if (attr.name === 'srcset' && attr.type === 6 /* ATTRIBUTE */) {
  29195. if (!attr.value)
  29196. return;
  29197. const value = attr.value.content;
  29198. if (!value)
  29199. return;
  29200. const imageCandidates = value.split(',').map(s => {
  29201. // The attribute value arrives here with all whitespace, except
  29202. // normal spaces, represented by escape sequences
  29203. const [url, descriptor] = s
  29204. .replace(escapedSpaceCharacters, ' ')
  29205. .trim()
  29206. .split(' ', 2);
  29207. return { url, descriptor };
  29208. });
  29209. // data urls contains comma after the encoding so we need to re-merge
  29210. // them
  29211. for (let i = 0; i < imageCandidates.length; i++) {
  29212. const { url } = imageCandidates[i];
  29213. if (isDataUrl(url)) {
  29214. imageCandidates[i + 1].url =
  29215. url + ',' + imageCandidates[i + 1].url;
  29216. imageCandidates.splice(i, 1);
  29217. }
  29218. }
  29219. const hasQualifiedUrl = imageCandidates.some(({ url }) => {
  29220. return (!isExternalUrl(url) &&
  29221. !isDataUrl(url) &&
  29222. (options.includeAbsolute || isRelativeUrl(url)));
  29223. });
  29224. // When srcset does not contain any qualified URLs, skip transforming
  29225. if (!hasQualifiedUrl) {
  29226. return;
  29227. }
  29228. if (options.base) {
  29229. const base = options.base;
  29230. const set = [];
  29231. imageCandidates.forEach(({ url, descriptor }) => {
  29232. descriptor = descriptor ? ` ${descriptor}` : ``;
  29233. if (isRelativeUrl(url)) {
  29234. set.push((path.posix || path).join(base, url) + descriptor);
  29235. }
  29236. else {
  29237. set.push(url + descriptor);
  29238. }
  29239. });
  29240. attr.value.content = set.join(', ');
  29241. return;
  29242. }
  29243. const compoundExpression = createCompoundExpression([], attr.loc);
  29244. imageCandidates.forEach(({ url, descriptor }, index) => {
  29245. if (!isExternalUrl(url) &&
  29246. !isDataUrl(url) &&
  29247. (options.includeAbsolute || isRelativeUrl(url))) {
  29248. const { path } = parseUrl(url);
  29249. let exp;
  29250. if (path) {
  29251. const existingImportsIndex = context.imports.findIndex(i => i.path === path);
  29252. if (existingImportsIndex > -1) {
  29253. exp = createSimpleExpression(`_imports_${existingImportsIndex}`, false, attr.loc, 3 /* CAN_STRINGIFY */);
  29254. }
  29255. else {
  29256. exp = createSimpleExpression(`_imports_${context.imports.length}`, false, attr.loc, 3 /* CAN_STRINGIFY */);
  29257. context.imports.push({ exp, path });
  29258. }
  29259. compoundExpression.children.push(exp);
  29260. }
  29261. }
  29262. else {
  29263. const exp = createSimpleExpression(`"${url}"`, false, attr.loc, 3 /* CAN_STRINGIFY */);
  29264. compoundExpression.children.push(exp);
  29265. }
  29266. const isNotLast = imageCandidates.length - 1 > index;
  29267. if (descriptor && isNotLast) {
  29268. compoundExpression.children.push(` + ' ${descriptor}, ' + `);
  29269. }
  29270. else if (descriptor) {
  29271. compoundExpression.children.push(` + ' ${descriptor}'`);
  29272. }
  29273. else if (isNotLast) {
  29274. compoundExpression.children.push(` + ', ' + `);
  29275. }
  29276. });
  29277. const hoisted = context.hoist(compoundExpression);
  29278. hoisted.constType = 3 /* CAN_STRINGIFY */;
  29279. node.props[index] = {
  29280. type: 7 /* DIRECTIVE */,
  29281. name: 'bind',
  29282. arg: createSimpleExpression('srcset', true, attr.loc),
  29283. exp: hoisted,
  29284. modifiers: [],
  29285. loc: attr.loc
  29286. };
  29287. }
  29288. });
  29289. }
  29290. }
  29291. };
  29292. const SSR_INTERPOLATE = Symbol(`ssrInterpolate`);
  29293. const SSR_RENDER_VNODE = Symbol(`ssrRenderVNode`);
  29294. const SSR_RENDER_COMPONENT = Symbol(`ssrRenderComponent`);
  29295. const SSR_RENDER_SLOT = Symbol(`ssrRenderSlot`);
  29296. const SSR_RENDER_CLASS = Symbol(`ssrRenderClass`);
  29297. const SSR_RENDER_STYLE = Symbol(`ssrRenderStyle`);
  29298. const SSR_RENDER_ATTRS = Symbol(`ssrRenderAttrs`);
  29299. const SSR_RENDER_ATTR = Symbol(`ssrRenderAttr`);
  29300. const SSR_RENDER_DYNAMIC_ATTR = Symbol(`ssrRenderDynamicAttr`);
  29301. const SSR_RENDER_LIST = Symbol(`ssrRenderList`);
  29302. const SSR_INCLUDE_BOOLEAN_ATTR = Symbol(`ssrIncludeBooleanAttr`);
  29303. const SSR_LOOSE_EQUAL = Symbol(`ssrLooseEqual`);
  29304. const SSR_LOOSE_CONTAIN = Symbol(`ssrLooseContain`);
  29305. const SSR_RENDER_DYNAMIC_MODEL = Symbol(`ssrRenderDynamicModel`);
  29306. const SSR_GET_DYNAMIC_MODEL_PROPS = Symbol(`ssrGetDynamicModelProps`);
  29307. const SSR_RENDER_TELEPORT = Symbol(`ssrRenderTeleport`);
  29308. const SSR_RENDER_SUSPENSE = Symbol(`ssrRenderSuspense`);
  29309. const ssrHelpers = {
  29310. [SSR_INTERPOLATE]: `ssrInterpolate`,
  29311. [SSR_RENDER_VNODE]: `ssrRenderVNode`,
  29312. [SSR_RENDER_COMPONENT]: `ssrRenderComponent`,
  29313. [SSR_RENDER_SLOT]: `ssrRenderSlot`,
  29314. [SSR_RENDER_CLASS]: `ssrRenderClass`,
  29315. [SSR_RENDER_STYLE]: `ssrRenderStyle`,
  29316. [SSR_RENDER_ATTRS]: `ssrRenderAttrs`,
  29317. [SSR_RENDER_ATTR]: `ssrRenderAttr`,
  29318. [SSR_RENDER_DYNAMIC_ATTR]: `ssrRenderDynamicAttr`,
  29319. [SSR_RENDER_LIST]: `ssrRenderList`,
  29320. [SSR_INCLUDE_BOOLEAN_ATTR]: `ssrIncludeBooleanAttr`,
  29321. [SSR_LOOSE_EQUAL]: `ssrLooseEqual`,
  29322. [SSR_LOOSE_CONTAIN]: `ssrLooseContain`,
  29323. [SSR_RENDER_DYNAMIC_MODEL]: `ssrRenderDynamicModel`,
  29324. [SSR_GET_DYNAMIC_MODEL_PROPS]: `ssrGetDynamicModelProps`,
  29325. [SSR_RENDER_TELEPORT]: `ssrRenderTeleport`,
  29326. [SSR_RENDER_SUSPENSE]: `ssrRenderSuspense`
  29327. };
  29328. // Note: these are helpers imported from @vue/server-renderer
  29329. // make sure the names match!
  29330. registerRuntimeHelpers(ssrHelpers);
  29331. // Plugin for the first transform pass, which simply constructs the AST node
  29332. const ssrTransformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, processIf);
  29333. // This is called during the 2nd transform pass to construct the SSR-specific
  29334. // codegen nodes.
  29335. function ssrProcessIf(node, context, disableNestedFragments = false) {
  29336. const [rootBranch] = node.branches;
  29337. const ifStatement = createIfStatement(rootBranch.condition, processIfBranch(rootBranch, context, disableNestedFragments));
  29338. context.pushStatement(ifStatement);
  29339. let currentIf = ifStatement;
  29340. for (let i = 1; i < node.branches.length; i++) {
  29341. const branch = node.branches[i];
  29342. const branchBlockStatement = processIfBranch(branch, context, disableNestedFragments);
  29343. if (branch.condition) {
  29344. // else-if
  29345. currentIf = currentIf.alternate = createIfStatement(branch.condition, branchBlockStatement);
  29346. }
  29347. else {
  29348. // else
  29349. currentIf.alternate = branchBlockStatement;
  29350. }
  29351. }
  29352. if (!currentIf.alternate) {
  29353. currentIf.alternate = createBlockStatement([
  29354. createCallExpression(`_push`, ['`<!---->`'])
  29355. ]);
  29356. }
  29357. }
  29358. function processIfBranch(branch, context, disableNestedFragments = false) {
  29359. const { children } = branch;
  29360. const needFragmentWrapper = !disableNestedFragments &&
  29361. (children.length !== 1 || children[0].type !== 1 /* ELEMENT */) &&
  29362. // optimize away nested fragments when the only child is a ForNode
  29363. !(children.length === 1 && children[0].type === 11 /* FOR */);
  29364. return processChildrenAsStatement(children, context, needFragmentWrapper);
  29365. }
  29366. // Plugin for the first transform pass, which simply constructs the AST node
  29367. const ssrTransformFor = createStructuralDirectiveTransform('for', processFor);
  29368. // This is called during the 2nd transform pass to construct the SSR-specific
  29369. // codegen nodes.
  29370. function ssrProcessFor(node, context, disableNestedFragments = false) {
  29371. const needFragmentWrapper = !disableNestedFragments &&
  29372. (node.children.length !== 1 || node.children[0].type !== 1 /* ELEMENT */);
  29373. const renderLoop = createFunctionExpression(createForLoopParams(node.parseResult));
  29374. renderLoop.body = processChildrenAsStatement(node.children, context, needFragmentWrapper);
  29375. // v-for always renders a fragment unless explicitly disabled
  29376. if (!disableNestedFragments) {
  29377. context.pushStringPart(`<!--[-->`);
  29378. }
  29379. context.pushStatement(createCallExpression(context.helper(SSR_RENDER_LIST), [
  29380. node.source,
  29381. renderLoop
  29382. ]));
  29383. if (!disableNestedFragments) {
  29384. context.pushStringPart(`<!--]-->`);
  29385. }
  29386. }
  29387. const ssrTransformSlotOutlet = (node, context) => {
  29388. if (isSlotOutlet(node)) {
  29389. const { slotName, slotProps } = processSlotOutlet(node, context);
  29390. const args = [
  29391. `_ctx.$slots`,
  29392. slotName,
  29393. slotProps || `{}`,
  29394. // fallback content placeholder. will be replaced in the process phase
  29395. `null`,
  29396. `_push`,
  29397. `_parent`
  29398. ];
  29399. // inject slot scope id if current template uses :slotted
  29400. if (context.scopeId && context.slotted !== false) {
  29401. args.push(`"${context.scopeId}-s"`);
  29402. }
  29403. node.ssrCodegenNode = createCallExpression(context.helper(SSR_RENDER_SLOT), args);
  29404. }
  29405. };
  29406. function ssrProcessSlotOutlet(node, context) {
  29407. const renderCall = node.ssrCodegenNode;
  29408. // has fallback content
  29409. if (node.children.length) {
  29410. const fallbackRenderFn = createFunctionExpression([]);
  29411. fallbackRenderFn.body = processChildrenAsStatement(node.children, context);
  29412. // _renderSlot(slots, name, props, fallback, ...)
  29413. renderCall.arguments[3] = fallbackRenderFn;
  29414. }
  29415. // Forwarded <slot/>. Merge slot scope ids
  29416. if (context.withSlotScopeId) {
  29417. const slotScopeId = renderCall.arguments[6];
  29418. renderCall.arguments[6] = slotScopeId
  29419. ? `${slotScopeId} + _scopeId`
  29420. : `_scopeId`;
  29421. }
  29422. context.pushStatement(node.ssrCodegenNode);
  29423. }
  29424. function createSSRCompilerError(code, loc) {
  29425. return createCompilerError(code, loc, SSRErrorMessages);
  29426. }
  29427. const SSRErrorMessages = {
  29428. [61 /* X_SSR_CUSTOM_DIRECTIVE_NO_TRANSFORM */]: `Custom directive is missing corresponding SSR transform and will be ignored.`,
  29429. [62 /* X_SSR_UNSAFE_ATTR_NAME */]: `Unsafe attribute name for SSR.`,
  29430. [63 /* X_SSR_NO_TELEPORT_TARGET */]: `Missing the 'to' prop on teleport element.`,
  29431. [64 /* X_SSR_INVALID_AST_NODE */]: `Invalid AST node during SSR transform.`
  29432. };
  29433. // Note: this is a 2nd-pass codegen transform.
  29434. function ssrProcessTeleport(node, context) {
  29435. const targetProp = findProp(node, 'to');
  29436. if (!targetProp) {
  29437. context.onError(createSSRCompilerError(63 /* X_SSR_NO_TELEPORT_TARGET */, node.loc));
  29438. return;
  29439. }
  29440. let target;
  29441. if (targetProp.type === 6 /* ATTRIBUTE */) {
  29442. target =
  29443. targetProp.value && createSimpleExpression(targetProp.value.content, true);
  29444. }
  29445. else {
  29446. target = targetProp.exp;
  29447. }
  29448. if (!target) {
  29449. context.onError(createSSRCompilerError(63 /* X_SSR_NO_TELEPORT_TARGET */, targetProp.loc));
  29450. return;
  29451. }
  29452. const disabledProp = findProp(node, 'disabled', false, true /* allow empty */);
  29453. const disabled = disabledProp
  29454. ? disabledProp.type === 6 /* ATTRIBUTE */
  29455. ? `true`
  29456. : disabledProp.exp || `false`
  29457. : `false`;
  29458. const contentRenderFn = createFunctionExpression([`_push`], undefined, // Body is added later
  29459. true, // newline
  29460. false, // isSlot
  29461. node.loc);
  29462. contentRenderFn.body = processChildrenAsStatement(node.children, context);
  29463. context.pushStatement(createCallExpression(context.helper(SSR_RENDER_TELEPORT), [
  29464. `_push`,
  29465. contentRenderFn,
  29466. target,
  29467. disabled,
  29468. `_parent`
  29469. ]));
  29470. }
  29471. const wipMap = new WeakMap();
  29472. // phase 1
  29473. function ssrTransformSuspense(node, context) {
  29474. return () => {
  29475. if (node.children.length) {
  29476. const wipEntry = {
  29477. slotsExp: null,
  29478. wipSlots: []
  29479. };
  29480. wipMap.set(node, wipEntry);
  29481. wipEntry.slotsExp = buildSlots(node, context, (_props, children, loc) => {
  29482. const fn = createFunctionExpression([], undefined, // no return, assign body later
  29483. true, // newline
  29484. false, // suspense slots are not treated as normal slots
  29485. loc);
  29486. wipEntry.wipSlots.push({
  29487. fn,
  29488. children
  29489. });
  29490. return fn;
  29491. }).slots;
  29492. }
  29493. };
  29494. }
  29495. // phase 2
  29496. function ssrProcessSuspense(node, context) {
  29497. // complete wip slots with ssr code
  29498. const wipEntry = wipMap.get(node);
  29499. if (!wipEntry) {
  29500. return;
  29501. }
  29502. const { slotsExp, wipSlots } = wipEntry;
  29503. for (let i = 0; i < wipSlots.length; i++) {
  29504. const { fn, children } = wipSlots[i];
  29505. fn.body = processChildrenAsStatement(children, context);
  29506. }
  29507. // _push(ssrRenderSuspense(slots))
  29508. context.pushStatement(createCallExpression(context.helper(SSR_RENDER_SUSPENSE), [
  29509. `_push`,
  29510. slotsExp
  29511. ]));
  29512. }
  29513. function ssrProcessTransitionGroup(node, context) {
  29514. const tag = findProp(node, 'tag');
  29515. if (tag) {
  29516. if (tag.type === 7 /* DIRECTIVE */) {
  29517. // dynamic :tag
  29518. context.pushStringPart(`<`);
  29519. context.pushStringPart(tag.exp);
  29520. context.pushStringPart(`>`);
  29521. processChildren(node.children, context, false,
  29522. /**
  29523. * TransitionGroup has the special runtime behavior of flattening and
  29524. * concatenating all children into a single fragment (in order for them to
  29525. * be patched using the same key map) so we need to account for that here
  29526. * by disabling nested fragment wrappers from being generated.
  29527. */
  29528. true);
  29529. context.pushStringPart(`</`);
  29530. context.pushStringPart(tag.exp);
  29531. context.pushStringPart(`>`);
  29532. }
  29533. else {
  29534. // static tag
  29535. context.pushStringPart(`<${tag.value.content}>`);
  29536. processChildren(node.children, context, false, true);
  29537. context.pushStringPart(`</${tag.value.content}>`);
  29538. }
  29539. }
  29540. else {
  29541. // fragment
  29542. processChildren(node.children, context, true, true);
  29543. }
  29544. }
  29545. // We need to construct the slot functions in the 1st pass to ensure proper
  29546. // scope tracking, but the children of each slot cannot be processed until
  29547. // the 2nd pass, so we store the WIP slot functions in a weakmap during the 1st
  29548. // pass and complete them in the 2nd pass.
  29549. const wipMap$1 = new WeakMap();
  29550. const componentTypeMap = new WeakMap();
  29551. // ssr component transform is done in two phases:
  29552. // In phase 1. we use `buildSlot` to analyze the children of the component into
  29553. // WIP slot functions (it must be done in phase 1 because `buildSlot` relies on
  29554. // the core transform context).
  29555. // In phase 2. we convert the WIP slots from phase 1 into ssr-specific codegen
  29556. // nodes.
  29557. const ssrTransformComponent = (node, context) => {
  29558. if (node.type !== 1 /* ELEMENT */ ||
  29559. node.tagType !== 1 /* COMPONENT */) {
  29560. return;
  29561. }
  29562. const component = resolveComponentType(node, context, true /* ssr */);
  29563. componentTypeMap.set(node, component);
  29564. if (isSymbol(component)) {
  29565. if (component === SUSPENSE) {
  29566. return ssrTransformSuspense(node, context);
  29567. }
  29568. return; // built-in component: fallthrough
  29569. }
  29570. // Build the fallback vnode-based branch for the component's slots.
  29571. // We need to clone the node into a fresh copy and use the buildSlots' logic
  29572. // to get access to the children of each slot. We then compile them with
  29573. // a child transform pipeline using vnode-based transforms (instead of ssr-
  29574. // based ones), and save the result branch (a ReturnStatement) in an array.
  29575. // The branch is retrieved when processing slots again in ssr mode.
  29576. const vnodeBranches = [];
  29577. const clonedNode = clone(node);
  29578. return function ssrPostTransformComponent() {
  29579. // Using the cloned node, build the normal VNode-based branches (for
  29580. // fallback in case the child is render-fn based). Store them in an array
  29581. // for later use.
  29582. if (clonedNode.children.length) {
  29583. buildSlots(clonedNode, context, (props, children) => {
  29584. vnodeBranches.push(createVNodeSlotBranch(props, children, context));
  29585. return createFunctionExpression(undefined);
  29586. });
  29587. }
  29588. const props = node.props.length > 0
  29589. ? // note we are not passing ssr: true here because for components, v-on
  29590. // handlers should still be passed
  29591. buildProps(node, context).props || `null`
  29592. : `null`;
  29593. const wipEntries = [];
  29594. wipMap$1.set(node, wipEntries);
  29595. const buildSSRSlotFn = (props, children, loc) => {
  29596. const fn = createFunctionExpression([props || `_`, `_push`, `_parent`, `_scopeId`], undefined, // no return, assign body later
  29597. true, // newline
  29598. true, // isSlot
  29599. loc);
  29600. wipEntries.push({
  29601. fn,
  29602. children,
  29603. // also collect the corresponding vnode branch built earlier
  29604. vnodeBranch: vnodeBranches[wipEntries.length]
  29605. });
  29606. return fn;
  29607. };
  29608. const slots = node.children.length
  29609. ? buildSlots(node, context, buildSSRSlotFn).slots
  29610. : `null`;
  29611. if (typeof component !== 'string') {
  29612. // dynamic component that resolved to a `resolveDynamicComponent` call
  29613. // expression - since the resolved result may be a plain element (string)
  29614. // or a VNode, handle it with `renderVNode`.
  29615. node.ssrCodegenNode = createCallExpression(context.helper(SSR_RENDER_VNODE), [
  29616. `_push`,
  29617. createCallExpression(context.helper(CREATE_VNODE), [
  29618. component,
  29619. props,
  29620. slots
  29621. ]),
  29622. `_parent`
  29623. ]);
  29624. }
  29625. else {
  29626. node.ssrCodegenNode = createCallExpression(context.helper(SSR_RENDER_COMPONENT), [component, props, slots, `_parent`]);
  29627. }
  29628. };
  29629. };
  29630. function ssrProcessComponent(node, context) {
  29631. const component = componentTypeMap.get(node);
  29632. if (!node.ssrCodegenNode) {
  29633. // this is a built-in component that fell-through.
  29634. if (component === TELEPORT) {
  29635. return ssrProcessTeleport(node, context);
  29636. }
  29637. else if (component === SUSPENSE) {
  29638. return ssrProcessSuspense(node, context);
  29639. }
  29640. else if (component === TRANSITION_GROUP) {
  29641. return ssrProcessTransitionGroup(node, context);
  29642. }
  29643. else {
  29644. // real fall-through: Transition / KeepAlive
  29645. // just render its children.
  29646. processChildren(node.children, context);
  29647. }
  29648. }
  29649. else {
  29650. // finish up slot function expressions from the 1st pass.
  29651. const wipEntries = wipMap$1.get(node) || [];
  29652. for (let i = 0; i < wipEntries.length; i++) {
  29653. const { fn, children, vnodeBranch } = wipEntries[i];
  29654. // For each slot, we generate two branches: one SSR-optimized branch and
  29655. // one normal vnode-based branch. The branches are taken based on the
  29656. // presence of the 2nd `_push` argument (which is only present if the slot
  29657. // is called by `_ssrRenderSlot`.
  29658. fn.body = createIfStatement(createSimpleExpression(`_push`, false), processChildrenAsStatement(children, context, false, true /* withSlotScopeId */), vnodeBranch);
  29659. }
  29660. // component is inside a slot, inherit slot scope Id
  29661. if (context.withSlotScopeId) {
  29662. node.ssrCodegenNode.arguments.push(`_scopeId`);
  29663. }
  29664. if (typeof component === 'string') {
  29665. // static component
  29666. context.pushStatement(createCallExpression(`_push`, [node.ssrCodegenNode]));
  29667. }
  29668. else {
  29669. // dynamic component (`resolveDynamicComponent` call)
  29670. // the codegen node is a `renderVNode` call
  29671. context.pushStatement(node.ssrCodegenNode);
  29672. }
  29673. }
  29674. }
  29675. const rawOptionsMap = new WeakMap();
  29676. const [baseNodeTransforms, baseDirectiveTransforms] = getBaseTransformPreset(true);
  29677. const vnodeNodeTransforms = [...baseNodeTransforms, ...DOMNodeTransforms];
  29678. const vnodeDirectiveTransforms = Object.assign(Object.assign({}, baseDirectiveTransforms), DOMDirectiveTransforms);
  29679. function createVNodeSlotBranch(props, children, parentContext) {
  29680. // apply a sub-transform using vnode-based transforms.
  29681. const rawOptions = rawOptionsMap.get(parentContext.root);
  29682. const subOptions = Object.assign(Object.assign({}, rawOptions), {
  29683. // overwrite with vnode-based transforms
  29684. nodeTransforms: [
  29685. ...vnodeNodeTransforms,
  29686. ...(rawOptions.nodeTransforms || [])
  29687. ], directiveTransforms: Object.assign(Object.assign({}, vnodeDirectiveTransforms), (rawOptions.directiveTransforms || {})) });
  29688. // wrap the children with a wrapper template for proper children treatment.
  29689. const wrapperNode = {
  29690. type: 1 /* ELEMENT */,
  29691. ns: 0 /* HTML */,
  29692. tag: 'template',
  29693. tagType: 3 /* TEMPLATE */,
  29694. isSelfClosing: false,
  29695. // important: provide v-slot="props" on the wrapper for proper
  29696. // scope analysis
  29697. props: [
  29698. {
  29699. type: 7 /* DIRECTIVE */,
  29700. name: 'slot',
  29701. exp: props,
  29702. arg: undefined,
  29703. modifiers: [],
  29704. loc: locStub
  29705. }
  29706. ],
  29707. children,
  29708. loc: locStub,
  29709. codegenNode: undefined
  29710. };
  29711. subTransform(wrapperNode, subOptions, parentContext);
  29712. return createReturnStatement(children);
  29713. }
  29714. function subTransform(node, options, parentContext) {
  29715. const childRoot = createRoot([node]);
  29716. const childContext = createTransformContext(childRoot, options);
  29717. // this sub transform is for vnode fallback branch so it should be handled
  29718. // like normal render functions
  29719. childContext.ssr = false;
  29720. // inherit parent scope analysis state
  29721. childContext.scopes = Object.assign({}, parentContext.scopes);
  29722. childContext.identifiers = Object.assign({}, parentContext.identifiers);
  29723. childContext.imports = parentContext.imports;
  29724. // traverse
  29725. traverseNode(childRoot, childContext);
  29726. ['helpers', 'components', 'directives'].forEach(key => {
  29727. childContext[key].forEach((value, helperKey) => {
  29728. if (key === 'helpers') {
  29729. const parentCount = parentContext.helpers.get(helperKey);
  29730. if (parentCount === undefined) {
  29731. parentContext.helpers.set(helperKey, value);
  29732. }
  29733. else {
  29734. parentContext.helpers.set(helperKey, value + parentCount);
  29735. }
  29736. }
  29737. else {
  29738. parentContext[key].add(value);
  29739. }
  29740. });
  29741. });
  29742. // imports/hoists are not merged because:
  29743. // - imports are only used for asset urls and should be consistent between
  29744. // node/client branches
  29745. // - hoists are not enabled for the client branch here
  29746. }
  29747. function clone(v) {
  29748. if (isArray(v)) {
  29749. return v.map(clone);
  29750. }
  29751. else if (isObject(v)) {
  29752. const res = {};
  29753. for (const key in v) {
  29754. res[key] = clone(v[key]);
  29755. }
  29756. return res;
  29757. }
  29758. else {
  29759. return v;
  29760. }
  29761. }
  29762. // for directives with children overwrite (e.g. v-html & v-text), we need to
  29763. // store the raw children so that they can be added in the 2nd pass.
  29764. const rawChildrenMap = new WeakMap();
  29765. const ssrTransformElement = (node, context) => {
  29766. if (node.type !== 1 /* ELEMENT */ ||
  29767. node.tagType !== 0 /* ELEMENT */) {
  29768. return;
  29769. }
  29770. return function ssrPostTransformElement() {
  29771. // element
  29772. // generate the template literal representing the open tag.
  29773. const openTag = [`<${node.tag}`];
  29774. // some tags need to be passed to runtime for special checks
  29775. const needTagForRuntime = node.tag === 'textarea' || node.tag.indexOf('-') > 0;
  29776. // v-bind="obj" or v-bind:[key] can potentially overwrite other static
  29777. // attrs and can affect final rendering result, so when they are present
  29778. // we need to bail out to full `renderAttrs`
  29779. const hasDynamicVBind = hasDynamicKeyVBind(node);
  29780. if (hasDynamicVBind) {
  29781. const { props } = buildProps(node, context, node.props, true /* ssr */);
  29782. if (props) {
  29783. const propsExp = createCallExpression(context.helper(SSR_RENDER_ATTRS), [props]);
  29784. if (node.tag === 'textarea') {
  29785. const existingText = node.children[0];
  29786. // If interpolation, this is dynamic <textarea> content, potentially
  29787. // injected by v-model and takes higher priority than v-bind value
  29788. if (!existingText || existingText.type !== 5 /* INTERPOLATION */) {
  29789. // <textarea> with dynamic v-bind. We don't know if the final props
  29790. // will contain .value, so we will have to do something special:
  29791. // assign the merged props to a temp variable, and check whether
  29792. // it contains value (if yes, render is as children).
  29793. const tempId = `_temp${context.temps++}`;
  29794. propsExp.arguments = [
  29795. createAssignmentExpression(createSimpleExpression(tempId, false), props)
  29796. ];
  29797. rawChildrenMap.set(node, createCallExpression(context.helper(SSR_INTERPOLATE), [
  29798. createConditionalExpression(createSimpleExpression(`"value" in ${tempId}`, false), createSimpleExpression(`${tempId}.value`, false), createSimpleExpression(existingText ? existingText.content : ``, true), false)
  29799. ]));
  29800. }
  29801. }
  29802. else if (node.tag === 'input') {
  29803. // <input v-bind="obj" v-model>
  29804. // we need to determine the props to render for the dynamic v-model
  29805. // and merge it with the v-bind expression.
  29806. const vModel = findVModel(node);
  29807. if (vModel) {
  29808. // 1. save the props (san v-model) in a temp variable
  29809. const tempId = `_temp${context.temps++}`;
  29810. const tempExp = createSimpleExpression(tempId, false);
  29811. propsExp.arguments = [
  29812. createSequenceExpression([
  29813. createAssignmentExpression(tempExp, props),
  29814. createCallExpression(context.helper(MERGE_PROPS), [
  29815. tempExp,
  29816. createCallExpression(context.helper(SSR_GET_DYNAMIC_MODEL_PROPS), [
  29817. tempExp,
  29818. vModel.exp // model
  29819. ])
  29820. ])
  29821. ])
  29822. ];
  29823. }
  29824. }
  29825. if (needTagForRuntime) {
  29826. propsExp.arguments.push(`"${node.tag}"`);
  29827. }
  29828. openTag.push(propsExp);
  29829. }
  29830. }
  29831. // book keeping static/dynamic class merging.
  29832. let dynamicClassBinding = undefined;
  29833. let staticClassBinding = undefined;
  29834. // all style bindings are converted to dynamic by transformStyle.
  29835. // but we need to make sure to merge them.
  29836. let dynamicStyleBinding = undefined;
  29837. for (let i = 0; i < node.props.length; i++) {
  29838. const prop = node.props[i];
  29839. // ignore true-value/false-value on input
  29840. if (node.tag === 'input' && isTrueFalseValue(prop)) {
  29841. continue;
  29842. }
  29843. // special cases with children override
  29844. if (prop.type === 7 /* DIRECTIVE */) {
  29845. if (prop.name === 'html' && prop.exp) {
  29846. rawChildrenMap.set(node, prop.exp);
  29847. }
  29848. else if (prop.name === 'text' && prop.exp) {
  29849. node.children = [createInterpolation(prop.exp, prop.loc)];
  29850. }
  29851. else if (prop.name === 'slot') {
  29852. context.onError(createCompilerError(40 /* X_V_SLOT_MISPLACED */, prop.loc));
  29853. }
  29854. else if (isTextareaWithValue(node, prop) && prop.exp) {
  29855. if (!hasDynamicVBind) {
  29856. node.children = [createInterpolation(prop.exp, prop.loc)];
  29857. }
  29858. }
  29859. else {
  29860. // Directive transforms.
  29861. const directiveTransform = context.directiveTransforms[prop.name];
  29862. if (!directiveTransform) {
  29863. // no corresponding ssr directive transform found.
  29864. context.onError(createSSRCompilerError(61 /* X_SSR_CUSTOM_DIRECTIVE_NO_TRANSFORM */, prop.loc));
  29865. }
  29866. else if (!hasDynamicVBind) {
  29867. const { props, ssrTagParts } = directiveTransform(prop, node, context);
  29868. if (ssrTagParts) {
  29869. openTag.push(...ssrTagParts);
  29870. }
  29871. for (let j = 0; j < props.length; j++) {
  29872. const { key, value } = props[j];
  29873. if (isStaticExp(key)) {
  29874. let attrName = key.content;
  29875. // static key attr
  29876. if (attrName === 'key' || attrName === 'ref') {
  29877. continue;
  29878. }
  29879. if (attrName === 'class') {
  29880. openTag.push(` class="`, (dynamicClassBinding = createCallExpression(context.helper(SSR_RENDER_CLASS), [value])), `"`);
  29881. }
  29882. else if (attrName === 'style') {
  29883. if (dynamicStyleBinding) {
  29884. // already has style binding, merge into it.
  29885. mergeCall(dynamicStyleBinding, value);
  29886. }
  29887. else {
  29888. openTag.push(` style="`, (dynamicStyleBinding = createCallExpression(context.helper(SSR_RENDER_STYLE), [value])), `"`);
  29889. }
  29890. }
  29891. else {
  29892. attrName =
  29893. node.tag.indexOf('-') > 0
  29894. ? attrName // preserve raw name on custom elements
  29895. : propsToAttrMap[attrName] || attrName.toLowerCase();
  29896. if (isBooleanAttr(attrName)) {
  29897. openTag.push(createConditionalExpression(createCallExpression(context.helper(SSR_INCLUDE_BOOLEAN_ATTR), [value]), createSimpleExpression(' ' + attrName, true), createSimpleExpression('', true), false /* no newline */));
  29898. }
  29899. else if (isSSRSafeAttrName(attrName)) {
  29900. openTag.push(createCallExpression(context.helper(SSR_RENDER_ATTR), [
  29901. key,
  29902. value
  29903. ]));
  29904. }
  29905. else {
  29906. context.onError(createSSRCompilerError(62 /* X_SSR_UNSAFE_ATTR_NAME */, key.loc));
  29907. }
  29908. }
  29909. }
  29910. else {
  29911. // dynamic key attr
  29912. // this branch is only encountered for custom directive
  29913. // transforms that returns properties with dynamic keys
  29914. const args = [key, value];
  29915. if (needTagForRuntime) {
  29916. args.push(`"${node.tag}"`);
  29917. }
  29918. openTag.push(createCallExpression(context.helper(SSR_RENDER_DYNAMIC_ATTR), args));
  29919. }
  29920. }
  29921. }
  29922. }
  29923. }
  29924. else {
  29925. // special case: value on <textarea>
  29926. if (node.tag === 'textarea' && prop.name === 'value' && prop.value) {
  29927. rawChildrenMap.set(node, escapeHtml(prop.value.content));
  29928. }
  29929. else if (!hasDynamicVBind) {
  29930. if (prop.name === 'key' || prop.name === 'ref') {
  29931. continue;
  29932. }
  29933. // static prop
  29934. if (prop.name === 'class' && prop.value) {
  29935. staticClassBinding = JSON.stringify(prop.value.content);
  29936. }
  29937. openTag.push(` ${prop.name}` +
  29938. (prop.value ? `="${escapeHtml(prop.value.content)}"` : ``));
  29939. }
  29940. }
  29941. }
  29942. // handle co-existence of dynamic + static class bindings
  29943. if (dynamicClassBinding && staticClassBinding) {
  29944. mergeCall(dynamicClassBinding, staticClassBinding);
  29945. removeStaticBinding(openTag, 'class');
  29946. }
  29947. if (context.scopeId) {
  29948. openTag.push(` ${context.scopeId}`);
  29949. }
  29950. node.ssrCodegenNode = createTemplateLiteral(openTag);
  29951. };
  29952. };
  29953. function isTrueFalseValue(prop) {
  29954. if (prop.type === 7 /* DIRECTIVE */) {
  29955. return (prop.name === 'bind' &&
  29956. prop.arg &&
  29957. isStaticExp(prop.arg) &&
  29958. (prop.arg.content === 'true-value' || prop.arg.content === 'false-value'));
  29959. }
  29960. else {
  29961. return prop.name === 'true-value' || prop.name === 'false-value';
  29962. }
  29963. }
  29964. function isTextareaWithValue(node, prop) {
  29965. return !!(node.tag === 'textarea' &&
  29966. prop.name === 'bind' &&
  29967. isStaticArgOf(prop.arg, 'value'));
  29968. }
  29969. function mergeCall(call, arg) {
  29970. const existing = call.arguments[0];
  29971. if (existing.type === 17 /* JS_ARRAY_EXPRESSION */) {
  29972. existing.elements.push(arg);
  29973. }
  29974. else {
  29975. call.arguments[0] = createArrayExpression([existing, arg]);
  29976. }
  29977. }
  29978. function removeStaticBinding(tag, binding) {
  29979. const regExp = new RegExp(`^ ${binding}=".+"$`);
  29980. const i = tag.findIndex(e => typeof e === 'string' && regExp.test(e));
  29981. if (i > -1) {
  29982. tag.splice(i, 1);
  29983. }
  29984. }
  29985. function findVModel(node) {
  29986. return node.props.find(p => p.type === 7 /* DIRECTIVE */ && p.name === 'model' && p.exp);
  29987. }
  29988. function ssrProcessElement(node, context) {
  29989. const isVoidTag = context.options.isVoidTag || NO;
  29990. const elementsToAdd = node.ssrCodegenNode.elements;
  29991. for (let j = 0; j < elementsToAdd.length; j++) {
  29992. context.pushStringPart(elementsToAdd[j]);
  29993. }
  29994. // Handle slot scopeId
  29995. if (context.withSlotScopeId) {
  29996. context.pushStringPart(createSimpleExpression(`_scopeId`, false));
  29997. }
  29998. // close open tag
  29999. context.pushStringPart(`>`);
  30000. const rawChildren = rawChildrenMap.get(node);
  30001. if (rawChildren) {
  30002. context.pushStringPart(rawChildren);
  30003. }
  30004. else if (node.children.length) {
  30005. processChildren(node.children, context);
  30006. }
  30007. if (!isVoidTag(node.tag)) {
  30008. // push closing tag
  30009. context.pushStringPart(`</${node.tag}>`);
  30010. }
  30011. }
  30012. // Because SSR codegen output is completely different from client-side output
  30013. // (e.g. multiple elements can be concatenated into a single template literal
  30014. // instead of each getting a corresponding call), we need to apply an extra
  30015. // transform pass to convert the template AST into a fresh JS AST before
  30016. // passing it to codegen.
  30017. function ssrCodegenTransform(ast, options) {
  30018. const context = createSSRTransformContext(ast, options);
  30019. // inject SFC <style> CSS variables
  30020. // we do this instead of inlining the expression to ensure the vars are
  30021. // only resolved once per render
  30022. if (options.ssrCssVars) {
  30023. const varsExp = processExpression(createSimpleExpression(options.ssrCssVars, false), createTransformContext(createRoot([]), options));
  30024. context.body.push(createCompoundExpression([`const _cssVars = { style: `, varsExp, `}`]));
  30025. }
  30026. const isFragment = ast.children.length > 1 && ast.children.some(c => !isText(c));
  30027. processChildren(ast.children, context, isFragment);
  30028. ast.codegenNode = createBlockStatement(context.body);
  30029. // Finalize helpers.
  30030. // We need to separate helpers imported from 'vue' vs. '@vue/server-renderer'
  30031. ast.ssrHelpers = Array.from(new Set([...ast.helpers.filter(h => h in ssrHelpers), ...context.helpers]));
  30032. ast.helpers = ast.helpers.filter(h => !(h in ssrHelpers));
  30033. }
  30034. function createSSRTransformContext(root, options, helpers = new Set(), withSlotScopeId = false) {
  30035. const body = [];
  30036. let currentString = null;
  30037. return {
  30038. root,
  30039. options,
  30040. body,
  30041. helpers,
  30042. withSlotScopeId,
  30043. onError: options.onError ||
  30044. (e => {
  30045. throw e;
  30046. }),
  30047. helper(name) {
  30048. helpers.add(name);
  30049. return name;
  30050. },
  30051. pushStringPart(part) {
  30052. if (!currentString) {
  30053. const currentCall = createCallExpression(`_push`);
  30054. body.push(currentCall);
  30055. currentString = createTemplateLiteral([]);
  30056. currentCall.arguments.push(currentString);
  30057. }
  30058. const bufferedElements = currentString.elements;
  30059. const lastItem = bufferedElements[bufferedElements.length - 1];
  30060. if (isString(part) && isString(lastItem)) {
  30061. bufferedElements[bufferedElements.length - 1] += part;
  30062. }
  30063. else {
  30064. bufferedElements.push(part);
  30065. }
  30066. },
  30067. pushStatement(statement) {
  30068. // close current string
  30069. currentString = null;
  30070. body.push(statement);
  30071. }
  30072. };
  30073. }
  30074. function createChildContext(parent, withSlotScopeId = parent.withSlotScopeId) {
  30075. // ensure child inherits parent helpers
  30076. return createSSRTransformContext(parent.root, parent.options, parent.helpers, withSlotScopeId);
  30077. }
  30078. function processChildren(children, context, asFragment = false, disableNestedFragments = false) {
  30079. if (asFragment) {
  30080. context.pushStringPart(`<!--[-->`);
  30081. }
  30082. for (let i = 0; i < children.length; i++) {
  30083. const child = children[i];
  30084. switch (child.type) {
  30085. case 1 /* ELEMENT */:
  30086. switch (child.tagType) {
  30087. case 0 /* ELEMENT */:
  30088. ssrProcessElement(child, context);
  30089. break;
  30090. case 1 /* COMPONENT */:
  30091. ssrProcessComponent(child, context);
  30092. break;
  30093. case 2 /* SLOT */:
  30094. ssrProcessSlotOutlet(child, context);
  30095. break;
  30096. case 3 /* TEMPLATE */:
  30097. // TODO
  30098. break;
  30099. default:
  30100. context.onError(createSSRCompilerError(64 /* X_SSR_INVALID_AST_NODE */, child.loc));
  30101. // make sure we exhaust all possible types
  30102. const exhaustiveCheck = child;
  30103. return exhaustiveCheck;
  30104. }
  30105. break;
  30106. case 2 /* TEXT */:
  30107. context.pushStringPart(escapeHtml(child.content));
  30108. break;
  30109. case 3 /* COMMENT */:
  30110. // no need to escape comment here because the AST can only
  30111. // contain valid comments.
  30112. context.pushStringPart(`<!--${child.content}-->`);
  30113. break;
  30114. case 5 /* INTERPOLATION */:
  30115. context.pushStringPart(createCallExpression(context.helper(SSR_INTERPOLATE), [child.content]));
  30116. break;
  30117. case 9 /* IF */:
  30118. ssrProcessIf(child, context, disableNestedFragments);
  30119. break;
  30120. case 11 /* FOR */:
  30121. ssrProcessFor(child, context, disableNestedFragments);
  30122. break;
  30123. case 10 /* IF_BRANCH */:
  30124. // no-op - handled by ssrProcessIf
  30125. break;
  30126. case 12 /* TEXT_CALL */:
  30127. case 8 /* COMPOUND_EXPRESSION */:
  30128. // no-op - these two types can never appear as template child node since
  30129. // `transformText` is not used during SSR compile.
  30130. break;
  30131. default:
  30132. context.onError(createSSRCompilerError(64 /* X_SSR_INVALID_AST_NODE */, child.loc));
  30133. // make sure we exhaust all possible types
  30134. const exhaustiveCheck = child;
  30135. return exhaustiveCheck;
  30136. }
  30137. }
  30138. if (asFragment) {
  30139. context.pushStringPart(`<!--]-->`);
  30140. }
  30141. }
  30142. function processChildrenAsStatement(children, parentContext, asFragment = false, withSlotScopeId = parentContext.withSlotScopeId) {
  30143. const childContext = createChildContext(parentContext, withSlotScopeId);
  30144. processChildren(children, childContext, asFragment);
  30145. return createBlockStatement(childContext.body);
  30146. }
  30147. const ssrTransformModel = (dir, node, context) => {
  30148. const model = dir.exp;
  30149. function checkDuplicatedValue() {
  30150. const value = findProp(node, 'value');
  30151. if (value) {
  30152. context.onError(createDOMCompilerError(57 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
  30153. }
  30154. }
  30155. if (node.tagType === 0 /* ELEMENT */) {
  30156. const res = { props: [] };
  30157. const defaultProps = [
  30158. // default value binding for text type inputs
  30159. createObjectProperty(`value`, model)
  30160. ];
  30161. if (node.tag === 'input') {
  30162. const type = findProp(node, 'type');
  30163. if (type) {
  30164. const value = findValueBinding(node);
  30165. if (type.type === 7 /* DIRECTIVE */) {
  30166. // dynamic type
  30167. res.ssrTagParts = [
  30168. createCallExpression(context.helper(SSR_RENDER_DYNAMIC_MODEL), [
  30169. type.exp,
  30170. model,
  30171. value
  30172. ])
  30173. ];
  30174. }
  30175. else if (type.value) {
  30176. // static type
  30177. switch (type.value.content) {
  30178. case 'radio':
  30179. res.props = [
  30180. createObjectProperty(`checked`, createCallExpression(context.helper(SSR_LOOSE_EQUAL), [
  30181. model,
  30182. value
  30183. ]))
  30184. ];
  30185. break;
  30186. case 'checkbox':
  30187. const trueValueBinding = findProp(node, 'true-value');
  30188. if (trueValueBinding) {
  30189. const trueValue = trueValueBinding.type === 6 /* ATTRIBUTE */
  30190. ? JSON.stringify(trueValueBinding.value.content)
  30191. : trueValueBinding.exp;
  30192. res.props = [
  30193. createObjectProperty(`checked`, createCallExpression(context.helper(SSR_LOOSE_EQUAL), [
  30194. model,
  30195. trueValue
  30196. ]))
  30197. ];
  30198. }
  30199. else {
  30200. res.props = [
  30201. createObjectProperty(`checked`, createConditionalExpression(createCallExpression(`Array.isArray`, [model]), createCallExpression(context.helper(SSR_LOOSE_CONTAIN), [
  30202. model,
  30203. value
  30204. ]), model))
  30205. ];
  30206. }
  30207. break;
  30208. case 'file':
  30209. context.onError(createDOMCompilerError(56 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
  30210. break;
  30211. default:
  30212. checkDuplicatedValue();
  30213. res.props = defaultProps;
  30214. break;
  30215. }
  30216. }
  30217. }
  30218. else if (hasDynamicKeyVBind(node)) ;
  30219. else {
  30220. // text type
  30221. checkDuplicatedValue();
  30222. res.props = defaultProps;
  30223. }
  30224. }
  30225. else if (node.tag === 'textarea') {
  30226. checkDuplicatedValue();
  30227. node.children = [createInterpolation(model, model.loc)];
  30228. }
  30229. else if (node.tag === 'select') ;
  30230. else {
  30231. context.onError(createDOMCompilerError(54 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
  30232. }
  30233. return res;
  30234. }
  30235. else {
  30236. // component v-model
  30237. return transformModel(dir, node, context);
  30238. }
  30239. };
  30240. function findValueBinding(node) {
  30241. const valueBinding = findProp(node, 'value');
  30242. return valueBinding
  30243. ? valueBinding.type === 7 /* DIRECTIVE */
  30244. ? valueBinding.exp
  30245. : createSimpleExpression(valueBinding.value.content, true)
  30246. : createSimpleExpression(`null`, false);
  30247. }
  30248. const ssrTransformShow = (dir, node, context) => {
  30249. if (!dir.exp) {
  30250. context.onError(createDOMCompilerError(58 /* X_V_SHOW_NO_EXPRESSION */));
  30251. }
  30252. return {
  30253. props: [
  30254. createObjectProperty(`style`, createConditionalExpression(dir.exp, createSimpleExpression(`null`, false), createObjectExpression([
  30255. createObjectProperty(`display`, createSimpleExpression(`none`, true))
  30256. ]), false /* no newline */))
  30257. ]
  30258. };
  30259. };
  30260. const hasSingleChild = (node) => node.children.filter(n => n.type !== 3 /* COMMENT */).length === 1;
  30261. const ssrInjectFallthroughAttrs = (node, context) => {
  30262. // _attrs is provided as a function argument.
  30263. // mark it as a known identifier so that it doesn't get prefixed by
  30264. // transformExpression.
  30265. if (node.type === 0 /* ROOT */) {
  30266. context.identifiers._attrs = 1;
  30267. }
  30268. if (node.type === 1 /* ELEMENT */ &&
  30269. node.tagType === 1 /* COMPONENT */ &&
  30270. (isBuiltInType(node.tag, 'Transition') ||
  30271. isBuiltInType(node.tag, 'KeepAlive'))) {
  30272. if (hasSingleChild(node)) {
  30273. injectFallthroughAttrs(node.children[0]);
  30274. }
  30275. return;
  30276. }
  30277. const parent = context.parent;
  30278. if (!parent || parent.type !== 0 /* ROOT */) {
  30279. return;
  30280. }
  30281. if (node.type === 10 /* IF_BRANCH */ && hasSingleChild(node)) {
  30282. injectFallthroughAttrs(node.children[0]);
  30283. }
  30284. else if (hasSingleChild(parent)) {
  30285. injectFallthroughAttrs(node);
  30286. }
  30287. };
  30288. function injectFallthroughAttrs(node) {
  30289. if (node.type === 1 /* ELEMENT */ &&
  30290. (node.tagType === 0 /* ELEMENT */ ||
  30291. node.tagType === 1 /* COMPONENT */) &&
  30292. !findDir(node, 'for')) {
  30293. node.props.push({
  30294. type: 7 /* DIRECTIVE */,
  30295. name: 'bind',
  30296. arg: undefined,
  30297. exp: createSimpleExpression(`_attrs`, false),
  30298. modifiers: [],
  30299. loc: locStub
  30300. });
  30301. }
  30302. }
  30303. const ssrInjectCssVars = (node, context) => {
  30304. if (!context.ssrCssVars) {
  30305. return;
  30306. }
  30307. // _cssVars is initialized once per render function
  30308. // the code is injected in ssrCodegenTransform when creating the
  30309. // ssr transform context
  30310. if (node.type === 0 /* ROOT */) {
  30311. context.identifiers._cssVars = 1;
  30312. }
  30313. const parent = context.parent;
  30314. if (!parent || parent.type !== 0 /* ROOT */) {
  30315. return;
  30316. }
  30317. if (node.type === 10 /* IF_BRANCH */) {
  30318. for (const child of node.children) {
  30319. injectCssVars(child);
  30320. }
  30321. }
  30322. else {
  30323. injectCssVars(node);
  30324. }
  30325. };
  30326. function injectCssVars(node) {
  30327. if (node.type === 1 /* ELEMENT */ &&
  30328. (node.tagType === 0 /* ELEMENT */ ||
  30329. node.tagType === 1 /* COMPONENT */) &&
  30330. !findDir(node, 'for')) {
  30331. if (isBuiltInType(node.tag, 'Suspense')) {
  30332. for (const child of node.children) {
  30333. if (child.type === 1 /* ELEMENT */ &&
  30334. child.tagType === 3 /* TEMPLATE */) {
  30335. // suspense slot
  30336. child.children.forEach(injectCssVars);
  30337. }
  30338. else {
  30339. injectCssVars(child);
  30340. }
  30341. }
  30342. }
  30343. else {
  30344. node.props.push({
  30345. type: 7 /* DIRECTIVE */,
  30346. name: 'bind',
  30347. arg: undefined,
  30348. exp: createSimpleExpression(`_cssVars`, false),
  30349. modifiers: [],
  30350. loc: locStub
  30351. });
  30352. }
  30353. }
  30354. }
  30355. function compile$1(template, options = {}) {
  30356. options = Object.assign(Object.assign(Object.assign({}, options), parserOptions), { ssr: true, inSSR: true, scopeId: options.mode === 'function' ? null : options.scopeId,
  30357. // always prefix since compiler-ssr doesn't have size concern
  30358. prefixIdentifiers: true,
  30359. // disable optimizations that are unnecessary for ssr
  30360. cacheHandlers: false, hoistStatic: false });
  30361. const ast = baseParse(template, options);
  30362. // Save raw options for AST. This is needed when performing sub-transforms
  30363. // on slot vnode branches.
  30364. rawOptionsMap.set(ast, options);
  30365. transform(ast, Object.assign(Object.assign({}, options), { hoistStatic: false, nodeTransforms: [
  30366. ssrTransformIf,
  30367. ssrTransformFor,
  30368. trackVForSlotScopes,
  30369. transformExpression,
  30370. ssrTransformSlotOutlet,
  30371. ssrInjectFallthroughAttrs,
  30372. ssrInjectCssVars,
  30373. ssrTransformElement,
  30374. ssrTransformComponent,
  30375. trackSlotScopes,
  30376. transformStyle,
  30377. ...(options.nodeTransforms || []) // user transforms
  30378. ], directiveTransforms: Object.assign({
  30379. // reusing core v-bind
  30380. bind: transformBind,
  30381. // model and show has dedicated SSR handling
  30382. model: ssrTransformModel, show: ssrTransformShow,
  30383. // the following are ignored during SSR
  30384. on: noopDirectiveTransform, cloak: noopDirectiveTransform, once: noopDirectiveTransform, memo: noopDirectiveTransform }, (options.directiveTransforms || {}) // user transforms
  30385. ) }));
  30386. // traverse the template AST and convert into SSR codegen AST
  30387. // by replacing ast.codegenNode.
  30388. ssrCodegenTransform(ast, options);
  30389. return generate(ast, options);
  30390. }
  30391. var CompilerSSR = /*#__PURE__*/Object.freeze({
  30392. __proto__: null,
  30393. compile: compile$1
  30394. });
  30395. var _polyfillNode_fs = {};
  30396. var _polyfillNode_fs$1 = /*#__PURE__*/Object.freeze({
  30397. __proto__: null,
  30398. 'default': _polyfillNode_fs
  30399. });
  30400. var _fs = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_fs$1);
  30401. var _path = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_path);
  30402. var require$$0 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_util$1);
  30403. const hasWarned = {};
  30404. function warnOnce(msg) {
  30405. const isNodeProd = typeof process !== 'undefined' && ({}).NODE_ENV === 'production';
  30406. if (!isNodeProd && !false && !hasWarned[msg]) {
  30407. hasWarned[msg] = true;
  30408. warn(msg);
  30409. }
  30410. }
  30411. function warn(msg) {
  30412. console.warn(`\x1b[1m\x1b[33m[@vue/compiler-sfc]\x1b[0m\x1b[33m ${msg}\x1b[0m\n`);
  30413. }
  30414. function preprocess({ source, filename, preprocessOptions }, preprocessor) {
  30415. // Consolidate exposes a callback based API, but the callback is in fact
  30416. // called synchronously for most templating engines. In our case, we have to
  30417. // expose a synchronous API so that it is usable in Jest transforms (which
  30418. // have to be sync because they are applied via Node.js require hooks)
  30419. let res = '';
  30420. let err = null;
  30421. preprocessor.render(source, Object.assign({ filename }, preprocessOptions), (_err, _res) => {
  30422. if (_err)
  30423. err = _err;
  30424. res = _res;
  30425. });
  30426. if (err)
  30427. throw err;
  30428. return res;
  30429. }
  30430. function compileTemplate(options) {
  30431. const { preprocessLang, preprocessCustomRequire } = options;
  30432. if (preprocessLang &&
  30433. !preprocessCustomRequire) {
  30434. throw new Error(`[@vue/compiler-sfc] Template preprocessing in the browser build must ` +
  30435. `provide the \`preprocessCustomRequire\` option to return the in-browser ` +
  30436. `version of the preprocessor in the shape of { render(): string }.`);
  30437. }
  30438. const preprocessor = preprocessLang
  30439. ? preprocessCustomRequire
  30440. ? preprocessCustomRequire(preprocessLang)
  30441. : undefined
  30442. : false;
  30443. if (preprocessor) {
  30444. try {
  30445. return doCompileTemplate(Object.assign(Object.assign({}, options), { source: preprocess(options, preprocessor) }));
  30446. }
  30447. catch (e) {
  30448. return {
  30449. code: `export default function render() {}`,
  30450. source: options.source,
  30451. tips: [],
  30452. errors: [e]
  30453. };
  30454. }
  30455. }
  30456. else if (preprocessLang) {
  30457. return {
  30458. code: `export default function render() {}`,
  30459. source: options.source,
  30460. tips: [
  30461. `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
  30462. ],
  30463. errors: [
  30464. `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
  30465. ]
  30466. };
  30467. }
  30468. else {
  30469. return doCompileTemplate(options);
  30470. }
  30471. }
  30472. function doCompileTemplate({ filename, id, scoped, slotted, inMap, source, ssr = false, ssrCssVars, isProd = false, compiler = ssr ? CompilerSSR : CompilerDOM, compilerOptions = {}, transformAssetUrls }) {
  30473. const errors = [];
  30474. const warnings = [];
  30475. let nodeTransforms = [];
  30476. if (isObject(transformAssetUrls)) {
  30477. const assetOptions = normalizeOptions(transformAssetUrls);
  30478. nodeTransforms = [
  30479. createAssetUrlTransformWithOptions(assetOptions),
  30480. createSrcsetTransformWithOptions(assetOptions)
  30481. ];
  30482. }
  30483. else if (transformAssetUrls !== false) {
  30484. nodeTransforms = [transformAssetUrl, transformSrcset];
  30485. }
  30486. if (ssr && !ssrCssVars) {
  30487. warnOnce(`compileTemplate is called with \`ssr: true\` but no ` +
  30488. `corresponding \`cssVars\` option.\`.`);
  30489. }
  30490. if (!id) {
  30491. warnOnce(`compileTemplate now requires the \`id\` option.\`.`);
  30492. id = '';
  30493. }
  30494. const shortId = id.replace(/^data-v-/, '');
  30495. const longId = `data-v-${shortId}`;
  30496. 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
  30497. ? genCssVarsFromList(ssrCssVars, shortId, isProd)
  30498. : '', scopeId: scoped ? longId : undefined, slotted, sourceMap: true }, compilerOptions), { nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []), filename, onError: e => errors.push(e), onWarn: w => warnings.push(w) }));
  30499. // inMap should be the map produced by ./parse.ts which is a simple line-only
  30500. // mapping. If it is present, we need to adjust the final map and errors to
  30501. // reflect the original line numbers.
  30502. if (inMap) {
  30503. if (map) {
  30504. map = mapLines(inMap, map);
  30505. }
  30506. if (errors.length) {
  30507. patchErrors(errors, source, inMap);
  30508. }
  30509. }
  30510. const tips = warnings.map(w => {
  30511. let msg = w.message;
  30512. if (w.loc) {
  30513. msg += `\n${generateCodeFrame(source, w.loc.start.offset, w.loc.end.offset)}`;
  30514. }
  30515. return msg;
  30516. });
  30517. return { code, ast, preamble, source, errors, tips, map };
  30518. }
  30519. function mapLines(oldMap, newMap) {
  30520. if (!oldMap)
  30521. return newMap;
  30522. if (!newMap)
  30523. return oldMap;
  30524. const oldMapConsumer = new SourceMapConsumer$1(oldMap);
  30525. const newMapConsumer = new SourceMapConsumer$1(newMap);
  30526. const mergedMapGenerator = new SourceMapGenerator$2();
  30527. newMapConsumer.eachMapping(m => {
  30528. if (m.originalLine == null) {
  30529. return;
  30530. }
  30531. const origPosInOldMap = oldMapConsumer.originalPositionFor({
  30532. line: m.originalLine,
  30533. column: m.originalColumn
  30534. });
  30535. if (origPosInOldMap.source == null) {
  30536. return;
  30537. }
  30538. mergedMapGenerator.addMapping({
  30539. generated: {
  30540. line: m.generatedLine,
  30541. column: m.generatedColumn
  30542. },
  30543. original: {
  30544. line: origPosInOldMap.line,
  30545. // use current column, since the oldMap produced by @vue/compiler-sfc
  30546. // does not
  30547. column: m.originalColumn
  30548. },
  30549. source: origPosInOldMap.source,
  30550. name: origPosInOldMap.name
  30551. });
  30552. });
  30553. // source-map's type definition is incomplete
  30554. const generator = mergedMapGenerator;
  30555. oldMapConsumer.sources.forEach((sourceFile) => {
  30556. generator._sources.add(sourceFile);
  30557. const sourceContent = oldMapConsumer.sourceContentFor(sourceFile);
  30558. if (sourceContent != null) {
  30559. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  30560. }
  30561. });
  30562. generator._sourceRoot = oldMap.sourceRoot;
  30563. generator._file = oldMap.file;
  30564. return generator.toJSON();
  30565. }
  30566. function patchErrors(errors, source, inMap) {
  30567. const originalSource = inMap.sourcesContent[0];
  30568. const offset = originalSource.indexOf(source);
  30569. const lineOffset = originalSource.slice(0, offset).split(/\r?\n/).length - 1;
  30570. errors.forEach(err => {
  30571. if (err.loc) {
  30572. err.loc.start.line += lineOffset;
  30573. err.loc.start.offset += offset;
  30574. if (err.loc.end !== err.loc.start) {
  30575. err.loc.end.line += lineOffset;
  30576. err.loc.end.offset += offset;
  30577. }
  30578. }
  30579. });
  30580. }
  30581. const defaultExportRE = /((?:^|\n|;)\s*)export(\s*)default/;
  30582. const namedDefaultExportRE = /((?:^|\n|;)\s*)export(.+)as(\s*)default/s;
  30583. const exportDefaultClassRE = /((?:^|\n|;)\s*)export\s+default\s+class\s+([\w$]+)/;
  30584. /**
  30585. * Utility for rewriting `export default` in a script block into a variable
  30586. * declaration so that we can inject things into it
  30587. */
  30588. function rewriteDefault(input, as, parserPlugins) {
  30589. if (!hasDefaultExport(input)) {
  30590. return input + `\nconst ${as} = {}`;
  30591. }
  30592. let replaced;
  30593. const classMatch = input.match(exportDefaultClassRE);
  30594. if (classMatch) {
  30595. replaced =
  30596. input.replace(exportDefaultClassRE, '$1class $2') +
  30597. `\nconst ${as} = ${classMatch[2]}`;
  30598. }
  30599. else {
  30600. replaced = input.replace(defaultExportRE, `$1const ${as} =`);
  30601. }
  30602. if (!hasDefaultExport(replaced)) {
  30603. return replaced;
  30604. }
  30605. // if the script somehow still contains `default export`, it probably has
  30606. // multi-line comments or template strings. fallback to a full parse.
  30607. const s = new MagicString(input);
  30608. const ast = parse_1(input, {
  30609. sourceType: 'module',
  30610. plugins: parserPlugins
  30611. }).program.body;
  30612. ast.forEach(node => {
  30613. if (node.type === 'ExportDefaultDeclaration') {
  30614. s.overwrite(node.start, node.declaration.start, `const ${as} = `);
  30615. }
  30616. if (node.type === 'ExportNamedDeclaration') {
  30617. node.specifiers.forEach(specifier => {
  30618. if (specifier.type === 'ExportSpecifier' &&
  30619. specifier.exported.type === 'Identifier' &&
  30620. specifier.exported.name === 'default') {
  30621. const end = specifier.end;
  30622. s.overwrite(specifier.start, input.charAt(end) === ',' ? end + 1 : end, ``);
  30623. s.append(`\nconst ${as} = ${specifier.local.name}`);
  30624. }
  30625. });
  30626. }
  30627. });
  30628. return s.toString();
  30629. }
  30630. function hasDefaultExport(input) {
  30631. return defaultExportRE.test(input) || namedDefaultExportRE.test(input);
  30632. }
  30633. const CONVERT_SYMBOL = '$';
  30634. const ESCAPE_SYMBOL = '$$';
  30635. const shorthands = ['ref', 'computed', 'shallowRef', 'toRef', 'customRef'];
  30636. const transformCheckRE = /[^\w]\$(?:\$|ref|computed|shallowRef)?\s*(\(|\<)/;
  30637. function shouldTransform(src) {
  30638. return transformCheckRE.test(src);
  30639. }
  30640. function transform$1(src, { filename, sourceMap, parserPlugins, importHelpersFrom = 'vue' } = {}) {
  30641. const plugins = parserPlugins || [];
  30642. if (filename) {
  30643. if (/\.tsx?$/.test(filename)) {
  30644. plugins.push('typescript');
  30645. }
  30646. if (filename.endsWith('x')) {
  30647. plugins.push('jsx');
  30648. }
  30649. }
  30650. const ast = parse_1(src, {
  30651. sourceType: 'module',
  30652. plugins
  30653. });
  30654. const s = new MagicString(src);
  30655. const res = transformAST(ast.program, s, 0);
  30656. // inject helper imports
  30657. if (res.importedHelpers.length) {
  30658. s.prepend(`import { ${res.importedHelpers
  30659. .map(h => `${h} as _${h}`)
  30660. .join(', ')} } from '${importHelpersFrom}'\n`);
  30661. }
  30662. return Object.assign(Object.assign({}, res), { code: s.toString(), map: sourceMap
  30663. ? s.generateMap({
  30664. source: filename,
  30665. hires: true,
  30666. includeContent: true
  30667. })
  30668. : null });
  30669. }
  30670. function transformAST(ast, s, offset = 0, knownRefs, knownProps) {
  30671. // TODO remove when out of experimental
  30672. warnExperimental();
  30673. let convertSymbol = CONVERT_SYMBOL;
  30674. let escapeSymbol = ESCAPE_SYMBOL;
  30675. // macro import handling
  30676. for (const node of ast.body) {
  30677. if (node.type === 'ImportDeclaration' &&
  30678. node.source.value === 'vue/macros') {
  30679. // remove macro imports
  30680. s.remove(node.start + offset, node.end + offset);
  30681. // check aliasing
  30682. for (const specifier of node.specifiers) {
  30683. if (specifier.type === 'ImportSpecifier') {
  30684. const imported = specifier.imported.name;
  30685. const local = specifier.local.name;
  30686. if (local !== imported) {
  30687. if (imported === ESCAPE_SYMBOL) {
  30688. escapeSymbol = local;
  30689. }
  30690. else if (imported === CONVERT_SYMBOL) {
  30691. convertSymbol = local;
  30692. }
  30693. else {
  30694. error(`macro imports for ref-creating methods do not support aliasing.`, specifier);
  30695. }
  30696. }
  30697. }
  30698. }
  30699. }
  30700. }
  30701. const importedHelpers = new Set();
  30702. const rootScope = {};
  30703. const scopeStack = [rootScope];
  30704. let currentScope = rootScope;
  30705. let escapeScope; // inside $$()
  30706. const excludedIds = new WeakSet();
  30707. const parentStack = [];
  30708. const propsLocalToPublicMap = Object.create(null);
  30709. if (knownRefs) {
  30710. for (const key of knownRefs) {
  30711. rootScope[key] = true;
  30712. }
  30713. }
  30714. if (knownProps) {
  30715. for (const key in knownProps) {
  30716. const { local } = knownProps[key];
  30717. rootScope[local] = 'prop';
  30718. propsLocalToPublicMap[local] = key;
  30719. }
  30720. }
  30721. function isRefCreationCall(callee) {
  30722. if (callee === convertSymbol) {
  30723. return convertSymbol;
  30724. }
  30725. if (callee[0] === '$' && shorthands.includes(callee.slice(1))) {
  30726. return callee;
  30727. }
  30728. return false;
  30729. }
  30730. function error(msg, node) {
  30731. const e = new Error(msg);
  30732. e.node = node;
  30733. throw e;
  30734. }
  30735. function helper(msg) {
  30736. importedHelpers.add(msg);
  30737. return `_${msg}`;
  30738. }
  30739. function registerBinding(id, isRef = false) {
  30740. excludedIds.add(id);
  30741. if (currentScope) {
  30742. currentScope[id.name] = isRef;
  30743. }
  30744. else {
  30745. error('registerBinding called without active scope, something is wrong.', id);
  30746. }
  30747. }
  30748. const registerRefBinding = (id) => registerBinding(id, true);
  30749. let tempVarCount = 0;
  30750. function genTempVar() {
  30751. return `__$temp_${++tempVarCount}`;
  30752. }
  30753. function snip(node) {
  30754. return s.original.slice(node.start + offset, node.end + offset);
  30755. }
  30756. function walkScope(node, isRoot = false) {
  30757. for (const stmt of node.body) {
  30758. if (stmt.type === 'VariableDeclaration') {
  30759. if (stmt.declare)
  30760. continue;
  30761. for (const decl of stmt.declarations) {
  30762. let refCall;
  30763. const isCall = decl.init &&
  30764. decl.init.type === 'CallExpression' &&
  30765. decl.init.callee.type === 'Identifier';
  30766. if (isCall &&
  30767. (refCall = isRefCreationCall(decl.init.callee.name))) {
  30768. processRefDeclaration(refCall, decl.id, decl.init);
  30769. }
  30770. else {
  30771. const isProps = isRoot &&
  30772. isCall &&
  30773. decl.init.callee.name === 'defineProps';
  30774. for (const id of extractIdentifiers(decl.id)) {
  30775. if (isProps) {
  30776. // for defineProps destructure, only exclude them since they
  30777. // are already passed in as knownProps
  30778. excludedIds.add(id);
  30779. }
  30780. else {
  30781. registerBinding(id);
  30782. }
  30783. }
  30784. }
  30785. }
  30786. }
  30787. else if (stmt.type === 'FunctionDeclaration' ||
  30788. stmt.type === 'ClassDeclaration') {
  30789. if (stmt.declare || !stmt.id)
  30790. continue;
  30791. registerBinding(stmt.id);
  30792. }
  30793. }
  30794. }
  30795. function processRefDeclaration(method, id, call) {
  30796. excludedIds.add(call.callee);
  30797. if (method === convertSymbol) {
  30798. // $
  30799. // remove macro
  30800. s.remove(call.callee.start + offset, call.callee.end + offset);
  30801. if (id.type === 'Identifier') {
  30802. // single variable
  30803. registerRefBinding(id);
  30804. }
  30805. else if (id.type === 'ObjectPattern') {
  30806. processRefObjectPattern(id, call);
  30807. }
  30808. else if (id.type === 'ArrayPattern') {
  30809. processRefArrayPattern(id, call);
  30810. }
  30811. }
  30812. else {
  30813. // shorthands
  30814. if (id.type === 'Identifier') {
  30815. registerRefBinding(id);
  30816. // replace call
  30817. s.overwrite(call.start + offset, call.start + method.length + offset, helper(method.slice(1)));
  30818. }
  30819. else {
  30820. error(`${method}() cannot be used with destructure patterns.`, call);
  30821. }
  30822. }
  30823. }
  30824. function processRefObjectPattern(pattern, call, tempVar, path = []) {
  30825. if (!tempVar) {
  30826. tempVar = genTempVar();
  30827. // const { x } = $(useFoo()) --> const __$temp_1 = useFoo()
  30828. s.overwrite(pattern.start + offset, pattern.end + offset, tempVar);
  30829. }
  30830. for (const p of pattern.properties) {
  30831. let nameId;
  30832. let key;
  30833. let defaultValue;
  30834. if (p.type === 'ObjectProperty') {
  30835. if (p.key.start === p.value.start) {
  30836. // shorthand { foo }
  30837. nameId = p.key;
  30838. if (p.value.type === 'Identifier') {
  30839. // avoid shorthand value identifier from being processed
  30840. excludedIds.add(p.value);
  30841. }
  30842. else if (p.value.type === 'AssignmentPattern' &&
  30843. p.value.left.type === 'Identifier') {
  30844. // { foo = 1 }
  30845. excludedIds.add(p.value.left);
  30846. defaultValue = p.value.right;
  30847. }
  30848. }
  30849. else {
  30850. key = p.computed ? p.key : p.key.name;
  30851. if (p.value.type === 'Identifier') {
  30852. // { foo: bar }
  30853. nameId = p.value;
  30854. }
  30855. else if (p.value.type === 'ObjectPattern') {
  30856. processRefObjectPattern(p.value, call, tempVar, [...path, key]);
  30857. }
  30858. else if (p.value.type === 'ArrayPattern') {
  30859. processRefArrayPattern(p.value, call, tempVar, [...path, key]);
  30860. }
  30861. else if (p.value.type === 'AssignmentPattern') {
  30862. if (p.value.left.type === 'Identifier') {
  30863. // { foo: bar = 1 }
  30864. nameId = p.value.left;
  30865. defaultValue = p.value.right;
  30866. }
  30867. else if (p.value.left.type === 'ObjectPattern') {
  30868. processRefObjectPattern(p.value.left, call, tempVar, [
  30869. ...path,
  30870. [key, p.value.right]
  30871. ]);
  30872. }
  30873. else if (p.value.left.type === 'ArrayPattern') {
  30874. processRefArrayPattern(p.value.left, call, tempVar, [
  30875. ...path,
  30876. [key, p.value.right]
  30877. ]);
  30878. }
  30879. else ;
  30880. }
  30881. }
  30882. }
  30883. else {
  30884. // rest element { ...foo }
  30885. error(`reactivity destructure does not support rest elements.`, p);
  30886. }
  30887. if (nameId) {
  30888. registerRefBinding(nameId);
  30889. // inject toRef() after original replaced pattern
  30890. const source = pathToString(tempVar, path);
  30891. const keyStr = isString(key)
  30892. ? `'${key}'`
  30893. : key
  30894. ? snip(key)
  30895. : `'${nameId.name}'`;
  30896. const defaultStr = defaultValue ? `, ${snip(defaultValue)}` : ``;
  30897. s.appendLeft(call.end + offset, `,\n ${nameId.name} = ${helper('toRef')}(${source}, ${keyStr}${defaultStr})`);
  30898. }
  30899. }
  30900. }
  30901. function processRefArrayPattern(pattern, call, tempVar, path = []) {
  30902. if (!tempVar) {
  30903. // const [x] = $(useFoo()) --> const __$temp_1 = useFoo()
  30904. tempVar = genTempVar();
  30905. s.overwrite(pattern.start + offset, pattern.end + offset, tempVar);
  30906. }
  30907. for (let i = 0; i < pattern.elements.length; i++) {
  30908. const e = pattern.elements[i];
  30909. if (!e)
  30910. continue;
  30911. let nameId;
  30912. let defaultValue;
  30913. if (e.type === 'Identifier') {
  30914. // [a] --> [__a]
  30915. nameId = e;
  30916. }
  30917. else if (e.type === 'AssignmentPattern') {
  30918. // [a = 1]
  30919. nameId = e.left;
  30920. defaultValue = e.right;
  30921. }
  30922. else if (e.type === 'RestElement') {
  30923. // [...a]
  30924. error(`reactivity destructure does not support rest elements.`, e);
  30925. }
  30926. else if (e.type === 'ObjectPattern') {
  30927. processRefObjectPattern(e, call, tempVar, [...path, i]);
  30928. }
  30929. else if (e.type === 'ArrayPattern') {
  30930. processRefArrayPattern(e, call, tempVar, [...path, i]);
  30931. }
  30932. if (nameId) {
  30933. registerRefBinding(nameId);
  30934. // inject toRef() after original replaced pattern
  30935. const source = pathToString(tempVar, path);
  30936. const defaultStr = defaultValue ? `, ${snip(defaultValue)}` : ``;
  30937. s.appendLeft(call.end + offset, `,\n ${nameId.name} = ${helper('toRef')}(${source}, ${i}${defaultStr})`);
  30938. }
  30939. }
  30940. }
  30941. function pathToString(source, path) {
  30942. if (path.length) {
  30943. for (const seg of path) {
  30944. if (isArray(seg)) {
  30945. source = `(${source}${segToString(seg[0])} || ${snip(seg[1])})`;
  30946. }
  30947. else {
  30948. source += segToString(seg);
  30949. }
  30950. }
  30951. }
  30952. return source;
  30953. }
  30954. function segToString(seg) {
  30955. if (typeof seg === 'number') {
  30956. return `[${seg}]`;
  30957. }
  30958. else if (typeof seg === 'string') {
  30959. return `.${seg}`;
  30960. }
  30961. else {
  30962. return snip(seg);
  30963. }
  30964. }
  30965. function rewriteId(scope, id, parent, parentStack) {
  30966. if (hasOwn(scope, id.name)) {
  30967. const bindingType = scope[id.name];
  30968. if (bindingType) {
  30969. const isProp = bindingType === 'prop';
  30970. if (isStaticProperty(parent) && parent.shorthand) {
  30971. // let binding used in a property shorthand
  30972. // skip for destructure patterns
  30973. if (!parent.inPattern ||
  30974. isInDestructureAssignment(parent, parentStack)) {
  30975. if (isProp) {
  30976. if (escapeScope) {
  30977. // prop binding in $$()
  30978. // { prop } -> { prop: __prop_prop }
  30979. registerEscapedPropBinding(id);
  30980. s.appendLeft(id.end + offset, `: __props_${propsLocalToPublicMap[id.name]}`);
  30981. }
  30982. else {
  30983. // { prop } -> { prop: __prop.prop }
  30984. s.appendLeft(id.end + offset, `: __props.${propsLocalToPublicMap[id.name]}`);
  30985. }
  30986. }
  30987. else {
  30988. // { foo } -> { foo: foo.value }
  30989. s.appendLeft(id.end + offset, `: ${id.name}.value`);
  30990. }
  30991. }
  30992. }
  30993. else {
  30994. if (isProp) {
  30995. if (escapeScope) {
  30996. // x --> __props_x
  30997. registerEscapedPropBinding(id);
  30998. s.overwrite(id.start + offset, id.end + offset, `__props_${propsLocalToPublicMap[id.name]}`);
  30999. }
  31000. else {
  31001. // x --> __props.x
  31002. s.overwrite(id.start + offset, id.end + offset, `__props.${propsLocalToPublicMap[id.name]}`);
  31003. }
  31004. }
  31005. else {
  31006. // x --> x.value
  31007. s.appendLeft(id.end + offset, '.value');
  31008. }
  31009. }
  31010. }
  31011. return true;
  31012. }
  31013. return false;
  31014. }
  31015. const propBindingRefs = {};
  31016. function registerEscapedPropBinding(id) {
  31017. if (!propBindingRefs.hasOwnProperty(id.name)) {
  31018. propBindingRefs[id.name] = true;
  31019. const publicKey = propsLocalToPublicMap[id.name];
  31020. s.prependRight(offset, `const __props_${publicKey} = ${helper(`toRef`)}(__props, '${publicKey}')\n`);
  31021. }
  31022. }
  31023. // check root scope first
  31024. walkScope(ast, true);
  31025. walk$1(ast, {
  31026. enter(node, parent) {
  31027. parent && parentStack.push(parent);
  31028. // function scopes
  31029. if (isFunctionType(node)) {
  31030. scopeStack.push((currentScope = {}));
  31031. walkFunctionParams(node, registerBinding);
  31032. if (node.body.type === 'BlockStatement') {
  31033. walkScope(node.body);
  31034. }
  31035. return;
  31036. }
  31037. // non-function block scopes
  31038. if (node.type === 'BlockStatement' && !isFunctionType(parent)) {
  31039. scopeStack.push((currentScope = {}));
  31040. walkScope(node);
  31041. return;
  31042. }
  31043. if (parent &&
  31044. parent.type.startsWith('TS') &&
  31045. parent.type !== 'TSAsExpression' &&
  31046. parent.type !== 'TSNonNullExpression' &&
  31047. parent.type !== 'TSTypeAssertion') {
  31048. return this.skip();
  31049. }
  31050. if (node.type === 'Identifier' &&
  31051. // if inside $$(), skip unless this is a destructured prop binding
  31052. !(escapeScope && rootScope[node.name] !== 'prop') &&
  31053. isReferencedIdentifier(node, parent, parentStack) &&
  31054. !excludedIds.has(node)) {
  31055. // walk up the scope chain to check if id should be appended .value
  31056. let i = scopeStack.length;
  31057. while (i--) {
  31058. if (rewriteId(scopeStack[i], node, parent, parentStack)) {
  31059. return;
  31060. }
  31061. }
  31062. }
  31063. if (node.type === 'CallExpression' && node.callee.type === 'Identifier') {
  31064. const callee = node.callee.name;
  31065. const refCall = isRefCreationCall(callee);
  31066. if (refCall && (!parent || parent.type !== 'VariableDeclarator')) {
  31067. return error(`${refCall} can only be used as the initializer of ` +
  31068. `a variable declaration.`, node);
  31069. }
  31070. if (callee === escapeSymbol) {
  31071. s.remove(node.callee.start + offset, node.callee.end + offset);
  31072. escapeScope = node;
  31073. }
  31074. // TODO remove when out of experimental
  31075. if (callee === '$raw') {
  31076. error(`$raw() has been replaced by $$(). ` +
  31077. `See ${RFC_LINK} for latest updates.`, node);
  31078. }
  31079. if (callee === '$fromRef') {
  31080. error(`$fromRef() has been replaced by $(). ` +
  31081. `See ${RFC_LINK} for latest updates.`, node);
  31082. }
  31083. }
  31084. },
  31085. leave(node, parent) {
  31086. parent && parentStack.pop();
  31087. if ((node.type === 'BlockStatement' && !isFunctionType(parent)) ||
  31088. isFunctionType(node)) {
  31089. scopeStack.pop();
  31090. currentScope = scopeStack[scopeStack.length - 1] || null;
  31091. }
  31092. if (node === escapeScope) {
  31093. escapeScope = undefined;
  31094. }
  31095. }
  31096. });
  31097. return {
  31098. rootRefs: Object.keys(rootScope).filter(key => rootScope[key] === true),
  31099. importedHelpers: [...importedHelpers]
  31100. };
  31101. }
  31102. const RFC_LINK = `https://github.com/vuejs/rfcs/discussions/369`;
  31103. const hasWarned$1 = {};
  31104. function warnExperimental() {
  31105. // eslint-disable-next-line
  31106. if (typeof window !== 'undefined') {
  31107. return;
  31108. }
  31109. warnOnce$1(`Reactivity transform is an experimental feature.\n` +
  31110. `Experimental features may change behavior between patch versions.\n` +
  31111. `It is recommended to pin your vue dependencies to exact versions to avoid breakage.\n` +
  31112. `You can follow the proposal's status at ${RFC_LINK}.`);
  31113. }
  31114. function warnOnce$1(msg) {
  31115. const isNodeProd = typeof process !== 'undefined' && ({}).NODE_ENV === 'production';
  31116. if (!isNodeProd && !false && !hasWarned$1[msg]) {
  31117. hasWarned$1[msg] = true;
  31118. warn$1(msg);
  31119. }
  31120. }
  31121. function warn$1(msg) {
  31122. console.warn(`\x1b[1m\x1b[33m[@vue/ref-transform]\x1b[0m\x1b[33m ${msg}\x1b[0m\n`);
  31123. }
  31124. // Special compiler macros
  31125. const DEFINE_PROPS = 'defineProps';
  31126. const DEFINE_EMITS = 'defineEmits';
  31127. const DEFINE_EXPOSE = 'defineExpose';
  31128. const WITH_DEFAULTS = 'withDefaults';
  31129. // constants
  31130. const DEFAULT_VAR = `__default__`;
  31131. const isBuiltInDir = makeMap(`once,memo,if,else,else-if,slot,text,html,on,bind,model,show,cloak,is`);
  31132. /**
  31133. * Compile `<script setup>`
  31134. * It requires the whole SFC descriptor because we need to handle and merge
  31135. * normal `<script>` + `<script setup>` if both are present.
  31136. */
  31137. function compileScript(sfc, options) {
  31138. let { script, scriptSetup, source, filename } = sfc;
  31139. // feature flags
  31140. // TODO remove support for deprecated options when out of experimental
  31141. const enableRefTransform = !!options.reactivityTransform ||
  31142. !!options.refSugar ||
  31143. !!options.refTransform;
  31144. const enablePropsTransform = !!options.reactivityTransform || !!options.propsDestructureTransform;
  31145. const isProd = !!options.isProd;
  31146. const genSourceMap = options.sourceMap !== false;
  31147. let refBindings;
  31148. if (!options.id) {
  31149. warnOnce(`compileScript now requires passing the \`id\` option.\n` +
  31150. `Upgrade your vite or vue-loader version for compatibility with ` +
  31151. `the latest experimental proposals.`);
  31152. }
  31153. const scopeId = options.id ? options.id.replace(/^data-v-/, '') : '';
  31154. const cssVars = sfc.cssVars;
  31155. const scriptLang = script && script.lang;
  31156. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  31157. const isTS = scriptLang === 'ts' ||
  31158. scriptLang === 'tsx' ||
  31159. scriptSetupLang === 'ts' ||
  31160. scriptSetupLang === 'tsx';
  31161. const plugins = [];
  31162. if (!isTS || scriptLang === 'tsx' || scriptSetupLang === 'tsx') {
  31163. plugins.push('jsx');
  31164. }
  31165. if (options.babelParserPlugins)
  31166. plugins.push(...options.babelParserPlugins);
  31167. if (isTS)
  31168. plugins.push('typescript', 'decorators-legacy');
  31169. if (!scriptSetup) {
  31170. if (!script) {
  31171. throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`);
  31172. }
  31173. if (scriptLang && !isTS && scriptLang !== 'jsx') {
  31174. // do not process non js/ts script blocks
  31175. return script;
  31176. }
  31177. try {
  31178. let content = script.content;
  31179. let map = script.map;
  31180. const scriptAst = parse_1(content, {
  31181. plugins,
  31182. sourceType: 'module'
  31183. }).program;
  31184. const bindings = analyzeScriptBindings(scriptAst.body);
  31185. if (enableRefTransform && shouldTransform(content)) {
  31186. const s = new MagicString(source);
  31187. const startOffset = script.loc.start.offset;
  31188. const endOffset = script.loc.end.offset;
  31189. const { importedHelpers } = transformAST(scriptAst, s, startOffset);
  31190. if (importedHelpers.length) {
  31191. s.prepend(`import { ${importedHelpers
  31192. .map(h => `${h} as _${h}`)
  31193. .join(', ')} } from 'vue'\n`);
  31194. }
  31195. s.remove(0, startOffset);
  31196. s.remove(endOffset, source.length);
  31197. content = s.toString();
  31198. if (genSourceMap) {
  31199. map = s.generateMap({
  31200. source: filename,
  31201. hires: true,
  31202. includeContent: true
  31203. });
  31204. }
  31205. }
  31206. if (cssVars.length) {
  31207. content = rewriteDefault(content, DEFAULT_VAR, plugins);
  31208. content += genNormalScriptCssVarsCode(cssVars, bindings, scopeId, isProd);
  31209. content += `\nexport default ${DEFAULT_VAR}`;
  31210. }
  31211. return Object.assign(Object.assign({}, script), { content,
  31212. map,
  31213. bindings, scriptAst: scriptAst.body });
  31214. }
  31215. catch (e) {
  31216. // silently fallback if parse fails since user may be using custom
  31217. // babel syntax
  31218. return script;
  31219. }
  31220. }
  31221. if (script && scriptLang !== scriptSetupLang) {
  31222. throw new Error(`[@vue/compiler-sfc] <script> and <script setup> must have the same ` +
  31223. `language type.`);
  31224. }
  31225. if (scriptSetupLang && !isTS && scriptSetupLang !== 'jsx') {
  31226. // do not process non js/ts script blocks
  31227. return scriptSetup;
  31228. }
  31229. // metadata that needs to be returned
  31230. const bindingMetadata = {};
  31231. const helperImports = new Set();
  31232. const userImports = Object.create(null);
  31233. const userImportAlias = Object.create(null);
  31234. const scriptBindings = Object.create(null);
  31235. const setupBindings = Object.create(null);
  31236. let defaultExport;
  31237. let hasDefinePropsCall = false;
  31238. let hasDefineEmitCall = false;
  31239. let hasDefineExposeCall = false;
  31240. let propsRuntimeDecl;
  31241. let propsRuntimeDefaults;
  31242. let propsDestructureDecl;
  31243. let propsDestructureRestId;
  31244. let propsTypeDecl;
  31245. let propsTypeDeclRaw;
  31246. let propsIdentifier;
  31247. let emitsRuntimeDecl;
  31248. let emitsTypeDecl;
  31249. let emitsTypeDeclRaw;
  31250. let emitIdentifier;
  31251. let hasAwait = false;
  31252. let hasInlinedSsrRenderFn = false;
  31253. // props/emits declared via types
  31254. const typeDeclaredProps = {};
  31255. const typeDeclaredEmits = new Set();
  31256. // record declared types for runtime props type generation
  31257. const declaredTypes = {};
  31258. // props destructure data
  31259. const propsDestructuredBindings = Object.create(null);
  31260. // magic-string state
  31261. const s = new MagicString(source);
  31262. const startOffset = scriptSetup.loc.start.offset;
  31263. const endOffset = scriptSetup.loc.end.offset;
  31264. const scriptStartOffset = script && script.loc.start.offset;
  31265. const scriptEndOffset = script && script.loc.end.offset;
  31266. function helper(key) {
  31267. helperImports.add(key);
  31268. return `_${key}`;
  31269. }
  31270. function parse(input, options, offset) {
  31271. try {
  31272. return parse_1(input, options).program;
  31273. }
  31274. catch (e) {
  31275. e.message = `[@vue/compiler-sfc] ${e.message}\n\n${sfc.filename}\n${generateCodeFrame(source, e.pos + offset, e.pos + offset + 1)}`;
  31276. throw e;
  31277. }
  31278. }
  31279. function error(msg, node, end = node.end + startOffset) {
  31280. throw new Error(`[@vue/compiler-sfc] ${msg}\n\n${sfc.filename}\n${generateCodeFrame(source, node.start + startOffset, end)}`);
  31281. }
  31282. function registerUserImport(source, local, imported, isType, isFromSetup) {
  31283. if (source === 'vue' && imported) {
  31284. userImportAlias[imported] = local;
  31285. }
  31286. let isUsedInTemplate = true;
  31287. if (isTS && sfc.template && !sfc.template.src && !sfc.template.lang) {
  31288. isUsedInTemplate = isImportUsed(local, sfc);
  31289. }
  31290. userImports[local] = {
  31291. isType,
  31292. imported: imported || 'default',
  31293. source,
  31294. isFromSetup,
  31295. isUsedInTemplate
  31296. };
  31297. }
  31298. function processDefineProps(node, declId) {
  31299. if (!isCallOf(node, DEFINE_PROPS)) {
  31300. return false;
  31301. }
  31302. if (hasDefinePropsCall) {
  31303. error(`duplicate ${DEFINE_PROPS}() call`, node);
  31304. }
  31305. hasDefinePropsCall = true;
  31306. propsRuntimeDecl = node.arguments[0];
  31307. // call has type parameters - infer runtime types from it
  31308. if (node.typeParameters) {
  31309. if (propsRuntimeDecl) {
  31310. error(`${DEFINE_PROPS}() cannot accept both type and non-type arguments ` +
  31311. `at the same time. Use one or the other.`, node);
  31312. }
  31313. propsTypeDeclRaw = node.typeParameters.params[0];
  31314. propsTypeDecl = resolveQualifiedType(propsTypeDeclRaw, node => node.type === 'TSTypeLiteral');
  31315. if (!propsTypeDecl) {
  31316. error(`type argument passed to ${DEFINE_PROPS}() must be a literal type, ` +
  31317. `or a reference to an interface or literal type.`, propsTypeDeclRaw);
  31318. }
  31319. }
  31320. if (declId) {
  31321. if (enablePropsTransform && declId.type === 'ObjectPattern') {
  31322. propsDestructureDecl = declId;
  31323. // props destructure - handle compilation sugar
  31324. for (const prop of declId.properties) {
  31325. if (prop.type === 'ObjectProperty') {
  31326. if (prop.computed) {
  31327. error(`${DEFINE_PROPS}() destructure cannot use computed key.`, prop.key);
  31328. }
  31329. const propKey = prop.key.name;
  31330. if (prop.value.type === 'AssignmentPattern') {
  31331. // default value { foo = 123 }
  31332. const { left, right } = prop.value;
  31333. if (left.type !== 'Identifier') {
  31334. error(`${DEFINE_PROPS}() destructure does not support nested patterns.`, left);
  31335. }
  31336. // store default value
  31337. propsDestructuredBindings[propKey] = {
  31338. local: left.name,
  31339. default: right
  31340. };
  31341. }
  31342. else if (prop.value.type === 'Identifier') {
  31343. // simple destructure
  31344. propsDestructuredBindings[propKey] = {
  31345. local: prop.value.name
  31346. };
  31347. }
  31348. else {
  31349. error(`${DEFINE_PROPS}() destructure does not support nested patterns.`, prop.value);
  31350. }
  31351. }
  31352. else {
  31353. // rest spread
  31354. propsDestructureRestId = prop.argument.name;
  31355. }
  31356. }
  31357. }
  31358. else {
  31359. propsIdentifier = scriptSetup.content.slice(declId.start, declId.end);
  31360. }
  31361. }
  31362. return true;
  31363. }
  31364. function processWithDefaults(node, declId) {
  31365. if (!isCallOf(node, WITH_DEFAULTS)) {
  31366. return false;
  31367. }
  31368. if (processDefineProps(node.arguments[0], declId)) {
  31369. if (propsRuntimeDecl) {
  31370. error(`${WITH_DEFAULTS} can only be used with type-based ` +
  31371. `${DEFINE_PROPS} declaration.`, node);
  31372. }
  31373. if (propsDestructureDecl) {
  31374. error(`${WITH_DEFAULTS}() is unnecessary when using destructure with ${DEFINE_PROPS}().\n` +
  31375. `Prefer using destructure default values, e.g. const { foo = 1 } = defineProps(...).`, node.callee);
  31376. }
  31377. propsRuntimeDefaults = node.arguments[1];
  31378. if (!propsRuntimeDefaults ||
  31379. propsRuntimeDefaults.type !== 'ObjectExpression') {
  31380. error(`The 2nd argument of ${WITH_DEFAULTS} must be an object literal.`, propsRuntimeDefaults || node);
  31381. }
  31382. }
  31383. else {
  31384. error(`${WITH_DEFAULTS}' first argument must be a ${DEFINE_PROPS} call.`, node.arguments[0] || node);
  31385. }
  31386. return true;
  31387. }
  31388. function processDefineEmits(node, declId) {
  31389. if (!isCallOf(node, DEFINE_EMITS)) {
  31390. return false;
  31391. }
  31392. if (hasDefineEmitCall) {
  31393. error(`duplicate ${DEFINE_EMITS}() call`, node);
  31394. }
  31395. hasDefineEmitCall = true;
  31396. emitsRuntimeDecl = node.arguments[0];
  31397. if (node.typeParameters) {
  31398. if (emitsRuntimeDecl) {
  31399. error(`${DEFINE_EMITS}() cannot accept both type and non-type arguments ` +
  31400. `at the same time. Use one or the other.`, node);
  31401. }
  31402. emitsTypeDeclRaw = node.typeParameters.params[0];
  31403. emitsTypeDecl = resolveQualifiedType(emitsTypeDeclRaw, node => node.type === 'TSFunctionType' || node.type === 'TSTypeLiteral');
  31404. if (!emitsTypeDecl) {
  31405. error(`type argument passed to ${DEFINE_EMITS}() must be a function type, ` +
  31406. `a literal type with call signatures, or a reference to the above types.`, emitsTypeDeclRaw);
  31407. }
  31408. }
  31409. if (declId) {
  31410. emitIdentifier = scriptSetup.content.slice(declId.start, declId.end);
  31411. }
  31412. return true;
  31413. }
  31414. function resolveQualifiedType(node, qualifier) {
  31415. if (qualifier(node)) {
  31416. return node;
  31417. }
  31418. if (node.type === 'TSTypeReference' &&
  31419. node.typeName.type === 'Identifier') {
  31420. const refName = node.typeName.name;
  31421. const isQualifiedType = (node) => {
  31422. if (node.type === 'TSInterfaceDeclaration' &&
  31423. node.id.name === refName) {
  31424. return node.body;
  31425. }
  31426. else if (node.type === 'TSTypeAliasDeclaration' &&
  31427. node.id.name === refName &&
  31428. qualifier(node.typeAnnotation)) {
  31429. return node.typeAnnotation;
  31430. }
  31431. else if (node.type === 'ExportNamedDeclaration' && node.declaration) {
  31432. return isQualifiedType(node.declaration);
  31433. }
  31434. };
  31435. const body = scriptAst
  31436. ? [...scriptSetupAst.body, ...scriptAst.body]
  31437. : scriptSetupAst.body;
  31438. for (const node of body) {
  31439. const qualified = isQualifiedType(node);
  31440. if (qualified) {
  31441. return qualified;
  31442. }
  31443. }
  31444. }
  31445. }
  31446. function processDefineExpose(node) {
  31447. if (isCallOf(node, DEFINE_EXPOSE)) {
  31448. if (hasDefineExposeCall) {
  31449. error(`duplicate ${DEFINE_EXPOSE}() call`, node);
  31450. }
  31451. hasDefineExposeCall = true;
  31452. return true;
  31453. }
  31454. return false;
  31455. }
  31456. function checkInvalidScopeReference(node, method) {
  31457. if (!node)
  31458. return;
  31459. walkIdentifiers(node, id => {
  31460. if (setupBindings[id.name]) {
  31461. error(`\`${method}()\` in <script setup> cannot reference locally ` +
  31462. `declared variables because it will be hoisted outside of the ` +
  31463. `setup() function. If your component options require initialization ` +
  31464. `in the module scope, use a separate normal <script> to export ` +
  31465. `the options instead.`, id);
  31466. }
  31467. });
  31468. }
  31469. /**
  31470. * await foo()
  31471. * -->
  31472. * ;(
  31473. * ([__temp,__restore] = withAsyncContext(() => foo())),
  31474. * await __temp,
  31475. * __restore()
  31476. * )
  31477. *
  31478. * const a = await foo()
  31479. * -->
  31480. * const a = (
  31481. * ([__temp, __restore] = withAsyncContext(() => foo())),
  31482. * __temp = await __temp,
  31483. * __restore(),
  31484. * __temp
  31485. * )
  31486. */
  31487. function processAwait(node, needSemi, isStatement) {
  31488. const argumentStart = node.argument.extra && node.argument.extra.parenthesized
  31489. ? node.argument.extra.parenStart
  31490. : node.argument.start;
  31491. const argumentStr = source.slice(argumentStart + startOffset, node.argument.end + startOffset);
  31492. const containsNestedAwait = /\bawait\b/.test(argumentStr);
  31493. s.overwrite(node.start + startOffset, argumentStart + startOffset, `${needSemi ? `;` : ``}(\n ([__temp,__restore] = ${helper(`withAsyncContext`)}(${containsNestedAwait ? `async ` : ``}() => `);
  31494. s.appendLeft(node.end + startOffset, `)),\n ${isStatement ? `` : `__temp = `}await __temp,\n __restore()${isStatement ? `` : `,\n __temp`}\n)`);
  31495. }
  31496. /**
  31497. * check defaults. If the default object is an object literal with only
  31498. * static properties, we can directly generate more optimized default
  31499. * declarations. Otherwise we will have to fallback to runtime merging.
  31500. */
  31501. function hasStaticWithDefaults() {
  31502. return (propsRuntimeDefaults &&
  31503. propsRuntimeDefaults.type === 'ObjectExpression' &&
  31504. propsRuntimeDefaults.properties.every(node => (node.type === 'ObjectProperty' && !node.computed) ||
  31505. node.type === 'ObjectMethod'));
  31506. }
  31507. function genRuntimeProps(props) {
  31508. const keys = Object.keys(props);
  31509. if (!keys.length) {
  31510. return ``;
  31511. }
  31512. const hasStaticDefaults = hasStaticWithDefaults();
  31513. const scriptSetupSource = scriptSetup.content;
  31514. let propsDecls = `{
  31515. ${keys
  31516. .map(key => {
  31517. let defaultString;
  31518. const destructured = genDestructuredDefaultValue(key);
  31519. if (destructured) {
  31520. defaultString = `default: ${destructured}`;
  31521. }
  31522. else if (hasStaticDefaults) {
  31523. const prop = propsRuntimeDefaults.properties.find((node) => node.key.name === key);
  31524. if (prop) {
  31525. if (prop.type === 'ObjectProperty') {
  31526. // prop has corresponding static default value
  31527. defaultString = `default: ${scriptSetupSource.slice(prop.value.start, prop.value.end)}`;
  31528. }
  31529. else {
  31530. defaultString = `default() ${scriptSetupSource.slice(prop.body.start, prop.body.end)}`;
  31531. }
  31532. }
  31533. }
  31534. const { type, required } = props[key];
  31535. if (!isProd) {
  31536. return `${key}: { type: ${toRuntimeTypeString(type)}, required: ${required}${defaultString ? `, ${defaultString}` : ``} }`;
  31537. }
  31538. else if (type.some(el => el === 'Boolean' || (defaultString && el === 'Function'))) {
  31539. // #4783 production: if boolean or defaultString and function exists, should keep the type.
  31540. return `${key}: { type: ${toRuntimeTypeString(type)}${defaultString ? `, ${defaultString}` : ``} }`;
  31541. }
  31542. else {
  31543. // production: checks are useless
  31544. return `${key}: ${defaultString ? `{ ${defaultString} }` : 'null'}`;
  31545. }
  31546. })
  31547. .join(',\n ')}\n }`;
  31548. if (propsRuntimeDefaults && !hasStaticDefaults) {
  31549. propsDecls = `${helper('mergeDefaults')}(${propsDecls}, ${source.slice(propsRuntimeDefaults.start + startOffset, propsRuntimeDefaults.end + startOffset)})`;
  31550. }
  31551. return `\n props: ${propsDecls},`;
  31552. }
  31553. function genDestructuredDefaultValue(key) {
  31554. const destructured = propsDestructuredBindings[key];
  31555. if (destructured && destructured.default) {
  31556. const value = scriptSetup.content.slice(destructured.default.start, destructured.default.end);
  31557. const isLiteral = destructured.default.type.endsWith('Literal');
  31558. return isLiteral ? value : `() => ${value}`;
  31559. }
  31560. }
  31561. function genSetupPropsType(node) {
  31562. const scriptSetupSource = scriptSetup.content;
  31563. if (hasStaticWithDefaults()) {
  31564. // if withDefaults() is used, we need to remove the optional flags
  31565. // on props that have default values
  31566. let res = `{ `;
  31567. const members = node.type === 'TSTypeLiteral' ? node.members : node.body;
  31568. for (const m of members) {
  31569. if ((m.type === 'TSPropertySignature' ||
  31570. m.type === 'TSMethodSignature') &&
  31571. m.typeAnnotation &&
  31572. m.key.type === 'Identifier') {
  31573. if (propsRuntimeDefaults.properties.some((p) => p.key.name === m.key.name)) {
  31574. res +=
  31575. m.key.name +
  31576. (m.type === 'TSMethodSignature' ? '()' : '') +
  31577. scriptSetupSource.slice(m.typeAnnotation.start, m.typeAnnotation.end) +
  31578. ', ';
  31579. }
  31580. else {
  31581. res +=
  31582. scriptSetupSource.slice(m.start, m.typeAnnotation.end) + `, `;
  31583. }
  31584. }
  31585. }
  31586. return (res.length ? res.slice(0, -2) : res) + ` }`;
  31587. }
  31588. else {
  31589. return scriptSetupSource.slice(node.start, node.end);
  31590. }
  31591. }
  31592. // 1. process normal <script> first if it exists
  31593. let scriptAst;
  31594. if (script) {
  31595. scriptAst = parse(script.content, {
  31596. plugins,
  31597. sourceType: 'module'
  31598. }, scriptStartOffset);
  31599. for (const node of scriptAst.body) {
  31600. if (node.type === 'ImportDeclaration') {
  31601. // record imports for dedupe
  31602. for (const specifier of node.specifiers) {
  31603. const imported = specifier.type === 'ImportSpecifier' &&
  31604. specifier.imported.type === 'Identifier' &&
  31605. specifier.imported.name;
  31606. registerUserImport(node.source.value, specifier.local.name, imported, node.importKind === 'type', false);
  31607. }
  31608. }
  31609. else if (node.type === 'ExportDefaultDeclaration') {
  31610. // export default
  31611. defaultExport = node;
  31612. // export default { ... } --> const __default__ = { ... }
  31613. const start = node.start + scriptStartOffset;
  31614. const end = node.declaration.start + scriptStartOffset;
  31615. s.overwrite(start, end, `const ${DEFAULT_VAR} = `);
  31616. }
  31617. else if (node.type === 'ExportNamedDeclaration') {
  31618. const defaultSpecifier = node.specifiers.find(s => s.exported.type === 'Identifier' && s.exported.name === 'default');
  31619. if (defaultSpecifier) {
  31620. defaultExport = node;
  31621. // 1. remove specifier
  31622. if (node.specifiers.length > 1) {
  31623. s.remove(defaultSpecifier.start + scriptStartOffset, defaultSpecifier.end + scriptStartOffset);
  31624. }
  31625. else {
  31626. s.remove(node.start + scriptStartOffset, node.end + scriptStartOffset);
  31627. }
  31628. if (node.source) {
  31629. // export { x as default } from './x'
  31630. // rewrite to `import { x as __default__ } from './x'` and
  31631. // add to top
  31632. s.prepend(`import { ${defaultSpecifier.local.name} as ${DEFAULT_VAR} } from '${node.source.value}'\n`);
  31633. }
  31634. else {
  31635. // export { x as default }
  31636. // rewrite to `const __default__ = x` and move to end
  31637. s.appendLeft(scriptEndOffset, `\nconst ${DEFAULT_VAR} = ${defaultSpecifier.local.name}\n`);
  31638. }
  31639. }
  31640. if (node.declaration) {
  31641. walkDeclaration(node.declaration, scriptBindings, userImportAlias);
  31642. }
  31643. }
  31644. else if ((node.type === 'VariableDeclaration' ||
  31645. node.type === 'FunctionDeclaration' ||
  31646. node.type === 'ClassDeclaration' ||
  31647. node.type === 'TSEnumDeclaration') &&
  31648. !node.declare) {
  31649. walkDeclaration(node, scriptBindings, userImportAlias);
  31650. }
  31651. }
  31652. // apply ref transform
  31653. if (enableRefTransform && shouldTransform(script.content)) {
  31654. const { rootRefs: rootVars, importedHelpers } = transformAST(scriptAst, s, scriptStartOffset);
  31655. refBindings = rootVars;
  31656. for (const h of importedHelpers) {
  31657. helperImports.add(h);
  31658. }
  31659. }
  31660. // <script> after <script setup>
  31661. // we need to move the block up so that `const __default__` is
  31662. // declared before being used in the actual component definition
  31663. if (scriptStartOffset > startOffset) {
  31664. s.move(scriptStartOffset, scriptEndOffset, 0);
  31665. }
  31666. }
  31667. // 2. parse <script setup> and walk over top level statements
  31668. const scriptSetupAst = parse(scriptSetup.content, {
  31669. plugins: [
  31670. ...plugins,
  31671. // allow top level await but only inside <script setup>
  31672. 'topLevelAwait'
  31673. ],
  31674. sourceType: 'module'
  31675. }, startOffset);
  31676. for (const node of scriptSetupAst.body) {
  31677. const start = node.start + startOffset;
  31678. let end = node.end + startOffset;
  31679. // locate comment
  31680. if (node.trailingComments && node.trailingComments.length > 0) {
  31681. const lastCommentNode = node.trailingComments[node.trailingComments.length - 1];
  31682. end = lastCommentNode.end + startOffset;
  31683. }
  31684. // locate the end of whitespace between this statement and the next
  31685. while (end <= source.length) {
  31686. if (!/\s/.test(source.charAt(end))) {
  31687. break;
  31688. }
  31689. end++;
  31690. }
  31691. // (Dropped) `ref: x` bindings
  31692. if (node.type === 'LabeledStatement' &&
  31693. node.label.name === 'ref' &&
  31694. node.body.type === 'ExpressionStatement') {
  31695. error(`ref sugar using the label syntax was an experimental proposal and ` +
  31696. `has been dropped based on community feedback. Please check out ` +
  31697. `the new proposal at https://github.com/vuejs/rfcs/discussions/369`, node);
  31698. }
  31699. if (node.type === 'ImportDeclaration') {
  31700. // import declarations are moved to top
  31701. s.move(start, end, 0);
  31702. // dedupe imports
  31703. let removed = 0;
  31704. const removeSpecifier = (i) => {
  31705. const removeLeft = i > removed;
  31706. removed++;
  31707. const current = node.specifiers[i];
  31708. const next = node.specifiers[i + 1];
  31709. s.remove(removeLeft
  31710. ? node.specifiers[i - 1].end + startOffset
  31711. : current.start + startOffset, next && !removeLeft
  31712. ? next.start + startOffset
  31713. : current.end + startOffset);
  31714. };
  31715. for (let i = 0; i < node.specifiers.length; i++) {
  31716. const specifier = node.specifiers[i];
  31717. const local = specifier.local.name;
  31718. const imported = specifier.type === 'ImportSpecifier' &&
  31719. specifier.imported.type === 'Identifier' &&
  31720. specifier.imported.name;
  31721. const source = node.source.value;
  31722. const existing = userImports[local];
  31723. if (source === 'vue' &&
  31724. (imported === DEFINE_PROPS ||
  31725. imported === DEFINE_EMITS ||
  31726. imported === DEFINE_EXPOSE)) {
  31727. warnOnce(`\`${imported}\` is a compiler macro and no longer needs to be imported.`);
  31728. removeSpecifier(i);
  31729. }
  31730. else if (existing) {
  31731. if (existing.source === source && existing.imported === imported) {
  31732. // already imported in <script setup>, dedupe
  31733. removeSpecifier(i);
  31734. }
  31735. else {
  31736. error(`different imports aliased to same local name.`, specifier);
  31737. }
  31738. }
  31739. else {
  31740. registerUserImport(source, local, imported, node.importKind === 'type', true);
  31741. }
  31742. }
  31743. if (node.specifiers.length && removed === node.specifiers.length) {
  31744. s.remove(node.start + startOffset, node.end + startOffset);
  31745. }
  31746. }
  31747. if (node.type === 'ExpressionStatement') {
  31748. // process `defineProps` and `defineEmit(s)` calls
  31749. if (processDefineProps(node.expression) ||
  31750. processDefineEmits(node.expression) ||
  31751. processWithDefaults(node.expression)) {
  31752. s.remove(node.start + startOffset, node.end + startOffset);
  31753. }
  31754. else if (processDefineExpose(node.expression)) {
  31755. // defineExpose({}) -> expose({})
  31756. const callee = node.expression.callee;
  31757. s.overwrite(callee.start + startOffset, callee.end + startOffset, 'expose');
  31758. }
  31759. }
  31760. if (node.type === 'VariableDeclaration' && !node.declare) {
  31761. const total = node.declarations.length;
  31762. let left = total;
  31763. for (let i = 0; i < total; i++) {
  31764. const decl = node.declarations[i];
  31765. if (decl.init) {
  31766. // defineProps / defineEmits
  31767. const isDefineProps = processDefineProps(decl.init, decl.id) ||
  31768. processWithDefaults(decl.init, decl.id);
  31769. const isDefineEmits = processDefineEmits(decl.init, decl.id);
  31770. if (isDefineProps || isDefineEmits) {
  31771. if (left === 1) {
  31772. s.remove(node.start + startOffset, node.end + startOffset);
  31773. }
  31774. else {
  31775. let start = decl.start + startOffset;
  31776. let end = decl.end + startOffset;
  31777. if (i < total - 1) {
  31778. // not the last one, locate the start of the next
  31779. end = node.declarations[i + 1].start + startOffset;
  31780. }
  31781. else {
  31782. // last one, locate the end of the prev
  31783. start = node.declarations[i - 1].end + startOffset;
  31784. }
  31785. s.remove(start, end);
  31786. left--;
  31787. }
  31788. }
  31789. }
  31790. }
  31791. }
  31792. // walk declarations to record declared bindings
  31793. if ((node.type === 'VariableDeclaration' ||
  31794. node.type === 'FunctionDeclaration' ||
  31795. node.type === 'ClassDeclaration') &&
  31796. !node.declare) {
  31797. walkDeclaration(node, setupBindings, userImportAlias);
  31798. }
  31799. // walk statements & named exports / variable declarations for top level
  31800. // await
  31801. if ((node.type === 'VariableDeclaration' && !node.declare) ||
  31802. node.type.endsWith('Statement')) {
  31803. walk$1(node, {
  31804. enter(child, parent) {
  31805. if (isFunctionType(child)) {
  31806. this.skip();
  31807. }
  31808. if (child.type === 'AwaitExpression') {
  31809. hasAwait = true;
  31810. const needsSemi = scriptSetupAst.body.some(n => {
  31811. return n.type === 'ExpressionStatement' && n.start === child.start;
  31812. });
  31813. processAwait(child, needsSemi, parent.type === 'ExpressionStatement');
  31814. }
  31815. }
  31816. });
  31817. }
  31818. if ((node.type === 'ExportNamedDeclaration' && node.exportKind !== 'type') ||
  31819. node.type === 'ExportAllDeclaration' ||
  31820. node.type === 'ExportDefaultDeclaration') {
  31821. error(`<script setup> cannot contain ES module exports. ` +
  31822. `If you are using a previous version of <script setup>, please ` +
  31823. `consult the updated RFC at https://github.com/vuejs/rfcs/pull/227.`, node);
  31824. }
  31825. if (isTS) {
  31826. // runtime enum
  31827. if (node.type === 'TSEnumDeclaration') {
  31828. registerBinding(setupBindings, node.id, "setup-const" /* SETUP_CONST */);
  31829. }
  31830. // move all Type declarations to outer scope
  31831. if (node.type.startsWith('TS') ||
  31832. (node.type === 'ExportNamedDeclaration' &&
  31833. node.exportKind === 'type') ||
  31834. (node.type === 'VariableDeclaration' && node.declare)) {
  31835. recordType(node, declaredTypes);
  31836. s.move(start, end, 0);
  31837. }
  31838. }
  31839. }
  31840. // 3. Apply ref sugar transform
  31841. if ((enableRefTransform && shouldTransform(scriptSetup.content)) ||
  31842. propsDestructureDecl) {
  31843. const { rootRefs, importedHelpers } = transformAST(scriptSetupAst, s, startOffset, refBindings, propsDestructuredBindings);
  31844. refBindings = refBindings ? [...refBindings, ...rootRefs] : rootRefs;
  31845. for (const h of importedHelpers) {
  31846. helperImports.add(h);
  31847. }
  31848. }
  31849. // 4. extract runtime props/emits code from setup context type
  31850. if (propsTypeDecl) {
  31851. extractRuntimeProps(propsTypeDecl, typeDeclaredProps, declaredTypes);
  31852. }
  31853. if (emitsTypeDecl) {
  31854. extractRuntimeEmits(emitsTypeDecl, typeDeclaredEmits);
  31855. }
  31856. // 5. check useOptions args to make sure it doesn't reference setup scope
  31857. // variables
  31858. checkInvalidScopeReference(propsRuntimeDecl, DEFINE_PROPS);
  31859. checkInvalidScopeReference(propsRuntimeDefaults, DEFINE_PROPS);
  31860. checkInvalidScopeReference(propsDestructureDecl, DEFINE_PROPS);
  31861. checkInvalidScopeReference(emitsRuntimeDecl, DEFINE_PROPS);
  31862. // 6. remove non-script content
  31863. if (script) {
  31864. if (startOffset < scriptStartOffset) {
  31865. // <script setup> before <script>
  31866. s.remove(0, startOffset);
  31867. s.remove(endOffset, scriptStartOffset);
  31868. s.remove(scriptEndOffset, source.length);
  31869. }
  31870. else {
  31871. // <script> before <script setup>
  31872. s.remove(0, scriptStartOffset);
  31873. s.remove(scriptEndOffset, startOffset);
  31874. s.remove(endOffset, source.length);
  31875. }
  31876. }
  31877. else {
  31878. // only <script setup>
  31879. s.remove(0, startOffset);
  31880. s.remove(endOffset, source.length);
  31881. }
  31882. // 7. analyze binding metadata
  31883. if (scriptAst) {
  31884. Object.assign(bindingMetadata, analyzeScriptBindings(scriptAst.body));
  31885. }
  31886. if (propsRuntimeDecl) {
  31887. for (const key of getObjectOrArrayExpressionKeys(propsRuntimeDecl)) {
  31888. bindingMetadata[key] = "props" /* PROPS */;
  31889. }
  31890. }
  31891. for (const key in typeDeclaredProps) {
  31892. bindingMetadata[key] = "props" /* PROPS */;
  31893. }
  31894. // props aliases
  31895. if (propsDestructureDecl) {
  31896. if (propsDestructureRestId) {
  31897. bindingMetadata[propsDestructureRestId] = "setup-const" /* SETUP_CONST */;
  31898. }
  31899. for (const key in propsDestructuredBindings) {
  31900. const { local } = propsDestructuredBindings[key];
  31901. if (local !== key) {
  31902. bindingMetadata[local] = "props-aliased" /* PROPS_ALIASED */;
  31903. (bindingMetadata.__propsAliases ||
  31904. (bindingMetadata.__propsAliases = {}))[local] = key;
  31905. }
  31906. }
  31907. }
  31908. for (const [key, { isType, imported, source }] of Object.entries(userImports)) {
  31909. if (isType)
  31910. continue;
  31911. bindingMetadata[key] =
  31912. (imported === 'default' && source.endsWith('.vue')) || source === 'vue'
  31913. ? "setup-const" /* SETUP_CONST */
  31914. : "setup-maybe-ref" /* SETUP_MAYBE_REF */;
  31915. }
  31916. for (const key in scriptBindings) {
  31917. bindingMetadata[key] = scriptBindings[key];
  31918. }
  31919. for (const key in setupBindings) {
  31920. bindingMetadata[key] = setupBindings[key];
  31921. }
  31922. // known ref bindings
  31923. if (refBindings) {
  31924. for (const key of refBindings) {
  31925. bindingMetadata[key] = "setup-ref" /* SETUP_REF */;
  31926. }
  31927. }
  31928. // 8. inject `useCssVars` calls
  31929. if (cssVars.length) {
  31930. helperImports.add(CSS_VARS_HELPER);
  31931. helperImports.add('unref');
  31932. s.prependRight(startOffset, `\n${genCssVarsCode(cssVars, bindingMetadata, scopeId, isProd)}\n`);
  31933. }
  31934. // 9. finalize setup() argument signature
  31935. let args = `__props`;
  31936. if (propsTypeDecl) {
  31937. // mark as any and only cast on assignment
  31938. // since the user defined complex types may be incompatible with the
  31939. // inferred type from generated runtime declarations
  31940. args += `: any`;
  31941. }
  31942. // inject user assignment of props
  31943. // we use a default __props so that template expressions referencing props
  31944. // can use it directly
  31945. if (propsIdentifier) {
  31946. s.prependLeft(startOffset, `\nconst ${propsIdentifier} = __props${propsTypeDecl ? ` as ${genSetupPropsType(propsTypeDecl)}` : ``}\n`);
  31947. }
  31948. if (propsDestructureRestId) {
  31949. s.prependLeft(startOffset, `\nconst ${propsDestructureRestId} = ${helper(`createPropsRestProxy`)}(__props, ${JSON.stringify(Object.keys(propsDestructuredBindings))})\n`);
  31950. }
  31951. // inject temp variables for async context preservation
  31952. if (hasAwait) {
  31953. const any = isTS ? `: any` : ``;
  31954. s.prependLeft(startOffset, `\nlet __temp${any}, __restore${any}\n`);
  31955. }
  31956. const destructureElements = hasDefineExposeCall || !options.inlineTemplate ? [`expose`] : [];
  31957. if (emitIdentifier) {
  31958. destructureElements.push(emitIdentifier === `emit` ? `emit` : `emit: ${emitIdentifier}`);
  31959. }
  31960. if (destructureElements.length) {
  31961. args += `, { ${destructureElements.join(', ')} }`;
  31962. if (emitsTypeDecl) {
  31963. args += `: { emit: (${scriptSetup.content.slice(emitsTypeDecl.start, emitsTypeDecl.end)}), expose: any, slots: any, attrs: any }`;
  31964. }
  31965. }
  31966. // 10. generate return statement
  31967. let returned;
  31968. if (options.inlineTemplate) {
  31969. if (sfc.template && !sfc.template.src) {
  31970. if (options.templateOptions && options.templateOptions.ssr) {
  31971. hasInlinedSsrRenderFn = true;
  31972. }
  31973. // inline render function mode - we are going to compile the template and
  31974. // inline it right here
  31975. 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 &&
  31976. options.templateOptions.compilerOptions)), { inline: true, isTS,
  31977. bindingMetadata }) }));
  31978. if (tips.length) {
  31979. tips.forEach(warnOnce);
  31980. }
  31981. const err = errors[0];
  31982. if (typeof err === 'string') {
  31983. throw new Error(err);
  31984. }
  31985. else if (err) {
  31986. if (err.loc) {
  31987. err.message +=
  31988. `\n\n` +
  31989. sfc.filename +
  31990. '\n' +
  31991. generateCodeFrame(source, err.loc.start.offset, err.loc.end.offset) +
  31992. `\n`;
  31993. }
  31994. throw err;
  31995. }
  31996. if (preamble) {
  31997. s.prepend(preamble);
  31998. }
  31999. // avoid duplicated unref import
  32000. // as this may get injected by the render function preamble OR the
  32001. // css vars codegen
  32002. if (ast && ast.helpers.includes(UNREF)) {
  32003. helperImports.delete('unref');
  32004. }
  32005. returned = code;
  32006. }
  32007. else {
  32008. returned = `() => {}`;
  32009. }
  32010. }
  32011. else {
  32012. // return bindings from script and script setup
  32013. const allBindings = Object.assign(Object.assign({}, scriptBindings), setupBindings);
  32014. for (const key in userImports) {
  32015. if (!userImports[key].isType && userImports[key].isUsedInTemplate) {
  32016. allBindings[key] = true;
  32017. }
  32018. }
  32019. returned = `{ ${Object.keys(allBindings).join(', ')} }`;
  32020. }
  32021. if (!options.inlineTemplate && !false) {
  32022. // in non-inline mode, the `__isScriptSetup: true` flag is used by
  32023. // componentPublicInstance proxy to allow properties that start with $ or _
  32024. s.appendRight(endOffset, `\nconst __returned__ = ${returned}\n` +
  32025. `Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })\n` +
  32026. `return __returned__` +
  32027. `\n}\n\n`);
  32028. }
  32029. else {
  32030. s.appendRight(endOffset, `\nreturn ${returned}\n}\n\n`);
  32031. }
  32032. // 11. finalize default export
  32033. let runtimeOptions = ``;
  32034. if (hasInlinedSsrRenderFn) {
  32035. runtimeOptions += `\n __ssrInlineRender: true,`;
  32036. }
  32037. if (propsRuntimeDecl) {
  32038. let declCode = scriptSetup.content
  32039. .slice(propsRuntimeDecl.start, propsRuntimeDecl.end)
  32040. .trim();
  32041. if (propsDestructureDecl) {
  32042. const defaults = [];
  32043. for (const key in propsDestructuredBindings) {
  32044. const d = genDestructuredDefaultValue(key);
  32045. if (d)
  32046. defaults.push(`${key}: ${d}`);
  32047. }
  32048. if (defaults.length) {
  32049. declCode = `${helper(`mergeDefaults`)}(${declCode}, {\n ${defaults.join(',\n ')}\n})`;
  32050. }
  32051. }
  32052. runtimeOptions += `\n props: ${declCode},`;
  32053. }
  32054. else if (propsTypeDecl) {
  32055. runtimeOptions += genRuntimeProps(typeDeclaredProps);
  32056. }
  32057. if (emitsRuntimeDecl) {
  32058. runtimeOptions += `\n emits: ${scriptSetup.content
  32059. .slice(emitsRuntimeDecl.start, emitsRuntimeDecl.end)
  32060. .trim()},`;
  32061. }
  32062. else if (emitsTypeDecl) {
  32063. runtimeOptions += genRuntimeEmits(typeDeclaredEmits);
  32064. }
  32065. // <script setup> components are closed by default. If the user did not
  32066. // explicitly call `defineExpose`, call expose() with no args.
  32067. const exposeCall = hasDefineExposeCall || options.inlineTemplate ? `` : ` expose();\n`;
  32068. // wrap setup code with function.
  32069. if (isTS) {
  32070. // for TS, make sure the exported type is still valid type with
  32071. // correct props information
  32072. // we have to use object spread for types to be merged properly
  32073. // user's TS setting should compile it down to proper targets
  32074. // export default defineComponent({ ...__default__, ... })
  32075. const def = defaultExport ? `\n ...${DEFAULT_VAR},` : ``;
  32076. s.prependLeft(startOffset, `\nexport default /*#__PURE__*/${helper(`defineComponent`)}({${def}${runtimeOptions}\n ${hasAwait ? `async ` : ``}setup(${args}) {\n${exposeCall}`);
  32077. s.appendRight(endOffset, `})`);
  32078. }
  32079. else {
  32080. if (defaultExport) {
  32081. // without TS, can't rely on rest spread, so we use Object.assign
  32082. // export default Object.assign(__default__, { ... })
  32083. s.prependLeft(startOffset, `\nexport default /*#__PURE__*/Object.assign(${DEFAULT_VAR}, {${runtimeOptions}\n ` +
  32084. `${hasAwait ? `async ` : ``}setup(${args}) {\n${exposeCall}`);
  32085. s.appendRight(endOffset, `})`);
  32086. }
  32087. else {
  32088. s.prependLeft(startOffset, `\nexport default {${runtimeOptions}\n ` +
  32089. `${hasAwait ? `async ` : ``}setup(${args}) {\n${exposeCall}`);
  32090. s.appendRight(endOffset, `}`);
  32091. }
  32092. }
  32093. // 12. finalize Vue helper imports
  32094. if (helperImports.size > 0) {
  32095. s.prepend(`import { ${[...helperImports]
  32096. .map(h => `${h} as _${h}`)
  32097. .join(', ')} } from 'vue'\n`);
  32098. }
  32099. s.trim();
  32100. return Object.assign(Object.assign({}, scriptSetup), { bindings: bindingMetadata, imports: userImports, content: s.toString(), map: genSourceMap
  32101. ? s.generateMap({
  32102. source: filename,
  32103. hires: true,
  32104. includeContent: true
  32105. })
  32106. : undefined, scriptAst: scriptAst === null || scriptAst === void 0 ? void 0 : scriptAst.body, scriptSetupAst: scriptSetupAst === null || scriptSetupAst === void 0 ? void 0 : scriptSetupAst.body });
  32107. }
  32108. function registerBinding(bindings, node, type) {
  32109. bindings[node.name] = type;
  32110. }
  32111. function walkDeclaration(node, bindings, userImportAlias) {
  32112. if (node.type === 'VariableDeclaration') {
  32113. const isConst = node.kind === 'const';
  32114. // export const foo = ...
  32115. for (const { id, init } of node.declarations) {
  32116. const isDefineCall = !!(isConst &&
  32117. isCallOf(init, c => c === DEFINE_PROPS || c === DEFINE_EMITS || c === WITH_DEFAULTS));
  32118. if (id.type === 'Identifier') {
  32119. let bindingType;
  32120. const userReactiveBinding = userImportAlias['reactive'] || 'reactive';
  32121. if (isCallOf(init, userReactiveBinding)) {
  32122. // treat reactive() calls as let since it's meant to be mutable
  32123. bindingType = "setup-let" /* SETUP_LET */;
  32124. }
  32125. else if (
  32126. // if a declaration is a const literal, we can mark it so that
  32127. // the generated render fn code doesn't need to unref() it
  32128. isDefineCall ||
  32129. (isConst && canNeverBeRef(init, userReactiveBinding))) {
  32130. bindingType = "setup-const" /* SETUP_CONST */;
  32131. }
  32132. else if (isConst) {
  32133. if (isCallOf(init, userImportAlias['ref'] || 'ref')) {
  32134. bindingType = "setup-ref" /* SETUP_REF */;
  32135. }
  32136. else {
  32137. bindingType = "setup-maybe-ref" /* SETUP_MAYBE_REF */;
  32138. }
  32139. }
  32140. else {
  32141. bindingType = "setup-let" /* SETUP_LET */;
  32142. }
  32143. registerBinding(bindings, id, bindingType);
  32144. }
  32145. else {
  32146. if (isCallOf(init, DEFINE_PROPS)) {
  32147. // skip walking props destructure
  32148. return;
  32149. }
  32150. if (id.type === 'ObjectPattern') {
  32151. walkObjectPattern(id, bindings, isConst, isDefineCall);
  32152. }
  32153. else if (id.type === 'ArrayPattern') {
  32154. walkArrayPattern(id, bindings, isConst, isDefineCall);
  32155. }
  32156. }
  32157. }
  32158. }
  32159. else if (node.type === 'TSEnumDeclaration' ||
  32160. node.type === 'FunctionDeclaration' ||
  32161. node.type === 'ClassDeclaration') {
  32162. // export function foo() {} / export class Foo {}
  32163. // export declarations must be named.
  32164. bindings[node.id.name] = "setup-const" /* SETUP_CONST */;
  32165. }
  32166. }
  32167. function walkObjectPattern(node, bindings, isConst, isDefineCall = false) {
  32168. for (const p of node.properties) {
  32169. if (p.type === 'ObjectProperty') {
  32170. if (p.key.type === 'Identifier' && p.key === p.value) {
  32171. // shorthand: const { x } = ...
  32172. const type = isDefineCall
  32173. ? "setup-const" /* SETUP_CONST */
  32174. : isConst
  32175. ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
  32176. : "setup-let" /* SETUP_LET */;
  32177. registerBinding(bindings, p.key, type);
  32178. }
  32179. else {
  32180. walkPattern(p.value, bindings, isConst, isDefineCall);
  32181. }
  32182. }
  32183. else {
  32184. // ...rest
  32185. // argument can only be identifier when destructuring
  32186. const type = isConst ? "setup-const" /* SETUP_CONST */ : "setup-let" /* SETUP_LET */;
  32187. registerBinding(bindings, p.argument, type);
  32188. }
  32189. }
  32190. }
  32191. function walkArrayPattern(node, bindings, isConst, isDefineCall = false) {
  32192. for (const e of node.elements) {
  32193. e && walkPattern(e, bindings, isConst, isDefineCall);
  32194. }
  32195. }
  32196. function walkPattern(node, bindings, isConst, isDefineCall = false) {
  32197. if (node.type === 'Identifier') {
  32198. const type = isDefineCall
  32199. ? "setup-const" /* SETUP_CONST */
  32200. : isConst
  32201. ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
  32202. : "setup-let" /* SETUP_LET */;
  32203. registerBinding(bindings, node, type);
  32204. }
  32205. else if (node.type === 'RestElement') {
  32206. // argument can only be identifier when destructuring
  32207. const type = isConst ? "setup-const" /* SETUP_CONST */ : "setup-let" /* SETUP_LET */;
  32208. registerBinding(bindings, node.argument, type);
  32209. }
  32210. else if (node.type === 'ObjectPattern') {
  32211. walkObjectPattern(node, bindings, isConst);
  32212. }
  32213. else if (node.type === 'ArrayPattern') {
  32214. walkArrayPattern(node, bindings, isConst);
  32215. }
  32216. else if (node.type === 'AssignmentPattern') {
  32217. if (node.left.type === 'Identifier') {
  32218. const type = isDefineCall
  32219. ? "setup-const" /* SETUP_CONST */
  32220. : isConst
  32221. ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
  32222. : "setup-let" /* SETUP_LET */;
  32223. registerBinding(bindings, node.left, type);
  32224. }
  32225. else {
  32226. walkPattern(node.left, bindings, isConst);
  32227. }
  32228. }
  32229. }
  32230. function recordType(node, declaredTypes) {
  32231. if (node.type === 'TSInterfaceDeclaration') {
  32232. declaredTypes[node.id.name] = [`Object`];
  32233. }
  32234. else if (node.type === 'TSTypeAliasDeclaration') {
  32235. declaredTypes[node.id.name] = inferRuntimeType(node.typeAnnotation, declaredTypes);
  32236. }
  32237. else if (node.type === 'ExportNamedDeclaration' && node.declaration) {
  32238. recordType(node.declaration, declaredTypes);
  32239. }
  32240. }
  32241. function extractRuntimeProps(node, props, declaredTypes, isProd) {
  32242. const members = node.type === 'TSTypeLiteral' ? node.members : node.body;
  32243. for (const m of members) {
  32244. if ((m.type === 'TSPropertySignature' || m.type === 'TSMethodSignature') &&
  32245. m.key.type === 'Identifier') {
  32246. let type;
  32247. if (m.type === 'TSMethodSignature') {
  32248. type = ['Function'];
  32249. }
  32250. else if (m.typeAnnotation) {
  32251. type = inferRuntimeType(m.typeAnnotation.typeAnnotation, declaredTypes);
  32252. }
  32253. props[m.key.name] = {
  32254. key: m.key.name,
  32255. required: !m.optional,
  32256. type: type || [`null`]
  32257. };
  32258. }
  32259. }
  32260. }
  32261. function inferRuntimeType(node, declaredTypes) {
  32262. switch (node.type) {
  32263. case 'TSStringKeyword':
  32264. return ['String'];
  32265. case 'TSNumberKeyword':
  32266. return ['Number'];
  32267. case 'TSBooleanKeyword':
  32268. return ['Boolean'];
  32269. case 'TSObjectKeyword':
  32270. return ['Object'];
  32271. case 'TSTypeLiteral':
  32272. // TODO (nice to have) generate runtime property validation
  32273. return ['Object'];
  32274. case 'TSFunctionType':
  32275. return ['Function'];
  32276. case 'TSArrayType':
  32277. case 'TSTupleType':
  32278. // TODO (nice to have) generate runtime element type/length checks
  32279. return ['Array'];
  32280. case 'TSLiteralType':
  32281. switch (node.literal.type) {
  32282. case 'StringLiteral':
  32283. return ['String'];
  32284. case 'BooleanLiteral':
  32285. return ['Boolean'];
  32286. case 'NumericLiteral':
  32287. case 'BigIntLiteral':
  32288. return ['Number'];
  32289. default:
  32290. return [`null`];
  32291. }
  32292. case 'TSTypeReference':
  32293. if (node.typeName.type === 'Identifier') {
  32294. if (declaredTypes[node.typeName.name]) {
  32295. return declaredTypes[node.typeName.name];
  32296. }
  32297. switch (node.typeName.name) {
  32298. case 'Array':
  32299. case 'Function':
  32300. case 'Object':
  32301. case 'Set':
  32302. case 'Map':
  32303. case 'WeakSet':
  32304. case 'WeakMap':
  32305. case 'Date':
  32306. return [node.typeName.name];
  32307. case 'Record':
  32308. case 'Partial':
  32309. case 'Readonly':
  32310. case 'Pick':
  32311. case 'Omit':
  32312. case 'Exclude':
  32313. case 'Extract':
  32314. case 'Required':
  32315. case 'InstanceType':
  32316. return ['Object'];
  32317. }
  32318. }
  32319. return [`null`];
  32320. case 'TSParenthesizedType':
  32321. return inferRuntimeType(node.typeAnnotation, declaredTypes);
  32322. case 'TSUnionType':
  32323. return [
  32324. ...new Set([].concat(...node.types.map(t => inferRuntimeType(t, declaredTypes))))
  32325. ];
  32326. case 'TSIntersectionType':
  32327. return ['Object'];
  32328. case 'TSSymbolKeyword':
  32329. return ['Symbol'];
  32330. default:
  32331. return [`null`]; // no runtime check
  32332. }
  32333. }
  32334. function toRuntimeTypeString(types) {
  32335. return types.length > 1 ? `[${types.join(', ')}]` : types[0];
  32336. }
  32337. function extractRuntimeEmits(node, emits) {
  32338. if (node.type === 'TSTypeLiteral' || node.type === 'TSInterfaceBody') {
  32339. const members = node.type === 'TSTypeLiteral' ? node.members : node.body;
  32340. for (let t of members) {
  32341. if (t.type === 'TSCallSignatureDeclaration') {
  32342. extractEventNames(t.parameters[0], emits);
  32343. }
  32344. }
  32345. return;
  32346. }
  32347. else {
  32348. extractEventNames(node.parameters[0], emits);
  32349. }
  32350. }
  32351. function extractEventNames(eventName, emits) {
  32352. if (eventName.type === 'Identifier' &&
  32353. eventName.typeAnnotation &&
  32354. eventName.typeAnnotation.type === 'TSTypeAnnotation') {
  32355. const typeNode = eventName.typeAnnotation.typeAnnotation;
  32356. if (typeNode.type === 'TSLiteralType') {
  32357. if (typeNode.literal.type !== 'UnaryExpression') {
  32358. emits.add(String(typeNode.literal.value));
  32359. }
  32360. }
  32361. else if (typeNode.type === 'TSUnionType') {
  32362. for (const t of typeNode.types) {
  32363. if (t.type === 'TSLiteralType' &&
  32364. t.literal.type !== 'UnaryExpression') {
  32365. emits.add(String(t.literal.value));
  32366. }
  32367. }
  32368. }
  32369. }
  32370. }
  32371. function genRuntimeEmits(emits) {
  32372. return emits.size
  32373. ? `\n emits: [${Array.from(emits)
  32374. .map(p => JSON.stringify(p))
  32375. .join(', ')}],`
  32376. : ``;
  32377. }
  32378. function isCallOf(node, test) {
  32379. return !!(node &&
  32380. node.type === 'CallExpression' &&
  32381. node.callee.type === 'Identifier' &&
  32382. (typeof test === 'string'
  32383. ? node.callee.name === test
  32384. : test(node.callee.name)));
  32385. }
  32386. function canNeverBeRef(node, userReactiveImport) {
  32387. if (isCallOf(node, userReactiveImport)) {
  32388. return true;
  32389. }
  32390. switch (node.type) {
  32391. case 'UnaryExpression':
  32392. case 'BinaryExpression':
  32393. case 'ArrayExpression':
  32394. case 'ObjectExpression':
  32395. case 'FunctionExpression':
  32396. case 'ArrowFunctionExpression':
  32397. case 'UpdateExpression':
  32398. case 'ClassExpression':
  32399. case 'TaggedTemplateExpression':
  32400. return true;
  32401. case 'SequenceExpression':
  32402. return canNeverBeRef(node.expressions[node.expressions.length - 1], userReactiveImport);
  32403. default:
  32404. if (node.type.endsWith('Literal')) {
  32405. return true;
  32406. }
  32407. return false;
  32408. }
  32409. }
  32410. /**
  32411. * Analyze bindings in normal `<script>`
  32412. * Note that `compileScriptSetup` already analyzes bindings as part of its
  32413. * compilation process so this should only be used on single `<script>` SFCs.
  32414. */
  32415. function analyzeScriptBindings(ast) {
  32416. for (const node of ast) {
  32417. if (node.type === 'ExportDefaultDeclaration' &&
  32418. node.declaration.type === 'ObjectExpression') {
  32419. return analyzeBindingsFromOptions(node.declaration);
  32420. }
  32421. }
  32422. return {};
  32423. }
  32424. function analyzeBindingsFromOptions(node) {
  32425. const bindings = {};
  32426. // #3270, #3275
  32427. // mark non-script-setup so we don't resolve components/directives from these
  32428. Object.defineProperty(bindings, '__isScriptSetup', {
  32429. enumerable: false,
  32430. value: false
  32431. });
  32432. for (const property of node.properties) {
  32433. if (property.type === 'ObjectProperty' &&
  32434. !property.computed &&
  32435. property.key.type === 'Identifier') {
  32436. // props
  32437. if (property.key.name === 'props') {
  32438. // props: ['foo']
  32439. // props: { foo: ... }
  32440. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  32441. bindings[key] = "props" /* PROPS */;
  32442. }
  32443. }
  32444. // inject
  32445. else if (property.key.name === 'inject') {
  32446. // inject: ['foo']
  32447. // inject: { foo: {} }
  32448. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  32449. bindings[key] = "options" /* OPTIONS */;
  32450. }
  32451. }
  32452. // computed & methods
  32453. else if (property.value.type === 'ObjectExpression' &&
  32454. (property.key.name === 'computed' || property.key.name === 'methods')) {
  32455. // methods: { foo() {} }
  32456. // computed: { foo() {} }
  32457. for (const key of getObjectExpressionKeys(property.value)) {
  32458. bindings[key] = "options" /* OPTIONS */;
  32459. }
  32460. }
  32461. }
  32462. // setup & data
  32463. else if (property.type === 'ObjectMethod' &&
  32464. property.key.type === 'Identifier' &&
  32465. (property.key.name === 'setup' || property.key.name === 'data')) {
  32466. for (const bodyItem of property.body.body) {
  32467. // setup() {
  32468. // return {
  32469. // foo: null
  32470. // }
  32471. // }
  32472. if (bodyItem.type === 'ReturnStatement' &&
  32473. bodyItem.argument &&
  32474. bodyItem.argument.type === 'ObjectExpression') {
  32475. for (const key of getObjectExpressionKeys(bodyItem.argument)) {
  32476. bindings[key] =
  32477. property.key.name === 'setup'
  32478. ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
  32479. : "data" /* DATA */;
  32480. }
  32481. }
  32482. }
  32483. }
  32484. }
  32485. return bindings;
  32486. }
  32487. function getObjectExpressionKeys(node) {
  32488. const keys = [];
  32489. for (const prop of node.properties) {
  32490. if ((prop.type === 'ObjectProperty' || prop.type === 'ObjectMethod') &&
  32491. !prop.computed) {
  32492. if (prop.key.type === 'Identifier') {
  32493. keys.push(prop.key.name);
  32494. }
  32495. else if (prop.key.type === 'StringLiteral') {
  32496. keys.push(prop.key.value);
  32497. }
  32498. }
  32499. }
  32500. return keys;
  32501. }
  32502. function getArrayExpressionKeys(node) {
  32503. const keys = [];
  32504. for (const element of node.elements) {
  32505. if (element && element.type === 'StringLiteral') {
  32506. keys.push(element.value);
  32507. }
  32508. }
  32509. return keys;
  32510. }
  32511. function getObjectOrArrayExpressionKeys(value) {
  32512. if (value.type === 'ArrayExpression') {
  32513. return getArrayExpressionKeys(value);
  32514. }
  32515. if (value.type === 'ObjectExpression') {
  32516. return getObjectExpressionKeys(value);
  32517. }
  32518. return [];
  32519. }
  32520. const templateUsageCheckCache = createCache();
  32521. function resolveTemplateUsageCheckString(sfc) {
  32522. const { content, ast } = sfc.template;
  32523. const cached = templateUsageCheckCache.get(content);
  32524. if (cached) {
  32525. return cached;
  32526. }
  32527. let code = '';
  32528. transform(createRoot([ast]), {
  32529. nodeTransforms: [
  32530. node => {
  32531. if (node.type === 1 /* ELEMENT */) {
  32532. if (!parserOptions.isNativeTag(node.tag) &&
  32533. !parserOptions.isBuiltInComponent(node.tag)) {
  32534. code += `,${camelize(node.tag)},${capitalize(camelize(node.tag))}`;
  32535. }
  32536. for (let i = 0; i < node.props.length; i++) {
  32537. const prop = node.props[i];
  32538. if (prop.type === 7 /* DIRECTIVE */) {
  32539. if (!isBuiltInDir(prop.name)) {
  32540. code += `,v${capitalize(camelize(prop.name))}`;
  32541. }
  32542. if (prop.exp) {
  32543. code += `,${stripStrings(prop.exp.content)}`;
  32544. }
  32545. }
  32546. }
  32547. }
  32548. else if (node.type === 5 /* INTERPOLATION */) {
  32549. code += `,${stripStrings(node.content.content)}`;
  32550. }
  32551. }
  32552. ]
  32553. });
  32554. code += ';';
  32555. templateUsageCheckCache.set(content, code);
  32556. return code;
  32557. }
  32558. function stripStrings(exp) {
  32559. return exp
  32560. .replace(/'[^']*'|"[^"]*"/g, '')
  32561. .replace(/`[^`]+`/g, stripTemplateString);
  32562. }
  32563. function stripTemplateString(str) {
  32564. const interpMatch = str.match(/\${[^}]+}/g);
  32565. if (interpMatch) {
  32566. return interpMatch.map(m => m.slice(2, -1)).join(',');
  32567. }
  32568. return '';
  32569. }
  32570. function isImportUsed(local, sfc) {
  32571. return new RegExp(
  32572. // #4274 escape $ since it's a special char in regex
  32573. // (and is the only regex special char that is valid in identifiers)
  32574. `[^\\w$_]${local.replace(/\$/g, '\\$')}[^\\w$_]`).test(resolveTemplateUsageCheckString(sfc));
  32575. }
  32576. /**
  32577. * Note: this comparison assumes the prev/next script are already identical,
  32578. * and only checks the special case where <script setup lang="ts"> unused import
  32579. * pruning result changes due to template changes.
  32580. */
  32581. function hmrShouldReload(prevImports, next) {
  32582. if (!next.scriptSetup ||
  32583. (next.scriptSetup.lang !== 'ts' && next.scriptSetup.lang !== 'tsx')) {
  32584. return false;
  32585. }
  32586. // for each previous import, check if its used status remain the same based on
  32587. // the next descriptor's template
  32588. for (const key in prevImports) {
  32589. // if an import was previous unused, but now is used, we need to force
  32590. // reload so that the script now includes that import.
  32591. if (!prevImports[key].isUsedInTemplate && isImportUsed(key, next)) {
  32592. return true;
  32593. }
  32594. }
  32595. return false;
  32596. }
  32597. const sourceToSFC = createCache();
  32598. function parse$4(source, { sourceMap = true, filename = 'anonymous.vue', sourceRoot = '', pad = false, ignoreEmpty = true, compiler = CompilerDOM } = {}) {
  32599. const sourceKey = source + sourceMap + filename + sourceRoot + pad + compiler.parse;
  32600. const cache = sourceToSFC.get(sourceKey);
  32601. if (cache) {
  32602. return cache;
  32603. }
  32604. const descriptor = {
  32605. filename,
  32606. source,
  32607. template: null,
  32608. script: null,
  32609. scriptSetup: null,
  32610. styles: [],
  32611. customBlocks: [],
  32612. cssVars: [],
  32613. slotted: false,
  32614. shouldForceReload: prevImports => hmrShouldReload(prevImports, descriptor)
  32615. };
  32616. const errors = [];
  32617. const ast = compiler.parse(source, {
  32618. // there are no components at SFC parsing level
  32619. isNativeTag: () => true,
  32620. // preserve all whitespaces
  32621. isPreTag: () => true,
  32622. getTextMode: ({ tag, props }, parent) => {
  32623. // all top level elements except <template> are parsed as raw text
  32624. // containers
  32625. if ((!parent && tag !== 'template') ||
  32626. // <template lang="xxx"> should also be treated as raw text
  32627. (tag === 'template' &&
  32628. props.some(p => p.type === 6 /* ATTRIBUTE */ &&
  32629. p.name === 'lang' &&
  32630. p.value &&
  32631. p.value.content &&
  32632. p.value.content !== 'html'))) {
  32633. return 2 /* RAWTEXT */;
  32634. }
  32635. else {
  32636. return 0 /* DATA */;
  32637. }
  32638. },
  32639. onError: e => {
  32640. errors.push(e);
  32641. }
  32642. });
  32643. ast.children.forEach(node => {
  32644. if (node.type !== 1 /* ELEMENT */) {
  32645. return;
  32646. }
  32647. // we only want to keep the nodes that are not empty (when the tag is not a template)
  32648. if (ignoreEmpty &&
  32649. node.tag !== 'template' &&
  32650. isEmpty(node) &&
  32651. !hasSrc(node)) {
  32652. return;
  32653. }
  32654. switch (node.tag) {
  32655. case 'template':
  32656. if (!descriptor.template) {
  32657. const templateBlock = (descriptor.template = createBlock(node, source, false));
  32658. templateBlock.ast = node;
  32659. // warn against 2.x <template functional>
  32660. if (templateBlock.attrs.functional) {
  32661. const err = new SyntaxError(`<template functional> is no longer supported in Vue 3, since ` +
  32662. `functional components no longer have significant performance ` +
  32663. `difference from stateful ones. Just use a normal <template> ` +
  32664. `instead.`);
  32665. err.loc = node.props.find(p => p.name === 'functional').loc;
  32666. errors.push(err);
  32667. }
  32668. }
  32669. else {
  32670. errors.push(createDuplicateBlockError(node));
  32671. }
  32672. break;
  32673. case 'script':
  32674. const scriptBlock = createBlock(node, source, pad);
  32675. const isSetup = !!scriptBlock.attrs.setup;
  32676. if (isSetup && !descriptor.scriptSetup) {
  32677. descriptor.scriptSetup = scriptBlock;
  32678. break;
  32679. }
  32680. if (!isSetup && !descriptor.script) {
  32681. descriptor.script = scriptBlock;
  32682. break;
  32683. }
  32684. errors.push(createDuplicateBlockError(node, isSetup));
  32685. break;
  32686. case 'style':
  32687. const styleBlock = createBlock(node, source, pad);
  32688. if (styleBlock.attrs.vars) {
  32689. errors.push(new SyntaxError(`<style vars> has been replaced by a new proposal: ` +
  32690. `https://github.com/vuejs/rfcs/pull/231`));
  32691. }
  32692. descriptor.styles.push(styleBlock);
  32693. break;
  32694. default:
  32695. descriptor.customBlocks.push(createBlock(node, source, pad));
  32696. break;
  32697. }
  32698. });
  32699. if (descriptor.scriptSetup) {
  32700. if (descriptor.scriptSetup.src) {
  32701. errors.push(new SyntaxError(`<script setup> cannot use the "src" attribute because ` +
  32702. `its syntax will be ambiguous outside of the component.`));
  32703. descriptor.scriptSetup = null;
  32704. }
  32705. if (descriptor.script && descriptor.script.src) {
  32706. errors.push(new SyntaxError(`<script> cannot use the "src" attribute when <script setup> is ` +
  32707. `also present because they must be processed together.`));
  32708. descriptor.script = null;
  32709. }
  32710. }
  32711. if (sourceMap) {
  32712. const genMap = (block) => {
  32713. if (block && !block.src) {
  32714. block.map = generateSourceMap(filename, source, block.content, sourceRoot, !pad || block.type === 'template' ? block.loc.start.line - 1 : 0);
  32715. }
  32716. };
  32717. genMap(descriptor.template);
  32718. genMap(descriptor.script);
  32719. descriptor.styles.forEach(genMap);
  32720. descriptor.customBlocks.forEach(genMap);
  32721. }
  32722. // parse CSS vars
  32723. descriptor.cssVars = parseCssVars(descriptor);
  32724. // check if the SFC uses :slotted
  32725. const slottedRE = /(?:::v-|:)slotted\(/;
  32726. descriptor.slotted = descriptor.styles.some(s => s.scoped && slottedRE.test(s.content));
  32727. const result = {
  32728. descriptor,
  32729. errors
  32730. };
  32731. sourceToSFC.set(sourceKey, result);
  32732. return result;
  32733. }
  32734. function createDuplicateBlockError(node, isScriptSetup = false) {
  32735. const err = new SyntaxError(`Single file component can contain only one <${node.tag}${isScriptSetup ? ` setup` : ``}> element`);
  32736. err.loc = node.loc;
  32737. return err;
  32738. }
  32739. function createBlock(node, source, pad) {
  32740. const type = node.tag;
  32741. let { start, end } = node.loc;
  32742. let content = '';
  32743. if (node.children.length) {
  32744. start = node.children[0].loc.start;
  32745. end = node.children[node.children.length - 1].loc.end;
  32746. content = source.slice(start.offset, end.offset);
  32747. }
  32748. else {
  32749. const offset = node.loc.source.indexOf(`</`);
  32750. if (offset > -1) {
  32751. start = {
  32752. line: start.line,
  32753. column: start.column + offset,
  32754. offset: start.offset + offset
  32755. };
  32756. }
  32757. end = Object.assign({}, start);
  32758. }
  32759. const loc = {
  32760. source: content,
  32761. start,
  32762. end
  32763. };
  32764. const attrs = {};
  32765. const block = {
  32766. type,
  32767. content,
  32768. loc,
  32769. attrs
  32770. };
  32771. if (pad) {
  32772. block.content = padContent(source, block, pad) + block.content;
  32773. }
  32774. node.props.forEach(p => {
  32775. if (p.type === 6 /* ATTRIBUTE */) {
  32776. attrs[p.name] = p.value ? p.value.content || true : true;
  32777. if (p.name === 'lang') {
  32778. block.lang = p.value && p.value.content;
  32779. }
  32780. else if (p.name === 'src') {
  32781. block.src = p.value && p.value.content;
  32782. }
  32783. else if (type === 'style') {
  32784. if (p.name === 'scoped') {
  32785. block.scoped = true;
  32786. }
  32787. else if (p.name === 'module') {
  32788. block.module = attrs[p.name];
  32789. }
  32790. }
  32791. else if (type === 'script' && p.name === 'setup') {
  32792. block.setup = attrs.setup;
  32793. }
  32794. }
  32795. });
  32796. return block;
  32797. }
  32798. const splitRE = /\r?\n/g;
  32799. const emptyRE = /^(?:\/\/)?\s*$/;
  32800. const replaceRE = /./g;
  32801. function generateSourceMap(filename, source, generated, sourceRoot, lineOffset) {
  32802. const map = new SourceMapGenerator$2({
  32803. file: filename.replace(/\\/g, '/'),
  32804. sourceRoot: sourceRoot.replace(/\\/g, '/')
  32805. });
  32806. map.setSourceContent(filename, source);
  32807. generated.split(splitRE).forEach((line, index) => {
  32808. if (!emptyRE.test(line)) {
  32809. const originalLine = index + 1 + lineOffset;
  32810. const generatedLine = index + 1;
  32811. for (let i = 0; i < line.length; i++) {
  32812. if (!/\s/.test(line[i])) {
  32813. map.addMapping({
  32814. source: filename,
  32815. original: {
  32816. line: originalLine,
  32817. column: i
  32818. },
  32819. generated: {
  32820. line: generatedLine,
  32821. column: i
  32822. }
  32823. });
  32824. }
  32825. }
  32826. }
  32827. });
  32828. return JSON.parse(map.toString());
  32829. }
  32830. function padContent(content, block, pad) {
  32831. content = content.slice(0, block.loc.start.offset);
  32832. if (pad === 'space') {
  32833. return content.replace(replaceRE, ' ');
  32834. }
  32835. else {
  32836. const offset = content.split(splitRE).length;
  32837. const padChar = block.type === 'script' && !block.lang ? '//\n' : '\n';
  32838. return Array(offset).join(padChar);
  32839. }
  32840. }
  32841. function hasSrc(node) {
  32842. return node.props.some(p => {
  32843. if (p.type !== 6 /* ATTRIBUTE */) {
  32844. return false;
  32845. }
  32846. return p.name === 'src';
  32847. });
  32848. }
  32849. /**
  32850. * Returns true if the node has no children
  32851. * once the empty text nodes (trimmed content) have been filtered out.
  32852. */
  32853. function isEmpty(node) {
  32854. for (let i = 0; i < node.children.length; i++) {
  32855. const child = node.children[i];
  32856. if (child.type !== 2 /* TEXT */ || child.content.trim() !== '') {
  32857. return false;
  32858. }
  32859. }
  32860. return true;
  32861. }
  32862. // MIT lisence
  32863. // from https://github.com/substack/tty-browserify/blob/1ba769a6429d242f36226538835b4034bf6b7886/index.js
  32864. function isatty() {
  32865. return false;
  32866. }
  32867. function ReadStream() {
  32868. throw new Error('tty.ReadStream is not implemented');
  32869. }
  32870. function WriteStream() {
  32871. throw new Error('tty.ReadStream is not implemented');
  32872. }
  32873. var _polyfillNode_tty = {
  32874. isatty: isatty,
  32875. ReadStream: ReadStream,
  32876. WriteStream: WriteStream
  32877. };
  32878. var _polyfillNode_tty$1 = /*#__PURE__*/Object.freeze({
  32879. __proto__: null,
  32880. isatty: isatty,
  32881. ReadStream: ReadStream,
  32882. WriteStream: WriteStream,
  32883. 'default': _polyfillNode_tty
  32884. });
  32885. var tty = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_tty$1);
  32886. let isColorSupported =
  32887. !("NO_COLOR" in ({}) || browser$1.argv.includes("--no-color")) &&
  32888. ("FORCE_COLOR" in ({}) ||
  32889. browser$1.argv.includes("--color") ||
  32890. "" === "win32" ||
  32891. (tty.isatty(1) && ({}).TERM !== "dumb") ||
  32892. "CI" in ({}));
  32893. let formatter =
  32894. (open, close, replace = open) =>
  32895. input => {
  32896. let string = "" + input;
  32897. let index = string.indexOf(close, open.length);
  32898. return ~index
  32899. ? open + replaceClose(string, close, replace, index) + close
  32900. : open + string + close
  32901. };
  32902. let replaceClose = (string, close, replace, index) => {
  32903. let start = string.substring(0, index) + replace;
  32904. let end = string.substring(index + close.length);
  32905. let nextIndex = end.indexOf(close);
  32906. return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end
  32907. };
  32908. let createColors = (enabled = isColorSupported) => ({
  32909. isColorSupported: enabled,
  32910. reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String,
  32911. bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String,
  32912. dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String,
  32913. italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String,
  32914. underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String,
  32915. inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String,
  32916. hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String,
  32917. strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String,
  32918. black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String,
  32919. red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String,
  32920. green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String,
  32921. yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String,
  32922. blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String,
  32923. magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String,
  32924. cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String,
  32925. white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String,
  32926. gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String,
  32927. bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String,
  32928. bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String,
  32929. bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String,
  32930. bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String,
  32931. bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String,
  32932. bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String,
  32933. bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String,
  32934. bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String,
  32935. });
  32936. var picocolors = createColors();
  32937. var createColors_1 = createColors;
  32938. picocolors.createColors = createColors_1;
  32939. const SINGLE_QUOTE = "'".charCodeAt(0);
  32940. const DOUBLE_QUOTE = '"'.charCodeAt(0);
  32941. const BACKSLASH = '\\'.charCodeAt(0);
  32942. const SLASH = '/'.charCodeAt(0);
  32943. const NEWLINE = '\n'.charCodeAt(0);
  32944. const SPACE = ' '.charCodeAt(0);
  32945. const FEED = '\f'.charCodeAt(0);
  32946. const TAB = '\t'.charCodeAt(0);
  32947. const CR = '\r'.charCodeAt(0);
  32948. const OPEN_SQUARE = '['.charCodeAt(0);
  32949. const CLOSE_SQUARE = ']'.charCodeAt(0);
  32950. const OPEN_PARENTHESES = '('.charCodeAt(0);
  32951. const CLOSE_PARENTHESES = ')'.charCodeAt(0);
  32952. const OPEN_CURLY = '{'.charCodeAt(0);
  32953. const CLOSE_CURLY = '}'.charCodeAt(0);
  32954. const SEMICOLON = ';'.charCodeAt(0);
  32955. const ASTERISK = '*'.charCodeAt(0);
  32956. const COLON = ':'.charCodeAt(0);
  32957. const AT = '@'.charCodeAt(0);
  32958. const RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g;
  32959. const RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g;
  32960. const RE_BAD_BRACKET = /.[\n"'(/\\]/;
  32961. const RE_HEX_ESCAPE = /[\da-f]/i;
  32962. var tokenize = function tokenizer(input, options = {}) {
  32963. let css = input.css.valueOf();
  32964. let ignore = options.ignoreErrors;
  32965. let code, next, quote, content, escape;
  32966. let escaped, escapePos, prev, n, currentToken;
  32967. let length = css.length;
  32968. let pos = 0;
  32969. let buffer = [];
  32970. let returned = [];
  32971. function position() {
  32972. return pos
  32973. }
  32974. function unclosed(what) {
  32975. throw input.error('Unclosed ' + what, pos)
  32976. }
  32977. function endOfFile() {
  32978. return returned.length === 0 && pos >= length
  32979. }
  32980. function nextToken(opts) {
  32981. if (returned.length) return returned.pop()
  32982. if (pos >= length) return
  32983. let ignoreUnclosed = opts ? opts.ignoreUnclosed : false;
  32984. code = css.charCodeAt(pos);
  32985. switch (code) {
  32986. case NEWLINE:
  32987. case SPACE:
  32988. case TAB:
  32989. case CR:
  32990. case FEED: {
  32991. next = pos;
  32992. do {
  32993. next += 1;
  32994. code = css.charCodeAt(next);
  32995. } while (
  32996. code === SPACE ||
  32997. code === NEWLINE ||
  32998. code === TAB ||
  32999. code === CR ||
  33000. code === FEED
  33001. )
  33002. currentToken = ['space', css.slice(pos, next)];
  33003. pos = next - 1;
  33004. break
  33005. }
  33006. case OPEN_SQUARE:
  33007. case CLOSE_SQUARE:
  33008. case OPEN_CURLY:
  33009. case CLOSE_CURLY:
  33010. case COLON:
  33011. case SEMICOLON:
  33012. case CLOSE_PARENTHESES: {
  33013. let controlChar = String.fromCharCode(code);
  33014. currentToken = [controlChar, controlChar, pos];
  33015. break
  33016. }
  33017. case OPEN_PARENTHESES: {
  33018. prev = buffer.length ? buffer.pop()[1] : '';
  33019. n = css.charCodeAt(pos + 1);
  33020. if (
  33021. prev === 'url' &&
  33022. n !== SINGLE_QUOTE &&
  33023. n !== DOUBLE_QUOTE &&
  33024. n !== SPACE &&
  33025. n !== NEWLINE &&
  33026. n !== TAB &&
  33027. n !== FEED &&
  33028. n !== CR
  33029. ) {
  33030. next = pos;
  33031. do {
  33032. escaped = false;
  33033. next = css.indexOf(')', next + 1);
  33034. if (next === -1) {
  33035. if (ignore || ignoreUnclosed) {
  33036. next = pos;
  33037. break
  33038. } else {
  33039. unclosed('bracket');
  33040. }
  33041. }
  33042. escapePos = next;
  33043. while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
  33044. escapePos -= 1;
  33045. escaped = !escaped;
  33046. }
  33047. } while (escaped)
  33048. currentToken = ['brackets', css.slice(pos, next + 1), pos, next];
  33049. pos = next;
  33050. } else {
  33051. next = css.indexOf(')', pos + 1);
  33052. content = css.slice(pos, next + 1);
  33053. if (next === -1 || RE_BAD_BRACKET.test(content)) {
  33054. currentToken = ['(', '(', pos];
  33055. } else {
  33056. currentToken = ['brackets', content, pos, next];
  33057. pos = next;
  33058. }
  33059. }
  33060. break
  33061. }
  33062. case SINGLE_QUOTE:
  33063. case DOUBLE_QUOTE: {
  33064. quote = code === SINGLE_QUOTE ? "'" : '"';
  33065. next = pos;
  33066. do {
  33067. escaped = false;
  33068. next = css.indexOf(quote, next + 1);
  33069. if (next === -1) {
  33070. if (ignore || ignoreUnclosed) {
  33071. next = pos + 1;
  33072. break
  33073. } else {
  33074. unclosed('string');
  33075. }
  33076. }
  33077. escapePos = next;
  33078. while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
  33079. escapePos -= 1;
  33080. escaped = !escaped;
  33081. }
  33082. } while (escaped)
  33083. currentToken = ['string', css.slice(pos, next + 1), pos, next];
  33084. pos = next;
  33085. break
  33086. }
  33087. case AT: {
  33088. RE_AT_END.lastIndex = pos + 1;
  33089. RE_AT_END.test(css);
  33090. if (RE_AT_END.lastIndex === 0) {
  33091. next = css.length - 1;
  33092. } else {
  33093. next = RE_AT_END.lastIndex - 2;
  33094. }
  33095. currentToken = ['at-word', css.slice(pos, next + 1), pos, next];
  33096. pos = next;
  33097. break
  33098. }
  33099. case BACKSLASH: {
  33100. next = pos;
  33101. escape = true;
  33102. while (css.charCodeAt(next + 1) === BACKSLASH) {
  33103. next += 1;
  33104. escape = !escape;
  33105. }
  33106. code = css.charCodeAt(next + 1);
  33107. if (
  33108. escape &&
  33109. code !== SLASH &&
  33110. code !== SPACE &&
  33111. code !== NEWLINE &&
  33112. code !== TAB &&
  33113. code !== CR &&
  33114. code !== FEED
  33115. ) {
  33116. next += 1;
  33117. if (RE_HEX_ESCAPE.test(css.charAt(next))) {
  33118. while (RE_HEX_ESCAPE.test(css.charAt(next + 1))) {
  33119. next += 1;
  33120. }
  33121. if (css.charCodeAt(next + 1) === SPACE) {
  33122. next += 1;
  33123. }
  33124. }
  33125. }
  33126. currentToken = ['word', css.slice(pos, next + 1), pos, next];
  33127. pos = next;
  33128. break
  33129. }
  33130. default: {
  33131. if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) {
  33132. next = css.indexOf('*/', pos + 2) + 1;
  33133. if (next === 0) {
  33134. if (ignore || ignoreUnclosed) {
  33135. next = css.length;
  33136. } else {
  33137. unclosed('comment');
  33138. }
  33139. }
  33140. currentToken = ['comment', css.slice(pos, next + 1), pos, next];
  33141. pos = next;
  33142. } else {
  33143. RE_WORD_END.lastIndex = pos + 1;
  33144. RE_WORD_END.test(css);
  33145. if (RE_WORD_END.lastIndex === 0) {
  33146. next = css.length - 1;
  33147. } else {
  33148. next = RE_WORD_END.lastIndex - 2;
  33149. }
  33150. currentToken = ['word', css.slice(pos, next + 1), pos, next];
  33151. buffer.push(currentToken);
  33152. pos = next;
  33153. }
  33154. break
  33155. }
  33156. }
  33157. pos++;
  33158. return currentToken
  33159. }
  33160. function back(token) {
  33161. returned.push(token);
  33162. }
  33163. return {
  33164. back,
  33165. nextToken,
  33166. endOfFile,
  33167. position
  33168. }
  33169. };
  33170. let Input;
  33171. function registerInput(dependant) {
  33172. Input = dependant;
  33173. }
  33174. const HIGHLIGHT_THEME = {
  33175. 'brackets': picocolors.cyan,
  33176. 'at-word': picocolors.cyan,
  33177. 'comment': picocolors.gray,
  33178. 'string': picocolors.green,
  33179. 'class': picocolors.yellow,
  33180. 'hash': picocolors.magenta,
  33181. 'call': picocolors.cyan,
  33182. '(': picocolors.cyan,
  33183. ')': picocolors.cyan,
  33184. '{': picocolors.yellow,
  33185. '}': picocolors.yellow,
  33186. '[': picocolors.yellow,
  33187. ']': picocolors.yellow,
  33188. ':': picocolors.yellow,
  33189. ';': picocolors.yellow
  33190. };
  33191. function getTokenType([type, value], processor) {
  33192. if (type === 'word') {
  33193. if (value[0] === '.') {
  33194. return 'class'
  33195. }
  33196. if (value[0] === '#') {
  33197. return 'hash'
  33198. }
  33199. }
  33200. if (!processor.endOfFile()) {
  33201. let next = processor.nextToken();
  33202. processor.back(next);
  33203. if (next[0] === 'brackets' || next[0] === '(') return 'call'
  33204. }
  33205. return type
  33206. }
  33207. function terminalHighlight(css) {
  33208. let processor = tokenize(new Input(css), { ignoreErrors: true });
  33209. let result = '';
  33210. while (!processor.endOfFile()) {
  33211. let token = processor.nextToken();
  33212. let color = HIGHLIGHT_THEME[getTokenType(token, processor)];
  33213. if (color) {
  33214. result += token[1]
  33215. .split(/\r?\n/)
  33216. .map(i => color(i))
  33217. .join('\n');
  33218. } else {
  33219. result += token[1];
  33220. }
  33221. }
  33222. return result
  33223. }
  33224. terminalHighlight.registerInput = registerInput;
  33225. var terminalHighlight_1 = terminalHighlight;
  33226. class CssSyntaxError extends Error {
  33227. constructor(message, line, column, source, file, plugin) {
  33228. super(message);
  33229. this.name = 'CssSyntaxError';
  33230. this.reason = message;
  33231. if (file) {
  33232. this.file = file;
  33233. }
  33234. if (source) {
  33235. this.source = source;
  33236. }
  33237. if (plugin) {
  33238. this.plugin = plugin;
  33239. }
  33240. if (typeof line !== 'undefined' && typeof column !== 'undefined') {
  33241. if (typeof line === 'number') {
  33242. this.line = line;
  33243. this.column = column;
  33244. } else {
  33245. this.line = line.line;
  33246. this.column = line.column;
  33247. this.endLine = column.line;
  33248. this.endColumn = column.column;
  33249. }
  33250. }
  33251. this.setMessage();
  33252. if (Error.captureStackTrace) {
  33253. Error.captureStackTrace(this, CssSyntaxError);
  33254. }
  33255. }
  33256. setMessage() {
  33257. this.message = this.plugin ? this.plugin + ': ' : '';
  33258. this.message += this.file ? this.file : '<css input>';
  33259. if (typeof this.line !== 'undefined') {
  33260. this.message += ':' + this.line + ':' + this.column;
  33261. }
  33262. this.message += ': ' + this.reason;
  33263. }
  33264. showSourceCode(color) {
  33265. if (!this.source) return ''
  33266. let css = this.source;
  33267. if (color == null) color = picocolors.isColorSupported;
  33268. if (terminalHighlight_1) {
  33269. if (color) css = terminalHighlight_1(css);
  33270. }
  33271. let lines = css.split(/\r?\n/);
  33272. let start = Math.max(this.line - 3, 0);
  33273. let end = Math.min(this.line + 2, lines.length);
  33274. let maxWidth = String(end).length;
  33275. let mark, aside;
  33276. if (color) {
  33277. let { bold, red, gray } = picocolors.createColors(true);
  33278. mark = text => bold(red(text));
  33279. aside = text => gray(text);
  33280. } else {
  33281. mark = aside = str => str;
  33282. }
  33283. return lines
  33284. .slice(start, end)
  33285. .map((line, index) => {
  33286. let number = start + 1 + index;
  33287. let gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | ';
  33288. if (number === this.line) {
  33289. let spacing =
  33290. aside(gutter.replace(/\d/g, ' ')) +
  33291. line.slice(0, this.column - 1).replace(/[^\t]/g, ' ');
  33292. return mark('>') + aside(gutter) + line + '\n ' + spacing + mark('^')
  33293. }
  33294. return ' ' + aside(gutter) + line
  33295. })
  33296. .join('\n')
  33297. }
  33298. toString() {
  33299. let code = this.showSourceCode();
  33300. if (code) {
  33301. code = '\n\n' + code + '\n';
  33302. }
  33303. return this.name + ': ' + this.message + code
  33304. }
  33305. }
  33306. var cssSyntaxError = CssSyntaxError;
  33307. CssSyntaxError.default = CssSyntaxError;
  33308. var isClean = Symbol('isClean');
  33309. var my = Symbol('my');
  33310. var symbols = {
  33311. isClean: isClean,
  33312. my: my
  33313. };
  33314. const DEFAULT_RAW = {
  33315. colon: ': ',
  33316. indent: ' ',
  33317. beforeDecl: '\n',
  33318. beforeRule: '\n',
  33319. beforeOpen: ' ',
  33320. beforeClose: '\n',
  33321. beforeComment: '\n',
  33322. after: '\n',
  33323. emptyBody: '',
  33324. commentLeft: ' ',
  33325. commentRight: ' ',
  33326. semicolon: false
  33327. };
  33328. function capitalize$1(str) {
  33329. return str[0].toUpperCase() + str.slice(1)
  33330. }
  33331. class Stringifier {
  33332. constructor(builder) {
  33333. this.builder = builder;
  33334. }
  33335. stringify(node, semicolon) {
  33336. /* c8 ignore start */
  33337. if (!this[node.type]) {
  33338. throw new Error(
  33339. 'Unknown AST node type ' +
  33340. node.type +
  33341. '. ' +
  33342. 'Maybe you need to change PostCSS stringifier.'
  33343. )
  33344. }
  33345. /* c8 ignore stop */
  33346. this[node.type](node, semicolon);
  33347. }
  33348. document(node) {
  33349. this.body(node);
  33350. }
  33351. root(node) {
  33352. this.body(node);
  33353. if (node.raws.after) this.builder(node.raws.after);
  33354. }
  33355. comment(node) {
  33356. let left = this.raw(node, 'left', 'commentLeft');
  33357. let right = this.raw(node, 'right', 'commentRight');
  33358. this.builder('/*' + left + node.text + right + '*/', node);
  33359. }
  33360. decl(node, semicolon) {
  33361. let between = this.raw(node, 'between', 'colon');
  33362. let string = node.prop + between + this.rawValue(node, 'value');
  33363. if (node.important) {
  33364. string += node.raws.important || ' !important';
  33365. }
  33366. if (semicolon) string += ';';
  33367. this.builder(string, node);
  33368. }
  33369. rule(node) {
  33370. this.block(node, this.rawValue(node, 'selector'));
  33371. if (node.raws.ownSemicolon) {
  33372. this.builder(node.raws.ownSemicolon, node, 'end');
  33373. }
  33374. }
  33375. atrule(node, semicolon) {
  33376. let name = '@' + node.name;
  33377. let params = node.params ? this.rawValue(node, 'params') : '';
  33378. if (typeof node.raws.afterName !== 'undefined') {
  33379. name += node.raws.afterName;
  33380. } else if (params) {
  33381. name += ' ';
  33382. }
  33383. if (node.nodes) {
  33384. this.block(node, name + params);
  33385. } else {
  33386. let end = (node.raws.between || '') + (semicolon ? ';' : '');
  33387. this.builder(name + params + end, node);
  33388. }
  33389. }
  33390. body(node) {
  33391. let last = node.nodes.length - 1;
  33392. while (last > 0) {
  33393. if (node.nodes[last].type !== 'comment') break
  33394. last -= 1;
  33395. }
  33396. let semicolon = this.raw(node, 'semicolon');
  33397. for (let i = 0; i < node.nodes.length; i++) {
  33398. let child = node.nodes[i];
  33399. let before = this.raw(child, 'before');
  33400. if (before) this.builder(before);
  33401. this.stringify(child, last !== i || semicolon);
  33402. }
  33403. }
  33404. block(node, start) {
  33405. let between = this.raw(node, 'between', 'beforeOpen');
  33406. this.builder(start + between + '{', node, 'start');
  33407. let after;
  33408. if (node.nodes && node.nodes.length) {
  33409. this.body(node);
  33410. after = this.raw(node, 'after');
  33411. } else {
  33412. after = this.raw(node, 'after', 'emptyBody');
  33413. }
  33414. if (after) this.builder(after);
  33415. this.builder('}', node, 'end');
  33416. }
  33417. raw(node, own, detect) {
  33418. let value;
  33419. if (!detect) detect = own;
  33420. // Already had
  33421. if (own) {
  33422. value = node.raws[own];
  33423. if (typeof value !== 'undefined') return value
  33424. }
  33425. let parent = node.parent;
  33426. if (detect === 'before') {
  33427. // Hack for first rule in CSS
  33428. if (!parent || (parent.type === 'root' && parent.first === node)) {
  33429. return ''
  33430. }
  33431. // `root` nodes in `document` should use only their own raws
  33432. if (parent && parent.type === 'document') {
  33433. return ''
  33434. }
  33435. }
  33436. // Floating child without parent
  33437. if (!parent) return DEFAULT_RAW[detect]
  33438. // Detect style by other nodes
  33439. let root = node.root();
  33440. if (!root.rawCache) root.rawCache = {};
  33441. if (typeof root.rawCache[detect] !== 'undefined') {
  33442. return root.rawCache[detect]
  33443. }
  33444. if (detect === 'before' || detect === 'after') {
  33445. return this.beforeAfter(node, detect)
  33446. } else {
  33447. let method = 'raw' + capitalize$1(detect);
  33448. if (this[method]) {
  33449. value = this[method](root, node);
  33450. } else {
  33451. root.walk(i => {
  33452. value = i.raws[own];
  33453. if (typeof value !== 'undefined') return false
  33454. });
  33455. }
  33456. }
  33457. if (typeof value === 'undefined') value = DEFAULT_RAW[detect];
  33458. root.rawCache[detect] = value;
  33459. return value
  33460. }
  33461. rawSemicolon(root) {
  33462. let value;
  33463. root.walk(i => {
  33464. if (i.nodes && i.nodes.length && i.last.type === 'decl') {
  33465. value = i.raws.semicolon;
  33466. if (typeof value !== 'undefined') return false
  33467. }
  33468. });
  33469. return value
  33470. }
  33471. rawEmptyBody(root) {
  33472. let value;
  33473. root.walk(i => {
  33474. if (i.nodes && i.nodes.length === 0) {
  33475. value = i.raws.after;
  33476. if (typeof value !== 'undefined') return false
  33477. }
  33478. });
  33479. return value
  33480. }
  33481. rawIndent(root) {
  33482. if (root.raws.indent) return root.raws.indent
  33483. let value;
  33484. root.walk(i => {
  33485. let p = i.parent;
  33486. if (p && p !== root && p.parent && p.parent === root) {
  33487. if (typeof i.raws.before !== 'undefined') {
  33488. let parts = i.raws.before.split('\n');
  33489. value = parts[parts.length - 1];
  33490. value = value.replace(/\S/g, '');
  33491. return false
  33492. }
  33493. }
  33494. });
  33495. return value
  33496. }
  33497. rawBeforeComment(root, node) {
  33498. let value;
  33499. root.walkComments(i => {
  33500. if (typeof i.raws.before !== 'undefined') {
  33501. value = i.raws.before;
  33502. if (value.includes('\n')) {
  33503. value = value.replace(/[^\n]+$/, '');
  33504. }
  33505. return false
  33506. }
  33507. });
  33508. if (typeof value === 'undefined') {
  33509. value = this.raw(node, null, 'beforeDecl');
  33510. } else if (value) {
  33511. value = value.replace(/\S/g, '');
  33512. }
  33513. return value
  33514. }
  33515. rawBeforeDecl(root, node) {
  33516. let value;
  33517. root.walkDecls(i => {
  33518. if (typeof i.raws.before !== 'undefined') {
  33519. value = i.raws.before;
  33520. if (value.includes('\n')) {
  33521. value = value.replace(/[^\n]+$/, '');
  33522. }
  33523. return false
  33524. }
  33525. });
  33526. if (typeof value === 'undefined') {
  33527. value = this.raw(node, null, 'beforeRule');
  33528. } else if (value) {
  33529. value = value.replace(/\S/g, '');
  33530. }
  33531. return value
  33532. }
  33533. rawBeforeRule(root) {
  33534. let value;
  33535. root.walk(i => {
  33536. if (i.nodes && (i.parent !== root || root.first !== i)) {
  33537. if (typeof i.raws.before !== 'undefined') {
  33538. value = i.raws.before;
  33539. if (value.includes('\n')) {
  33540. value = value.replace(/[^\n]+$/, '');
  33541. }
  33542. return false
  33543. }
  33544. }
  33545. });
  33546. if (value) value = value.replace(/\S/g, '');
  33547. return value
  33548. }
  33549. rawBeforeClose(root) {
  33550. let value;
  33551. root.walk(i => {
  33552. if (i.nodes && i.nodes.length > 0) {
  33553. if (typeof i.raws.after !== 'undefined') {
  33554. value = i.raws.after;
  33555. if (value.includes('\n')) {
  33556. value = value.replace(/[^\n]+$/, '');
  33557. }
  33558. return false
  33559. }
  33560. }
  33561. });
  33562. if (value) value = value.replace(/\S/g, '');
  33563. return value
  33564. }
  33565. rawBeforeOpen(root) {
  33566. let value;
  33567. root.walk(i => {
  33568. if (i.type !== 'decl') {
  33569. value = i.raws.between;
  33570. if (typeof value !== 'undefined') return false
  33571. }
  33572. });
  33573. return value
  33574. }
  33575. rawColon(root) {
  33576. let value;
  33577. root.walkDecls(i => {
  33578. if (typeof i.raws.between !== 'undefined') {
  33579. value = i.raws.between.replace(/[^\s:]/g, '');
  33580. return false
  33581. }
  33582. });
  33583. return value
  33584. }
  33585. beforeAfter(node, detect) {
  33586. let value;
  33587. if (node.type === 'decl') {
  33588. value = this.raw(node, null, 'beforeDecl');
  33589. } else if (node.type === 'comment') {
  33590. value = this.raw(node, null, 'beforeComment');
  33591. } else if (detect === 'before') {
  33592. value = this.raw(node, null, 'beforeRule');
  33593. } else {
  33594. value = this.raw(node, null, 'beforeClose');
  33595. }
  33596. let buf = node.parent;
  33597. let depth = 0;
  33598. while (buf && buf.type !== 'root') {
  33599. depth += 1;
  33600. buf = buf.parent;
  33601. }
  33602. if (value.includes('\n')) {
  33603. let indent = this.raw(node, null, 'indent');
  33604. if (indent.length) {
  33605. for (let step = 0; step < depth; step++) value += indent;
  33606. }
  33607. }
  33608. return value
  33609. }
  33610. rawValue(node, prop) {
  33611. let value = node[prop];
  33612. let raw = node.raws[prop];
  33613. if (raw && raw.value === value) {
  33614. return raw.raw
  33615. }
  33616. return value
  33617. }
  33618. }
  33619. var stringifier = Stringifier;
  33620. Stringifier.default = Stringifier;
  33621. function stringify$1(node, builder) {
  33622. let str = new stringifier(builder);
  33623. str.stringify(node);
  33624. }
  33625. var stringify_1 = stringify$1;
  33626. stringify$1.default = stringify$1;
  33627. let { isClean: isClean$1, my: my$1 } = symbols;
  33628. function cloneNode(obj, parent) {
  33629. let cloned = new obj.constructor();
  33630. for (let i in obj) {
  33631. if (!Object.prototype.hasOwnProperty.call(obj, i)) {
  33632. /* c8 ignore next 2 */
  33633. continue
  33634. }
  33635. if (i === 'proxyCache') continue
  33636. let value = obj[i];
  33637. let type = typeof value;
  33638. if (i === 'parent' && type === 'object') {
  33639. if (parent) cloned[i] = parent;
  33640. } else if (i === 'source') {
  33641. cloned[i] = value;
  33642. } else if (Array.isArray(value)) {
  33643. cloned[i] = value.map(j => cloneNode(j, cloned));
  33644. } else {
  33645. if (type === 'object' && value !== null) value = cloneNode(value);
  33646. cloned[i] = value;
  33647. }
  33648. }
  33649. return cloned
  33650. }
  33651. class Node$1 {
  33652. constructor(defaults = {}) {
  33653. this.raws = {};
  33654. this[isClean$1] = false;
  33655. this[my$1] = true;
  33656. for (let name in defaults) {
  33657. if (name === 'nodes') {
  33658. this.nodes = [];
  33659. for (let node of defaults[name]) {
  33660. if (typeof node.clone === 'function') {
  33661. this.append(node.clone());
  33662. } else {
  33663. this.append(node);
  33664. }
  33665. }
  33666. } else {
  33667. this[name] = defaults[name];
  33668. }
  33669. }
  33670. }
  33671. error(message, opts = {}) {
  33672. if (this.source) {
  33673. let { start, end } = this.rangeBy(opts);
  33674. return this.source.input.error(
  33675. message,
  33676. { line: start.line, column: start.column },
  33677. { line: end.line, column: end.column },
  33678. opts
  33679. )
  33680. }
  33681. return new cssSyntaxError(message)
  33682. }
  33683. warn(result, text, opts) {
  33684. let data = { node: this };
  33685. for (let i in opts) data[i] = opts[i];
  33686. return result.warn(text, data)
  33687. }
  33688. remove() {
  33689. if (this.parent) {
  33690. this.parent.removeChild(this);
  33691. }
  33692. this.parent = undefined;
  33693. return this
  33694. }
  33695. toString(stringifier = stringify_1) {
  33696. if (stringifier.stringify) stringifier = stringifier.stringify;
  33697. let result = '';
  33698. stringifier(this, i => {
  33699. result += i;
  33700. });
  33701. return result
  33702. }
  33703. assign(overrides = {}) {
  33704. for (let name in overrides) {
  33705. this[name] = overrides[name];
  33706. }
  33707. return this
  33708. }
  33709. clone(overrides = {}) {
  33710. let cloned = cloneNode(this);
  33711. for (let name in overrides) {
  33712. cloned[name] = overrides[name];
  33713. }
  33714. return cloned
  33715. }
  33716. cloneBefore(overrides = {}) {
  33717. let cloned = this.clone(overrides);
  33718. this.parent.insertBefore(this, cloned);
  33719. return cloned
  33720. }
  33721. cloneAfter(overrides = {}) {
  33722. let cloned = this.clone(overrides);
  33723. this.parent.insertAfter(this, cloned);
  33724. return cloned
  33725. }
  33726. replaceWith(...nodes) {
  33727. if (this.parent) {
  33728. let bookmark = this;
  33729. let foundSelf = false;
  33730. for (let node of nodes) {
  33731. if (node === this) {
  33732. foundSelf = true;
  33733. } else if (foundSelf) {
  33734. this.parent.insertAfter(bookmark, node);
  33735. bookmark = node;
  33736. } else {
  33737. this.parent.insertBefore(bookmark, node);
  33738. }
  33739. }
  33740. if (!foundSelf) {
  33741. this.remove();
  33742. }
  33743. }
  33744. return this
  33745. }
  33746. next() {
  33747. if (!this.parent) return undefined
  33748. let index = this.parent.index(this);
  33749. return this.parent.nodes[index + 1]
  33750. }
  33751. prev() {
  33752. if (!this.parent) return undefined
  33753. let index = this.parent.index(this);
  33754. return this.parent.nodes[index - 1]
  33755. }
  33756. before(add) {
  33757. this.parent.insertBefore(this, add);
  33758. return this
  33759. }
  33760. after(add) {
  33761. this.parent.insertAfter(this, add);
  33762. return this
  33763. }
  33764. root() {
  33765. let result = this;
  33766. while (result.parent && result.parent.type !== 'document') {
  33767. result = result.parent;
  33768. }
  33769. return result
  33770. }
  33771. raw(prop, defaultType) {
  33772. let str = new stringifier();
  33773. return str.raw(this, prop, defaultType)
  33774. }
  33775. cleanRaws(keepBetween) {
  33776. delete this.raws.before;
  33777. delete this.raws.after;
  33778. if (!keepBetween) delete this.raws.between;
  33779. }
  33780. toJSON(_, inputs) {
  33781. let fixed = {};
  33782. let emitInputs = inputs == null;
  33783. inputs = inputs || new Map();
  33784. let inputsNextIndex = 0;
  33785. for (let name in this) {
  33786. if (!Object.prototype.hasOwnProperty.call(this, name)) {
  33787. /* c8 ignore next 2 */
  33788. continue
  33789. }
  33790. if (name === 'parent' || name === 'proxyCache') continue
  33791. let value = this[name];
  33792. if (Array.isArray(value)) {
  33793. fixed[name] = value.map(i => {
  33794. if (typeof i === 'object' && i.toJSON) {
  33795. return i.toJSON(null, inputs)
  33796. } else {
  33797. return i
  33798. }
  33799. });
  33800. } else if (typeof value === 'object' && value.toJSON) {
  33801. fixed[name] = value.toJSON(null, inputs);
  33802. } else if (name === 'source') {
  33803. let inputId = inputs.get(value.input);
  33804. if (inputId == null) {
  33805. inputId = inputsNextIndex;
  33806. inputs.set(value.input, inputsNextIndex);
  33807. inputsNextIndex++;
  33808. }
  33809. fixed[name] = {
  33810. inputId,
  33811. start: value.start,
  33812. end: value.end
  33813. };
  33814. } else {
  33815. fixed[name] = value;
  33816. }
  33817. }
  33818. if (emitInputs) {
  33819. fixed.inputs = [...inputs.keys()].map(input => input.toJSON());
  33820. }
  33821. return fixed
  33822. }
  33823. positionInside(index) {
  33824. let string = this.toString();
  33825. let column = this.source.start.column;
  33826. let line = this.source.start.line;
  33827. for (let i = 0; i < index; i++) {
  33828. if (string[i] === '\n') {
  33829. column = 1;
  33830. line += 1;
  33831. } else {
  33832. column += 1;
  33833. }
  33834. }
  33835. return { line, column }
  33836. }
  33837. positionBy(opts) {
  33838. let pos = this.source.start;
  33839. if (opts.index) {
  33840. pos = this.positionInside(opts.index);
  33841. } else if (opts.word) {
  33842. let index = this.toString().indexOf(opts.word);
  33843. if (index !== -1) pos = this.positionInside(index);
  33844. }
  33845. return pos
  33846. }
  33847. rangeBy(opts) {
  33848. let start = {
  33849. line: this.source.start.line,
  33850. column: this.source.start.column
  33851. };
  33852. let end = this.source.end
  33853. ? {
  33854. line: this.source.end.line,
  33855. column: this.source.end.column + 1
  33856. }
  33857. : {
  33858. line: start.line,
  33859. column: start.column + 1
  33860. };
  33861. if (opts.word) {
  33862. let index = this.toString().indexOf(opts.word);
  33863. if (index !== -1) {
  33864. start = this.positionInside(index);
  33865. end = this.positionInside(index + opts.word.length);
  33866. }
  33867. } else {
  33868. if (opts.start) {
  33869. start = {
  33870. line: opts.start.line,
  33871. column: opts.start.column
  33872. };
  33873. } else if (opts.index) {
  33874. start = this.positionInside(opts.index);
  33875. }
  33876. if (opts.end) {
  33877. end = {
  33878. line: opts.end.line,
  33879. column: opts.end.column
  33880. };
  33881. } else if (opts.endIndex) {
  33882. end = this.positionInside(opts.endIndex);
  33883. } else if (opts.index) {
  33884. end = this.positionInside(opts.index + 1);
  33885. }
  33886. }
  33887. if (
  33888. end.line < start.line ||
  33889. (end.line === start.line && end.column <= start.column)
  33890. ) {
  33891. end = { line: start.line, column: start.column + 1 };
  33892. }
  33893. return { start, end }
  33894. }
  33895. getProxyProcessor() {
  33896. return {
  33897. set(node, prop, value) {
  33898. if (node[prop] === value) return true
  33899. node[prop] = value;
  33900. if (
  33901. prop === 'prop' ||
  33902. prop === 'value' ||
  33903. prop === 'name' ||
  33904. prop === 'params' ||
  33905. prop === 'important' ||
  33906. /* c8 ignore next */
  33907. prop === 'text'
  33908. ) {
  33909. node.markDirty();
  33910. }
  33911. return true
  33912. },
  33913. get(node, prop) {
  33914. if (prop === 'proxyOf') {
  33915. return node
  33916. } else if (prop === 'root') {
  33917. return () => node.root().toProxy()
  33918. } else {
  33919. return node[prop]
  33920. }
  33921. }
  33922. }
  33923. }
  33924. toProxy() {
  33925. if (!this.proxyCache) {
  33926. this.proxyCache = new Proxy(this, this.getProxyProcessor());
  33927. }
  33928. return this.proxyCache
  33929. }
  33930. addToError(error) {
  33931. error.postcssNode = this;
  33932. if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
  33933. let s = this.source;
  33934. error.stack = error.stack.replace(
  33935. /\n\s{4}at /,
  33936. `$&${s.input.from}:${s.start.line}:${s.start.column}$&`
  33937. );
  33938. }
  33939. return error
  33940. }
  33941. markDirty() {
  33942. if (this[isClean$1]) {
  33943. this[isClean$1] = false;
  33944. let next = this;
  33945. while ((next = next.parent)) {
  33946. next[isClean$1] = false;
  33947. }
  33948. }
  33949. }
  33950. get proxyOf() {
  33951. return this
  33952. }
  33953. }
  33954. var node_1 = Node$1;
  33955. Node$1.default = Node$1;
  33956. class Declaration extends node_1 {
  33957. constructor(defaults) {
  33958. if (
  33959. defaults &&
  33960. typeof defaults.value !== 'undefined' &&
  33961. typeof defaults.value !== 'string'
  33962. ) {
  33963. defaults = { ...defaults, value: String(defaults.value) };
  33964. }
  33965. super(defaults);
  33966. this.type = 'decl';
  33967. }
  33968. get variable() {
  33969. return this.prop.startsWith('--') || this.prop[0] === '$'
  33970. }
  33971. }
  33972. var declaration = Declaration;
  33973. Declaration.default = Declaration;
  33974. /* -*- Mode: js; js-indent-level: 2; -*- */
  33975. /*
  33976. * Copyright 2011 Mozilla Foundation and contributors
  33977. * Licensed under the New BSD license. See LICENSE or:
  33978. * http://opensource.org/licenses/BSD-3-Clause
  33979. */
  33980. var intToCharMap$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  33981. /**
  33982. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  33983. */
  33984. var encode$4 = function (number) {
  33985. if (0 <= number && number < intToCharMap$1.length) {
  33986. return intToCharMap$1[number];
  33987. }
  33988. throw new TypeError("Must be between 0 and 63: " + number);
  33989. };
  33990. /**
  33991. * Decode a single base 64 character code digit to an integer. Returns -1 on
  33992. * failure.
  33993. */
  33994. var decode$2 = function (charCode) {
  33995. var bigA = 65; // 'A'
  33996. var bigZ = 90; // 'Z'
  33997. var littleA = 97; // 'a'
  33998. var littleZ = 122; // 'z'
  33999. var zero = 48; // '0'
  34000. var nine = 57; // '9'
  34001. var plus = 43; // '+'
  34002. var slash = 47; // '/'
  34003. var littleOffset = 26;
  34004. var numberOffset = 52;
  34005. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  34006. if (bigA <= charCode && charCode <= bigZ) {
  34007. return (charCode - bigA);
  34008. }
  34009. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  34010. if (littleA <= charCode && charCode <= littleZ) {
  34011. return (charCode - littleA + littleOffset);
  34012. }
  34013. // 52 - 61: 0123456789
  34014. if (zero <= charCode && charCode <= nine) {
  34015. return (charCode - zero + numberOffset);
  34016. }
  34017. // 62: +
  34018. if (charCode == plus) {
  34019. return 62;
  34020. }
  34021. // 63: /
  34022. if (charCode == slash) {
  34023. return 63;
  34024. }
  34025. // Invalid base64 digit.
  34026. return -1;
  34027. };
  34028. var base64$1 = {
  34029. encode: encode$4,
  34030. decode: decode$2
  34031. };
  34032. /* -*- Mode: js; js-indent-level: 2; -*- */
  34033. /*
  34034. * Copyright 2011 Mozilla Foundation and contributors
  34035. * Licensed under the New BSD license. See LICENSE or:
  34036. * http://opensource.org/licenses/BSD-3-Clause
  34037. *
  34038. * Based on the Base 64 VLQ implementation in Closure Compiler:
  34039. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  34040. *
  34041. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  34042. * Redistribution and use in source and binary forms, with or without
  34043. * modification, are permitted provided that the following conditions are
  34044. * met:
  34045. *
  34046. * * Redistributions of source code must retain the above copyright
  34047. * notice, this list of conditions and the following disclaimer.
  34048. * * Redistributions in binary form must reproduce the above
  34049. * copyright notice, this list of conditions and the following
  34050. * disclaimer in the documentation and/or other materials provided
  34051. * with the distribution.
  34052. * * Neither the name of Google Inc. nor the names of its
  34053. * contributors may be used to endorse or promote products derived
  34054. * from this software without specific prior written permission.
  34055. *
  34056. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  34057. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  34058. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  34059. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  34060. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  34061. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  34062. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  34063. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  34064. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  34065. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  34066. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  34067. */
  34068. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  34069. // length quantities we use in the source map spec, the first bit is the sign,
  34070. // the next four bits are the actual value, and the 6th bit is the
  34071. // continuation bit. The continuation bit tells us whether there are more
  34072. // digits in this value following this digit.
  34073. //
  34074. // Continuation
  34075. // | Sign
  34076. // | |
  34077. // V V
  34078. // 101011
  34079. var VLQ_BASE_SHIFT$1 = 5;
  34080. // binary: 100000
  34081. var VLQ_BASE$1 = 1 << VLQ_BASE_SHIFT$1;
  34082. // binary: 011111
  34083. var VLQ_BASE_MASK$1 = VLQ_BASE$1 - 1;
  34084. // binary: 100000
  34085. var VLQ_CONTINUATION_BIT$1 = VLQ_BASE$1;
  34086. /**
  34087. * Converts from a two-complement value to a value where the sign bit is
  34088. * placed in the least significant bit. For example, as decimals:
  34089. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  34090. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  34091. */
  34092. function toVLQSigned$1(aValue) {
  34093. return aValue < 0
  34094. ? ((-aValue) << 1) + 1
  34095. : (aValue << 1) + 0;
  34096. }
  34097. /**
  34098. * Converts to a two-complement value from a value where the sign bit is
  34099. * placed in the least significant bit. For example, as decimals:
  34100. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  34101. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  34102. */
  34103. function fromVLQSigned$1(aValue) {
  34104. var isNegative = (aValue & 1) === 1;
  34105. var shifted = aValue >> 1;
  34106. return isNegative
  34107. ? -shifted
  34108. : shifted;
  34109. }
  34110. /**
  34111. * Returns the base 64 VLQ encoded value.
  34112. */
  34113. var encode$5 = function base64VLQ_encode(aValue) {
  34114. var encoded = "";
  34115. var digit;
  34116. var vlq = toVLQSigned$1(aValue);
  34117. do {
  34118. digit = vlq & VLQ_BASE_MASK$1;
  34119. vlq >>>= VLQ_BASE_SHIFT$1;
  34120. if (vlq > 0) {
  34121. // There are still more digits in this value, so we must make sure the
  34122. // continuation bit is marked.
  34123. digit |= VLQ_CONTINUATION_BIT$1;
  34124. }
  34125. encoded += base64$1.encode(digit);
  34126. } while (vlq > 0);
  34127. return encoded;
  34128. };
  34129. /**
  34130. * Decodes the next base 64 VLQ value from the given string and returns the
  34131. * value and the rest of the string via the out parameter.
  34132. */
  34133. var decode$3 = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  34134. var strLen = aStr.length;
  34135. var result = 0;
  34136. var shift = 0;
  34137. var continuation, digit;
  34138. do {
  34139. if (aIndex >= strLen) {
  34140. throw new Error("Expected more digits in base 64 VLQ value.");
  34141. }
  34142. digit = base64$1.decode(aStr.charCodeAt(aIndex++));
  34143. if (digit === -1) {
  34144. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  34145. }
  34146. continuation = !!(digit & VLQ_CONTINUATION_BIT$1);
  34147. digit &= VLQ_BASE_MASK$1;
  34148. result = result + (digit << shift);
  34149. shift += VLQ_BASE_SHIFT$1;
  34150. } while (continuation);
  34151. aOutParam.value = fromVLQSigned$1(result);
  34152. aOutParam.rest = aIndex;
  34153. };
  34154. var base64Vlq$1 = {
  34155. encode: encode$5,
  34156. decode: decode$3
  34157. };
  34158. /* -*- Mode: js; js-indent-level: 2; -*- */
  34159. var util$1 = createCommonjsModule(function (module, exports) {
  34160. /*
  34161. * Copyright 2011 Mozilla Foundation and contributors
  34162. * Licensed under the New BSD license. See LICENSE or:
  34163. * http://opensource.org/licenses/BSD-3-Clause
  34164. */
  34165. /**
  34166. * This is a helper function for getting values from parameter/options
  34167. * objects.
  34168. *
  34169. * @param args The object we are extracting values from
  34170. * @param name The name of the property we are getting.
  34171. * @param defaultValue An optional value to return if the property is missing
  34172. * from the object. If this is not specified and the property is missing, an
  34173. * error will be thrown.
  34174. */
  34175. function getArg(aArgs, aName, aDefaultValue) {
  34176. if (aName in aArgs) {
  34177. return aArgs[aName];
  34178. } else if (arguments.length === 3) {
  34179. return aDefaultValue;
  34180. } else {
  34181. throw new Error('"' + aName + '" is a required argument.');
  34182. }
  34183. }
  34184. exports.getArg = getArg;
  34185. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  34186. var dataUrlRegexp = /^data:.+\,.+$/;
  34187. function urlParse(aUrl) {
  34188. var match = aUrl.match(urlRegexp);
  34189. if (!match) {
  34190. return null;
  34191. }
  34192. return {
  34193. scheme: match[1],
  34194. auth: match[2],
  34195. host: match[3],
  34196. port: match[4],
  34197. path: match[5]
  34198. };
  34199. }
  34200. exports.urlParse = urlParse;
  34201. function urlGenerate(aParsedUrl) {
  34202. var url = '';
  34203. if (aParsedUrl.scheme) {
  34204. url += aParsedUrl.scheme + ':';
  34205. }
  34206. url += '//';
  34207. if (aParsedUrl.auth) {
  34208. url += aParsedUrl.auth + '@';
  34209. }
  34210. if (aParsedUrl.host) {
  34211. url += aParsedUrl.host;
  34212. }
  34213. if (aParsedUrl.port) {
  34214. url += ":" + aParsedUrl.port;
  34215. }
  34216. if (aParsedUrl.path) {
  34217. url += aParsedUrl.path;
  34218. }
  34219. return url;
  34220. }
  34221. exports.urlGenerate = urlGenerate;
  34222. var MAX_CACHED_INPUTS = 32;
  34223. /**
  34224. * Takes some function `f(input) -> result` and returns a memoized version of
  34225. * `f`.
  34226. *
  34227. * We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The
  34228. * memoization is a dumb-simple, linear least-recently-used cache.
  34229. */
  34230. function lruMemoize(f) {
  34231. var cache = [];
  34232. return function(input) {
  34233. for (var i = 0; i < cache.length; i++) {
  34234. if (cache[i].input === input) {
  34235. var temp = cache[0];
  34236. cache[0] = cache[i];
  34237. cache[i] = temp;
  34238. return cache[0].result;
  34239. }
  34240. }
  34241. var result = f(input);
  34242. cache.unshift({
  34243. input,
  34244. result,
  34245. });
  34246. if (cache.length > MAX_CACHED_INPUTS) {
  34247. cache.pop();
  34248. }
  34249. return result;
  34250. };
  34251. }
  34252. /**
  34253. * Normalizes a path, or the path portion of a URL:
  34254. *
  34255. * - Replaces consecutive slashes with one slash.
  34256. * - Removes unnecessary '.' parts.
  34257. * - Removes unnecessary '<dir>/..' parts.
  34258. *
  34259. * Based on code in the Node.js 'path' core module.
  34260. *
  34261. * @param aPath The path or url to normalize.
  34262. */
  34263. var normalize = lruMemoize(function normalize(aPath) {
  34264. var path = aPath;
  34265. var url = urlParse(aPath);
  34266. if (url) {
  34267. if (!url.path) {
  34268. return aPath;
  34269. }
  34270. path = url.path;
  34271. }
  34272. var isAbsolute = exports.isAbsolute(path);
  34273. // Split the path into parts between `/` characters. This is much faster than
  34274. // using `.split(/\/+/g)`.
  34275. var parts = [];
  34276. var start = 0;
  34277. var i = 0;
  34278. while (true) {
  34279. start = i;
  34280. i = path.indexOf("/", start);
  34281. if (i === -1) {
  34282. parts.push(path.slice(start));
  34283. break;
  34284. } else {
  34285. parts.push(path.slice(start, i));
  34286. while (i < path.length && path[i] === "/") {
  34287. i++;
  34288. }
  34289. }
  34290. }
  34291. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  34292. part = parts[i];
  34293. if (part === '.') {
  34294. parts.splice(i, 1);
  34295. } else if (part === '..') {
  34296. up++;
  34297. } else if (up > 0) {
  34298. if (part === '') {
  34299. // The first part is blank if the path is absolute. Trying to go
  34300. // above the root is a no-op. Therefore we can remove all '..' parts
  34301. // directly after the root.
  34302. parts.splice(i + 1, up);
  34303. up = 0;
  34304. } else {
  34305. parts.splice(i, 2);
  34306. up--;
  34307. }
  34308. }
  34309. }
  34310. path = parts.join('/');
  34311. if (path === '') {
  34312. path = isAbsolute ? '/' : '.';
  34313. }
  34314. if (url) {
  34315. url.path = path;
  34316. return urlGenerate(url);
  34317. }
  34318. return path;
  34319. });
  34320. exports.normalize = normalize;
  34321. /**
  34322. * Joins two paths/URLs.
  34323. *
  34324. * @param aRoot The root path or URL.
  34325. * @param aPath The path or URL to be joined with the root.
  34326. *
  34327. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  34328. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  34329. * first.
  34330. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  34331. * is updated with the result and aRoot is returned. Otherwise the result
  34332. * is returned.
  34333. * - If aPath is absolute, the result is aPath.
  34334. * - Otherwise the two paths are joined with a slash.
  34335. * - Joining for example 'http://' and 'www.example.com' is also supported.
  34336. */
  34337. function join(aRoot, aPath) {
  34338. if (aRoot === "") {
  34339. aRoot = ".";
  34340. }
  34341. if (aPath === "") {
  34342. aPath = ".";
  34343. }
  34344. var aPathUrl = urlParse(aPath);
  34345. var aRootUrl = urlParse(aRoot);
  34346. if (aRootUrl) {
  34347. aRoot = aRootUrl.path || '/';
  34348. }
  34349. // `join(foo, '//www.example.org')`
  34350. if (aPathUrl && !aPathUrl.scheme) {
  34351. if (aRootUrl) {
  34352. aPathUrl.scheme = aRootUrl.scheme;
  34353. }
  34354. return urlGenerate(aPathUrl);
  34355. }
  34356. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  34357. return aPath;
  34358. }
  34359. // `join('http://', 'www.example.com')`
  34360. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  34361. aRootUrl.host = aPath;
  34362. return urlGenerate(aRootUrl);
  34363. }
  34364. var joined = aPath.charAt(0) === '/'
  34365. ? aPath
  34366. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  34367. if (aRootUrl) {
  34368. aRootUrl.path = joined;
  34369. return urlGenerate(aRootUrl);
  34370. }
  34371. return joined;
  34372. }
  34373. exports.join = join;
  34374. exports.isAbsolute = function (aPath) {
  34375. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  34376. };
  34377. /**
  34378. * Make a path relative to a URL or another path.
  34379. *
  34380. * @param aRoot The root path or URL.
  34381. * @param aPath The path or URL to be made relative to aRoot.
  34382. */
  34383. function relative(aRoot, aPath) {
  34384. if (aRoot === "") {
  34385. aRoot = ".";
  34386. }
  34387. aRoot = aRoot.replace(/\/$/, '');
  34388. // It is possible for the path to be above the root. In this case, simply
  34389. // checking whether the root is a prefix of the path won't work. Instead, we
  34390. // need to remove components from the root one by one, until either we find
  34391. // a prefix that fits, or we run out of components to remove.
  34392. var level = 0;
  34393. while (aPath.indexOf(aRoot + '/') !== 0) {
  34394. var index = aRoot.lastIndexOf("/");
  34395. if (index < 0) {
  34396. return aPath;
  34397. }
  34398. // If the only part of the root that is left is the scheme (i.e. http://,
  34399. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  34400. // have exhausted all components, so the path is not relative to the root.
  34401. aRoot = aRoot.slice(0, index);
  34402. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  34403. return aPath;
  34404. }
  34405. ++level;
  34406. }
  34407. // Make sure we add a "../" for each component we removed from the root.
  34408. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  34409. }
  34410. exports.relative = relative;
  34411. var supportsNullProto = (function () {
  34412. var obj = Object.create(null);
  34413. return !('__proto__' in obj);
  34414. }());
  34415. function identity (s) {
  34416. return s;
  34417. }
  34418. /**
  34419. * Because behavior goes wacky when you set `__proto__` on objects, we
  34420. * have to prefix all the strings in our set with an arbitrary character.
  34421. *
  34422. * See https://github.com/mozilla/source-map/pull/31 and
  34423. * https://github.com/mozilla/source-map/issues/30
  34424. *
  34425. * @param String aStr
  34426. */
  34427. function toSetString(aStr) {
  34428. if (isProtoString(aStr)) {
  34429. return '$' + aStr;
  34430. }
  34431. return aStr;
  34432. }
  34433. exports.toSetString = supportsNullProto ? identity : toSetString;
  34434. function fromSetString(aStr) {
  34435. if (isProtoString(aStr)) {
  34436. return aStr.slice(1);
  34437. }
  34438. return aStr;
  34439. }
  34440. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  34441. function isProtoString(s) {
  34442. if (!s) {
  34443. return false;
  34444. }
  34445. var length = s.length;
  34446. if (length < 9 /* "__proto__".length */) {
  34447. return false;
  34448. }
  34449. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  34450. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  34451. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  34452. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  34453. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  34454. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  34455. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  34456. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  34457. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  34458. return false;
  34459. }
  34460. for (var i = length - 10; i >= 0; i--) {
  34461. if (s.charCodeAt(i) !== 36 /* '$' */) {
  34462. return false;
  34463. }
  34464. }
  34465. return true;
  34466. }
  34467. /**
  34468. * Comparator between two mappings where the original positions are compared.
  34469. *
  34470. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  34471. * mappings with the same original source/line/column, but different generated
  34472. * line and column the same. Useful when searching for a mapping with a
  34473. * stubbed out mapping.
  34474. */
  34475. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  34476. var cmp = strcmp(mappingA.source, mappingB.source);
  34477. if (cmp !== 0) {
  34478. return cmp;
  34479. }
  34480. cmp = mappingA.originalLine - mappingB.originalLine;
  34481. if (cmp !== 0) {
  34482. return cmp;
  34483. }
  34484. cmp = mappingA.originalColumn - mappingB.originalColumn;
  34485. if (cmp !== 0 || onlyCompareOriginal) {
  34486. return cmp;
  34487. }
  34488. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  34489. if (cmp !== 0) {
  34490. return cmp;
  34491. }
  34492. cmp = mappingA.generatedLine - mappingB.generatedLine;
  34493. if (cmp !== 0) {
  34494. return cmp;
  34495. }
  34496. return strcmp(mappingA.name, mappingB.name);
  34497. }
  34498. exports.compareByOriginalPositions = compareByOriginalPositions;
  34499. function compareByOriginalPositionsNoSource(mappingA, mappingB, onlyCompareOriginal) {
  34500. var cmp;
  34501. cmp = mappingA.originalLine - mappingB.originalLine;
  34502. if (cmp !== 0) {
  34503. return cmp;
  34504. }
  34505. cmp = mappingA.originalColumn - mappingB.originalColumn;
  34506. if (cmp !== 0 || onlyCompareOriginal) {
  34507. return cmp;
  34508. }
  34509. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  34510. if (cmp !== 0) {
  34511. return cmp;
  34512. }
  34513. cmp = mappingA.generatedLine - mappingB.generatedLine;
  34514. if (cmp !== 0) {
  34515. return cmp;
  34516. }
  34517. return strcmp(mappingA.name, mappingB.name);
  34518. }
  34519. exports.compareByOriginalPositionsNoSource = compareByOriginalPositionsNoSource;
  34520. /**
  34521. * Comparator between two mappings with deflated source and name indices where
  34522. * the generated positions are compared.
  34523. *
  34524. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  34525. * mappings with the same generated line and column, but different
  34526. * source/name/original line and column the same. Useful when searching for a
  34527. * mapping with a stubbed out mapping.
  34528. */
  34529. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  34530. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  34531. if (cmp !== 0) {
  34532. return cmp;
  34533. }
  34534. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  34535. if (cmp !== 0 || onlyCompareGenerated) {
  34536. return cmp;
  34537. }
  34538. cmp = strcmp(mappingA.source, mappingB.source);
  34539. if (cmp !== 0) {
  34540. return cmp;
  34541. }
  34542. cmp = mappingA.originalLine - mappingB.originalLine;
  34543. if (cmp !== 0) {
  34544. return cmp;
  34545. }
  34546. cmp = mappingA.originalColumn - mappingB.originalColumn;
  34547. if (cmp !== 0) {
  34548. return cmp;
  34549. }
  34550. return strcmp(mappingA.name, mappingB.name);
  34551. }
  34552. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  34553. function compareByGeneratedPositionsDeflatedNoLine(mappingA, mappingB, onlyCompareGenerated) {
  34554. var cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  34555. if (cmp !== 0 || onlyCompareGenerated) {
  34556. return cmp;
  34557. }
  34558. cmp = strcmp(mappingA.source, mappingB.source);
  34559. if (cmp !== 0) {
  34560. return cmp;
  34561. }
  34562. cmp = mappingA.originalLine - mappingB.originalLine;
  34563. if (cmp !== 0) {
  34564. return cmp;
  34565. }
  34566. cmp = mappingA.originalColumn - mappingB.originalColumn;
  34567. if (cmp !== 0) {
  34568. return cmp;
  34569. }
  34570. return strcmp(mappingA.name, mappingB.name);
  34571. }
  34572. exports.compareByGeneratedPositionsDeflatedNoLine = compareByGeneratedPositionsDeflatedNoLine;
  34573. function strcmp(aStr1, aStr2) {
  34574. if (aStr1 === aStr2) {
  34575. return 0;
  34576. }
  34577. if (aStr1 === null) {
  34578. return 1; // aStr2 !== null
  34579. }
  34580. if (aStr2 === null) {
  34581. return -1; // aStr1 !== null
  34582. }
  34583. if (aStr1 > aStr2) {
  34584. return 1;
  34585. }
  34586. return -1;
  34587. }
  34588. /**
  34589. * Comparator between two mappings with inflated source and name strings where
  34590. * the generated positions are compared.
  34591. */
  34592. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  34593. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  34594. if (cmp !== 0) {
  34595. return cmp;
  34596. }
  34597. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  34598. if (cmp !== 0) {
  34599. return cmp;
  34600. }
  34601. cmp = strcmp(mappingA.source, mappingB.source);
  34602. if (cmp !== 0) {
  34603. return cmp;
  34604. }
  34605. cmp = mappingA.originalLine - mappingB.originalLine;
  34606. if (cmp !== 0) {
  34607. return cmp;
  34608. }
  34609. cmp = mappingA.originalColumn - mappingB.originalColumn;
  34610. if (cmp !== 0) {
  34611. return cmp;
  34612. }
  34613. return strcmp(mappingA.name, mappingB.name);
  34614. }
  34615. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  34616. /**
  34617. * Strip any JSON XSSI avoidance prefix from the string (as documented
  34618. * in the source maps specification), and then parse the string as
  34619. * JSON.
  34620. */
  34621. function parseSourceMapInput(str) {
  34622. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  34623. }
  34624. exports.parseSourceMapInput = parseSourceMapInput;
  34625. /**
  34626. * Compute the URL of a source given the the source root, the source's
  34627. * URL, and the source map's URL.
  34628. */
  34629. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  34630. sourceURL = sourceURL || '';
  34631. if (sourceRoot) {
  34632. // This follows what Chrome does.
  34633. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  34634. sourceRoot += '/';
  34635. }
  34636. // The spec says:
  34637. // Line 4: An optional source root, useful for relocating source
  34638. // files on a server or removing repeated values in the
  34639. // “sources” entry. This value is prepended to the individual
  34640. // entries in the “source” field.
  34641. sourceURL = sourceRoot + sourceURL;
  34642. }
  34643. // Historically, SourceMapConsumer did not take the sourceMapURL as
  34644. // a parameter. This mode is still somewhat supported, which is why
  34645. // this code block is conditional. However, it's preferable to pass
  34646. // the source map URL to SourceMapConsumer, so that this function
  34647. // can implement the source URL resolution algorithm as outlined in
  34648. // the spec. This block is basically the equivalent of:
  34649. // new URL(sourceURL, sourceMapURL).toString()
  34650. // ... except it avoids using URL, which wasn't available in the
  34651. // older releases of node still supported by this library.
  34652. //
  34653. // The spec says:
  34654. // If the sources are not absolute URLs after prepending of the
  34655. // “sourceRoot”, the sources are resolved relative to the
  34656. // SourceMap (like resolving script src in a html document).
  34657. if (sourceMapURL) {
  34658. var parsed = urlParse(sourceMapURL);
  34659. if (!parsed) {
  34660. throw new Error("sourceMapURL could not be parsed");
  34661. }
  34662. if (parsed.path) {
  34663. // Strip the last path component, but keep the "/".
  34664. var index = parsed.path.lastIndexOf('/');
  34665. if (index >= 0) {
  34666. parsed.path = parsed.path.substring(0, index + 1);
  34667. }
  34668. }
  34669. sourceURL = join(urlGenerate(parsed), sourceURL);
  34670. }
  34671. return normalize(sourceURL);
  34672. }
  34673. exports.computeSourceURL = computeSourceURL;
  34674. });
  34675. /* -*- Mode: js; js-indent-level: 2; -*- */
  34676. /*
  34677. * Copyright 2011 Mozilla Foundation and contributors
  34678. * Licensed under the New BSD license. See LICENSE or:
  34679. * http://opensource.org/licenses/BSD-3-Clause
  34680. */
  34681. var has$1 = Object.prototype.hasOwnProperty;
  34682. var hasNativeMap$1 = typeof Map !== "undefined";
  34683. /**
  34684. * A data structure which is a combination of an array and a set. Adding a new
  34685. * member is O(1), testing for membership is O(1), and finding the index of an
  34686. * element is O(1). Removing elements from the set is not supported. Only
  34687. * strings are supported for membership.
  34688. */
  34689. function ArraySet$3() {
  34690. this._array = [];
  34691. this._set = hasNativeMap$1 ? new Map() : Object.create(null);
  34692. }
  34693. /**
  34694. * Static method for creating ArraySet instances from an existing array.
  34695. */
  34696. ArraySet$3.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  34697. var set = new ArraySet$3();
  34698. for (var i = 0, len = aArray.length; i < len; i++) {
  34699. set.add(aArray[i], aAllowDuplicates);
  34700. }
  34701. return set;
  34702. };
  34703. /**
  34704. * Return how many unique items are in this ArraySet. If duplicates have been
  34705. * added, than those do not count towards the size.
  34706. *
  34707. * @returns Number
  34708. */
  34709. ArraySet$3.prototype.size = function ArraySet_size() {
  34710. return hasNativeMap$1 ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  34711. };
  34712. /**
  34713. * Add the given string to this set.
  34714. *
  34715. * @param String aStr
  34716. */
  34717. ArraySet$3.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  34718. var sStr = hasNativeMap$1 ? aStr : util$1.toSetString(aStr);
  34719. var isDuplicate = hasNativeMap$1 ? this.has(aStr) : has$1.call(this._set, sStr);
  34720. var idx = this._array.length;
  34721. if (!isDuplicate || aAllowDuplicates) {
  34722. this._array.push(aStr);
  34723. }
  34724. if (!isDuplicate) {
  34725. if (hasNativeMap$1) {
  34726. this._set.set(aStr, idx);
  34727. } else {
  34728. this._set[sStr] = idx;
  34729. }
  34730. }
  34731. };
  34732. /**
  34733. * Is the given string a member of this set?
  34734. *
  34735. * @param String aStr
  34736. */
  34737. ArraySet$3.prototype.has = function ArraySet_has(aStr) {
  34738. if (hasNativeMap$1) {
  34739. return this._set.has(aStr);
  34740. } else {
  34741. var sStr = util$1.toSetString(aStr);
  34742. return has$1.call(this._set, sStr);
  34743. }
  34744. };
  34745. /**
  34746. * What is the index of the given string in the array?
  34747. *
  34748. * @param String aStr
  34749. */
  34750. ArraySet$3.prototype.indexOf = function ArraySet_indexOf(aStr) {
  34751. if (hasNativeMap$1) {
  34752. var idx = this._set.get(aStr);
  34753. if (idx >= 0) {
  34754. return idx;
  34755. }
  34756. } else {
  34757. var sStr = util$1.toSetString(aStr);
  34758. if (has$1.call(this._set, sStr)) {
  34759. return this._set[sStr];
  34760. }
  34761. }
  34762. throw new Error('"' + aStr + '" is not in the set.');
  34763. };
  34764. /**
  34765. * What is the element at the given index?
  34766. *
  34767. * @param Number aIdx
  34768. */
  34769. ArraySet$3.prototype.at = function ArraySet_at(aIdx) {
  34770. if (aIdx >= 0 && aIdx < this._array.length) {
  34771. return this._array[aIdx];
  34772. }
  34773. throw new Error('No element indexed by ' + aIdx);
  34774. };
  34775. /**
  34776. * Returns the array representation of this set (which has the proper indices
  34777. * indicated by indexOf). Note that this is a copy of the internal array used
  34778. * for storing the members so that no one can mess with internal state.
  34779. */
  34780. ArraySet$3.prototype.toArray = function ArraySet_toArray() {
  34781. return this._array.slice();
  34782. };
  34783. var ArraySet_1$1 = ArraySet$3;
  34784. var arraySet$1 = {
  34785. ArraySet: ArraySet_1$1
  34786. };
  34787. /* -*- Mode: js; js-indent-level: 2; -*- */
  34788. /*
  34789. * Copyright 2014 Mozilla Foundation and contributors
  34790. * Licensed under the New BSD license. See LICENSE or:
  34791. * http://opensource.org/licenses/BSD-3-Clause
  34792. */
  34793. /**
  34794. * Determine whether mappingB is after mappingA with respect to generated
  34795. * position.
  34796. */
  34797. function generatedPositionAfter$1(mappingA, mappingB) {
  34798. // Optimized for most common case
  34799. var lineA = mappingA.generatedLine;
  34800. var lineB = mappingB.generatedLine;
  34801. var columnA = mappingA.generatedColumn;
  34802. var columnB = mappingB.generatedColumn;
  34803. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  34804. util$1.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  34805. }
  34806. /**
  34807. * A data structure to provide a sorted view of accumulated mappings in a
  34808. * performance conscious manner. It trades a neglibable overhead in general
  34809. * case for a large speedup in case of mappings being added in order.
  34810. */
  34811. function MappingList$2() {
  34812. this._array = [];
  34813. this._sorted = true;
  34814. // Serves as infimum
  34815. this._last = {generatedLine: -1, generatedColumn: 0};
  34816. }
  34817. /**
  34818. * Iterate through internal items. This method takes the same arguments that
  34819. * `Array.prototype.forEach` takes.
  34820. *
  34821. * NOTE: The order of the mappings is NOT guaranteed.
  34822. */
  34823. MappingList$2.prototype.unsortedForEach =
  34824. function MappingList_forEach(aCallback, aThisArg) {
  34825. this._array.forEach(aCallback, aThisArg);
  34826. };
  34827. /**
  34828. * Add the given source mapping.
  34829. *
  34830. * @param Object aMapping
  34831. */
  34832. MappingList$2.prototype.add = function MappingList_add(aMapping) {
  34833. if (generatedPositionAfter$1(this._last, aMapping)) {
  34834. this._last = aMapping;
  34835. this._array.push(aMapping);
  34836. } else {
  34837. this._sorted = false;
  34838. this._array.push(aMapping);
  34839. }
  34840. };
  34841. /**
  34842. * Returns the flat, sorted array of mappings. The mappings are sorted by
  34843. * generated position.
  34844. *
  34845. * WARNING: This method returns internal data without copying, for
  34846. * performance. The return value must NOT be mutated, and should be treated as
  34847. * an immutable borrow. If you want to take ownership, you must make your own
  34848. * copy.
  34849. */
  34850. MappingList$2.prototype.toArray = function MappingList_toArray() {
  34851. if (!this._sorted) {
  34852. this._array.sort(util$1.compareByGeneratedPositionsInflated);
  34853. this._sorted = true;
  34854. }
  34855. return this._array;
  34856. };
  34857. var MappingList_1$1 = MappingList$2;
  34858. var mappingList$1 = {
  34859. MappingList: MappingList_1$1
  34860. };
  34861. /* -*- Mode: js; js-indent-level: 2; -*- */
  34862. /*
  34863. * Copyright 2011 Mozilla Foundation and contributors
  34864. * Licensed under the New BSD license. See LICENSE or:
  34865. * http://opensource.org/licenses/BSD-3-Clause
  34866. */
  34867. var ArraySet$4 = arraySet$1.ArraySet;
  34868. var MappingList$3 = mappingList$1.MappingList;
  34869. /**
  34870. * An instance of the SourceMapGenerator represents a source map which is
  34871. * being built incrementally. You may pass an object with the following
  34872. * properties:
  34873. *
  34874. * - file: The filename of the generated source.
  34875. * - sourceRoot: A root for all relative URLs in this source map.
  34876. */
  34877. function SourceMapGenerator$3(aArgs) {
  34878. if (!aArgs) {
  34879. aArgs = {};
  34880. }
  34881. this._file = util$1.getArg(aArgs, 'file', null);
  34882. this._sourceRoot = util$1.getArg(aArgs, 'sourceRoot', null);
  34883. this._skipValidation = util$1.getArg(aArgs, 'skipValidation', false);
  34884. this._sources = new ArraySet$4();
  34885. this._names = new ArraySet$4();
  34886. this._mappings = new MappingList$3();
  34887. this._sourcesContents = null;
  34888. }
  34889. SourceMapGenerator$3.prototype._version = 3;
  34890. /**
  34891. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  34892. *
  34893. * @param aSourceMapConsumer The SourceMap.
  34894. */
  34895. SourceMapGenerator$3.fromSourceMap =
  34896. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  34897. var sourceRoot = aSourceMapConsumer.sourceRoot;
  34898. var generator = new SourceMapGenerator$3({
  34899. file: aSourceMapConsumer.file,
  34900. sourceRoot: sourceRoot
  34901. });
  34902. aSourceMapConsumer.eachMapping(function (mapping) {
  34903. var newMapping = {
  34904. generated: {
  34905. line: mapping.generatedLine,
  34906. column: mapping.generatedColumn
  34907. }
  34908. };
  34909. if (mapping.source != null) {
  34910. newMapping.source = mapping.source;
  34911. if (sourceRoot != null) {
  34912. newMapping.source = util$1.relative(sourceRoot, newMapping.source);
  34913. }
  34914. newMapping.original = {
  34915. line: mapping.originalLine,
  34916. column: mapping.originalColumn
  34917. };
  34918. if (mapping.name != null) {
  34919. newMapping.name = mapping.name;
  34920. }
  34921. }
  34922. generator.addMapping(newMapping);
  34923. });
  34924. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  34925. var sourceRelative = sourceFile;
  34926. if (sourceRoot !== null) {
  34927. sourceRelative = util$1.relative(sourceRoot, sourceFile);
  34928. }
  34929. if (!generator._sources.has(sourceRelative)) {
  34930. generator._sources.add(sourceRelative);
  34931. }
  34932. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  34933. if (content != null) {
  34934. generator.setSourceContent(sourceFile, content);
  34935. }
  34936. });
  34937. return generator;
  34938. };
  34939. /**
  34940. * Add a single mapping from original source line and column to the generated
  34941. * source's line and column for this source map being created. The mapping
  34942. * object should have the following properties:
  34943. *
  34944. * - generated: An object with the generated line and column positions.
  34945. * - original: An object with the original line and column positions.
  34946. * - source: The original source file (relative to the sourceRoot).
  34947. * - name: An optional original token name for this mapping.
  34948. */
  34949. SourceMapGenerator$3.prototype.addMapping =
  34950. function SourceMapGenerator_addMapping(aArgs) {
  34951. var generated = util$1.getArg(aArgs, 'generated');
  34952. var original = util$1.getArg(aArgs, 'original', null);
  34953. var source = util$1.getArg(aArgs, 'source', null);
  34954. var name = util$1.getArg(aArgs, 'name', null);
  34955. if (!this._skipValidation) {
  34956. this._validateMapping(generated, original, source, name);
  34957. }
  34958. if (source != null) {
  34959. source = String(source);
  34960. if (!this._sources.has(source)) {
  34961. this._sources.add(source);
  34962. }
  34963. }
  34964. if (name != null) {
  34965. name = String(name);
  34966. if (!this._names.has(name)) {
  34967. this._names.add(name);
  34968. }
  34969. }
  34970. this._mappings.add({
  34971. generatedLine: generated.line,
  34972. generatedColumn: generated.column,
  34973. originalLine: original != null && original.line,
  34974. originalColumn: original != null && original.column,
  34975. source: source,
  34976. name: name
  34977. });
  34978. };
  34979. /**
  34980. * Set the source content for a source file.
  34981. */
  34982. SourceMapGenerator$3.prototype.setSourceContent =
  34983. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  34984. var source = aSourceFile;
  34985. if (this._sourceRoot != null) {
  34986. source = util$1.relative(this._sourceRoot, source);
  34987. }
  34988. if (aSourceContent != null) {
  34989. // Add the source content to the _sourcesContents map.
  34990. // Create a new _sourcesContents map if the property is null.
  34991. if (!this._sourcesContents) {
  34992. this._sourcesContents = Object.create(null);
  34993. }
  34994. this._sourcesContents[util$1.toSetString(source)] = aSourceContent;
  34995. } else if (this._sourcesContents) {
  34996. // Remove the source file from the _sourcesContents map.
  34997. // If the _sourcesContents map is empty, set the property to null.
  34998. delete this._sourcesContents[util$1.toSetString(source)];
  34999. if (Object.keys(this._sourcesContents).length === 0) {
  35000. this._sourcesContents = null;
  35001. }
  35002. }
  35003. };
  35004. /**
  35005. * Applies the mappings of a sub-source-map for a specific source file to the
  35006. * source map being generated. Each mapping to the supplied source file is
  35007. * rewritten using the supplied source map. Note: The resolution for the
  35008. * resulting mappings is the minimium of this map and the supplied map.
  35009. *
  35010. * @param aSourceMapConsumer The source map to be applied.
  35011. * @param aSourceFile Optional. The filename of the source file.
  35012. * If omitted, SourceMapConsumer's file property will be used.
  35013. * @param aSourceMapPath Optional. The dirname of the path to the source map
  35014. * to be applied. If relative, it is relative to the SourceMapConsumer.
  35015. * This parameter is needed when the two source maps aren't in the same
  35016. * directory, and the source map to be applied contains relative source
  35017. * paths. If so, those relative source paths need to be rewritten
  35018. * relative to the SourceMapGenerator.
  35019. */
  35020. SourceMapGenerator$3.prototype.applySourceMap =
  35021. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  35022. var sourceFile = aSourceFile;
  35023. // If aSourceFile is omitted, we will use the file property of the SourceMap
  35024. if (aSourceFile == null) {
  35025. if (aSourceMapConsumer.file == null) {
  35026. throw new Error(
  35027. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  35028. 'or the source map\'s "file" property. Both were omitted.'
  35029. );
  35030. }
  35031. sourceFile = aSourceMapConsumer.file;
  35032. }
  35033. var sourceRoot = this._sourceRoot;
  35034. // Make "sourceFile" relative if an absolute Url is passed.
  35035. if (sourceRoot != null) {
  35036. sourceFile = util$1.relative(sourceRoot, sourceFile);
  35037. }
  35038. // Applying the SourceMap can add and remove items from the sources and
  35039. // the names array.
  35040. var newSources = new ArraySet$4();
  35041. var newNames = new ArraySet$4();
  35042. // Find mappings for the "sourceFile"
  35043. this._mappings.unsortedForEach(function (mapping) {
  35044. if (mapping.source === sourceFile && mapping.originalLine != null) {
  35045. // Check if it can be mapped by the source map, then update the mapping.
  35046. var original = aSourceMapConsumer.originalPositionFor({
  35047. line: mapping.originalLine,
  35048. column: mapping.originalColumn
  35049. });
  35050. if (original.source != null) {
  35051. // Copy mapping
  35052. mapping.source = original.source;
  35053. if (aSourceMapPath != null) {
  35054. mapping.source = util$1.join(aSourceMapPath, mapping.source);
  35055. }
  35056. if (sourceRoot != null) {
  35057. mapping.source = util$1.relative(sourceRoot, mapping.source);
  35058. }
  35059. mapping.originalLine = original.line;
  35060. mapping.originalColumn = original.column;
  35061. if (original.name != null) {
  35062. mapping.name = original.name;
  35063. }
  35064. }
  35065. }
  35066. var source = mapping.source;
  35067. if (source != null && !newSources.has(source)) {
  35068. newSources.add(source);
  35069. }
  35070. var name = mapping.name;
  35071. if (name != null && !newNames.has(name)) {
  35072. newNames.add(name);
  35073. }
  35074. }, this);
  35075. this._sources = newSources;
  35076. this._names = newNames;
  35077. // Copy sourcesContents of applied map.
  35078. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  35079. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  35080. if (content != null) {
  35081. if (aSourceMapPath != null) {
  35082. sourceFile = util$1.join(aSourceMapPath, sourceFile);
  35083. }
  35084. if (sourceRoot != null) {
  35085. sourceFile = util$1.relative(sourceRoot, sourceFile);
  35086. }
  35087. this.setSourceContent(sourceFile, content);
  35088. }
  35089. }, this);
  35090. };
  35091. /**
  35092. * A mapping can have one of the three levels of data:
  35093. *
  35094. * 1. Just the generated position.
  35095. * 2. The Generated position, original position, and original source.
  35096. * 3. Generated and original position, original source, as well as a name
  35097. * token.
  35098. *
  35099. * To maintain consistency, we validate that any new mapping being added falls
  35100. * in to one of these categories.
  35101. */
  35102. SourceMapGenerator$3.prototype._validateMapping =
  35103. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  35104. aName) {
  35105. // When aOriginal is truthy but has empty values for .line and .column,
  35106. // it is most likely a programmer error. In this case we throw a very
  35107. // specific error message to try to guide them the right way.
  35108. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  35109. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  35110. throw new Error(
  35111. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  35112. 'the original mapping entirely and only map the generated position. If so, pass ' +
  35113. 'null for the original mapping instead of an object with empty or null values.'
  35114. );
  35115. }
  35116. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  35117. && aGenerated.line > 0 && aGenerated.column >= 0
  35118. && !aOriginal && !aSource && !aName) {
  35119. // Case 1.
  35120. return;
  35121. }
  35122. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  35123. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  35124. && aGenerated.line > 0 && aGenerated.column >= 0
  35125. && aOriginal.line > 0 && aOriginal.column >= 0
  35126. && aSource) {
  35127. // Cases 2 and 3.
  35128. return;
  35129. }
  35130. else {
  35131. throw new Error('Invalid mapping: ' + JSON.stringify({
  35132. generated: aGenerated,
  35133. source: aSource,
  35134. original: aOriginal,
  35135. name: aName
  35136. }));
  35137. }
  35138. };
  35139. /**
  35140. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  35141. * specified by the source map format.
  35142. */
  35143. SourceMapGenerator$3.prototype._serializeMappings =
  35144. function SourceMapGenerator_serializeMappings() {
  35145. var previousGeneratedColumn = 0;
  35146. var previousGeneratedLine = 1;
  35147. var previousOriginalColumn = 0;
  35148. var previousOriginalLine = 0;
  35149. var previousName = 0;
  35150. var previousSource = 0;
  35151. var result = '';
  35152. var next;
  35153. var mapping;
  35154. var nameIdx;
  35155. var sourceIdx;
  35156. var mappings = this._mappings.toArray();
  35157. for (var i = 0, len = mappings.length; i < len; i++) {
  35158. mapping = mappings[i];
  35159. next = '';
  35160. if (mapping.generatedLine !== previousGeneratedLine) {
  35161. previousGeneratedColumn = 0;
  35162. while (mapping.generatedLine !== previousGeneratedLine) {
  35163. next += ';';
  35164. previousGeneratedLine++;
  35165. }
  35166. }
  35167. else {
  35168. if (i > 0) {
  35169. if (!util$1.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  35170. continue;
  35171. }
  35172. next += ',';
  35173. }
  35174. }
  35175. next += base64Vlq$1.encode(mapping.generatedColumn
  35176. - previousGeneratedColumn);
  35177. previousGeneratedColumn = mapping.generatedColumn;
  35178. if (mapping.source != null) {
  35179. sourceIdx = this._sources.indexOf(mapping.source);
  35180. next += base64Vlq$1.encode(sourceIdx - previousSource);
  35181. previousSource = sourceIdx;
  35182. // lines are stored 0-based in SourceMap spec version 3
  35183. next += base64Vlq$1.encode(mapping.originalLine - 1
  35184. - previousOriginalLine);
  35185. previousOriginalLine = mapping.originalLine - 1;
  35186. next += base64Vlq$1.encode(mapping.originalColumn
  35187. - previousOriginalColumn);
  35188. previousOriginalColumn = mapping.originalColumn;
  35189. if (mapping.name != null) {
  35190. nameIdx = this._names.indexOf(mapping.name);
  35191. next += base64Vlq$1.encode(nameIdx - previousName);
  35192. previousName = nameIdx;
  35193. }
  35194. }
  35195. result += next;
  35196. }
  35197. return result;
  35198. };
  35199. SourceMapGenerator$3.prototype._generateSourcesContent =
  35200. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  35201. return aSources.map(function (source) {
  35202. if (!this._sourcesContents) {
  35203. return null;
  35204. }
  35205. if (aSourceRoot != null) {
  35206. source = util$1.relative(aSourceRoot, source);
  35207. }
  35208. var key = util$1.toSetString(source);
  35209. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  35210. ? this._sourcesContents[key]
  35211. : null;
  35212. }, this);
  35213. };
  35214. /**
  35215. * Externalize the source map.
  35216. */
  35217. SourceMapGenerator$3.prototype.toJSON =
  35218. function SourceMapGenerator_toJSON() {
  35219. var map = {
  35220. version: this._version,
  35221. sources: this._sources.toArray(),
  35222. names: this._names.toArray(),
  35223. mappings: this._serializeMappings()
  35224. };
  35225. if (this._file != null) {
  35226. map.file = this._file;
  35227. }
  35228. if (this._sourceRoot != null) {
  35229. map.sourceRoot = this._sourceRoot;
  35230. }
  35231. if (this._sourcesContents) {
  35232. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  35233. }
  35234. return map;
  35235. };
  35236. /**
  35237. * Render the source map being generated to a string.
  35238. */
  35239. SourceMapGenerator$3.prototype.toString =
  35240. function SourceMapGenerator_toString() {
  35241. return JSON.stringify(this.toJSON());
  35242. };
  35243. var SourceMapGenerator_1$1 = SourceMapGenerator$3;
  35244. var sourceMapGenerator$1 = {
  35245. SourceMapGenerator: SourceMapGenerator_1$1
  35246. };
  35247. /* -*- Mode: js; js-indent-level: 2; -*- */
  35248. var binarySearch$1 = createCommonjsModule(function (module, exports) {
  35249. /*
  35250. * Copyright 2011 Mozilla Foundation and contributors
  35251. * Licensed under the New BSD license. See LICENSE or:
  35252. * http://opensource.org/licenses/BSD-3-Clause
  35253. */
  35254. exports.GREATEST_LOWER_BOUND = 1;
  35255. exports.LEAST_UPPER_BOUND = 2;
  35256. /**
  35257. * Recursive implementation of binary search.
  35258. *
  35259. * @param aLow Indices here and lower do not contain the needle.
  35260. * @param aHigh Indices here and higher do not contain the needle.
  35261. * @param aNeedle The element being searched for.
  35262. * @param aHaystack The non-empty array being searched.
  35263. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  35264. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  35265. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  35266. * closest element that is smaller than or greater than the one we are
  35267. * searching for, respectively, if the exact element cannot be found.
  35268. */
  35269. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  35270. // This function terminates when one of the following is true:
  35271. //
  35272. // 1. We find the exact element we are looking for.
  35273. //
  35274. // 2. We did not find the exact element, but we can return the index of
  35275. // the next-closest element.
  35276. //
  35277. // 3. We did not find the exact element, and there is no next-closest
  35278. // element than the one we are searching for, so we return -1.
  35279. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  35280. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  35281. if (cmp === 0) {
  35282. // Found the element we are looking for.
  35283. return mid;
  35284. }
  35285. else if (cmp > 0) {
  35286. // Our needle is greater than aHaystack[mid].
  35287. if (aHigh - mid > 1) {
  35288. // The element is in the upper half.
  35289. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  35290. }
  35291. // The exact needle element was not found in this haystack. Determine if
  35292. // we are in termination case (3) or (2) and return the appropriate thing.
  35293. if (aBias == exports.LEAST_UPPER_BOUND) {
  35294. return aHigh < aHaystack.length ? aHigh : -1;
  35295. } else {
  35296. return mid;
  35297. }
  35298. }
  35299. else {
  35300. // Our needle is less than aHaystack[mid].
  35301. if (mid - aLow > 1) {
  35302. // The element is in the lower half.
  35303. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  35304. }
  35305. // we are in termination case (3) or (2) and return the appropriate thing.
  35306. if (aBias == exports.LEAST_UPPER_BOUND) {
  35307. return mid;
  35308. } else {
  35309. return aLow < 0 ? -1 : aLow;
  35310. }
  35311. }
  35312. }
  35313. /**
  35314. * This is an implementation of binary search which will always try and return
  35315. * the index of the closest element if there is no exact hit. This is because
  35316. * mappings between original and generated line/col pairs are single points,
  35317. * and there is an implicit region between each of them, so a miss just means
  35318. * that you aren't on the very start of a region.
  35319. *
  35320. * @param aNeedle The element you are looking for.
  35321. * @param aHaystack The array that is being searched.
  35322. * @param aCompare A function which takes the needle and an element in the
  35323. * array and returns -1, 0, or 1 depending on whether the needle is less
  35324. * than, equal to, or greater than the element, respectively.
  35325. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  35326. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  35327. * closest element that is smaller than or greater than the one we are
  35328. * searching for, respectively, if the exact element cannot be found.
  35329. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  35330. */
  35331. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  35332. if (aHaystack.length === 0) {
  35333. return -1;
  35334. }
  35335. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  35336. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  35337. if (index < 0) {
  35338. return -1;
  35339. }
  35340. // We have found either the exact element, or the next-closest element than
  35341. // the one we are searching for. However, there may be more than one such
  35342. // element. Make sure we always return the smallest of these.
  35343. while (index - 1 >= 0) {
  35344. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  35345. break;
  35346. }
  35347. --index;
  35348. }
  35349. return index;
  35350. };
  35351. });
  35352. /* -*- Mode: js; js-indent-level: 2; -*- */
  35353. /*
  35354. * Copyright 2011 Mozilla Foundation and contributors
  35355. * Licensed under the New BSD license. See LICENSE or:
  35356. * http://opensource.org/licenses/BSD-3-Clause
  35357. */
  35358. // It turns out that some (most?) JavaScript engines don't self-host
  35359. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  35360. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  35361. // custom comparator function, calling back and forth between the VM's C++ and
  35362. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  35363. // worse generated code for the comparator function than would be optimal. In
  35364. // fact, when sorting with a comparator, these costs outweigh the benefits of
  35365. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  35366. // a ~3500ms mean speed-up in `bench/bench.html`.
  35367. function SortTemplate(comparator) {
  35368. /**
  35369. * Swap the elements indexed by `x` and `y` in the array `ary`.
  35370. *
  35371. * @param {Array} ary
  35372. * The array.
  35373. * @param {Number} x
  35374. * The index of the first item.
  35375. * @param {Number} y
  35376. * The index of the second item.
  35377. */
  35378. function swap(ary, x, y) {
  35379. var temp = ary[x];
  35380. ary[x] = ary[y];
  35381. ary[y] = temp;
  35382. }
  35383. /**
  35384. * Returns a random integer within the range `low .. high` inclusive.
  35385. *
  35386. * @param {Number} low
  35387. * The lower bound on the range.
  35388. * @param {Number} high
  35389. * The upper bound on the range.
  35390. */
  35391. function randomIntInRange(low, high) {
  35392. return Math.round(low + (Math.random() * (high - low)));
  35393. }
  35394. /**
  35395. * The Quick Sort algorithm.
  35396. *
  35397. * @param {Array} ary
  35398. * An array to sort.
  35399. * @param {function} comparator
  35400. * Function to use to compare two items.
  35401. * @param {Number} p
  35402. * Start index of the array
  35403. * @param {Number} r
  35404. * End index of the array
  35405. */
  35406. function doQuickSort(ary, comparator, p, r) {
  35407. // If our lower bound is less than our upper bound, we (1) partition the
  35408. // array into two pieces and (2) recurse on each half. If it is not, this is
  35409. // the empty array and our base case.
  35410. if (p < r) {
  35411. // (1) Partitioning.
  35412. //
  35413. // The partitioning chooses a pivot between `p` and `r` and moves all
  35414. // elements that are less than or equal to the pivot to the before it, and
  35415. // all the elements that are greater than it after it. The effect is that
  35416. // once partition is done, the pivot is in the exact place it will be when
  35417. // the array is put in sorted order, and it will not need to be moved
  35418. // again. This runs in O(n) time.
  35419. // Always choose a random pivot so that an input array which is reverse
  35420. // sorted does not cause O(n^2) running time.
  35421. var pivotIndex = randomIntInRange(p, r);
  35422. var i = p - 1;
  35423. swap(ary, pivotIndex, r);
  35424. var pivot = ary[r];
  35425. // Immediately after `j` is incremented in this loop, the following hold
  35426. // true:
  35427. //
  35428. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  35429. //
  35430. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  35431. for (var j = p; j < r; j++) {
  35432. if (comparator(ary[j], pivot, false) <= 0) {
  35433. i += 1;
  35434. swap(ary, i, j);
  35435. }
  35436. }
  35437. swap(ary, i + 1, j);
  35438. var q = i + 1;
  35439. // (2) Recurse on each half.
  35440. doQuickSort(ary, comparator, p, q - 1);
  35441. doQuickSort(ary, comparator, q + 1, r);
  35442. }
  35443. }
  35444. return doQuickSort;
  35445. }
  35446. function cloneSort(comparator) {
  35447. let template = SortTemplate.toString();
  35448. let templateFn = new Function(`return ${template}`)();
  35449. return templateFn(comparator);
  35450. }
  35451. /**
  35452. * Sort the given array in-place with the given comparator function.
  35453. *
  35454. * @param {Array} ary
  35455. * An array to sort.
  35456. * @param {function} comparator
  35457. * Function to use to compare two items.
  35458. */
  35459. let sortCache = new WeakMap();
  35460. var quickSort_1$1 = function (ary, comparator, start = 0) {
  35461. let doQuickSort = sortCache.get(comparator);
  35462. if (doQuickSort === void 0) {
  35463. doQuickSort = cloneSort(comparator);
  35464. sortCache.set(comparator, doQuickSort);
  35465. }
  35466. doQuickSort(ary, comparator, start, ary.length - 1);
  35467. };
  35468. var quickSort$2 = {
  35469. quickSort: quickSort_1$1
  35470. };
  35471. /* -*- Mode: js; js-indent-level: 2; -*- */
  35472. /*
  35473. * Copyright 2011 Mozilla Foundation and contributors
  35474. * Licensed under the New BSD license. See LICENSE or:
  35475. * http://opensource.org/licenses/BSD-3-Clause
  35476. */
  35477. var ArraySet$5 = arraySet$1.ArraySet;
  35478. var quickSort$3 = quickSort$2.quickSort;
  35479. function SourceMapConsumer$2(aSourceMap, aSourceMapURL) {
  35480. var sourceMap = aSourceMap;
  35481. if (typeof aSourceMap === 'string') {
  35482. sourceMap = util$1.parseSourceMapInput(aSourceMap);
  35483. }
  35484. return sourceMap.sections != null
  35485. ? new IndexedSourceMapConsumer$1(sourceMap, aSourceMapURL)
  35486. : new BasicSourceMapConsumer$1(sourceMap, aSourceMapURL);
  35487. }
  35488. SourceMapConsumer$2.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  35489. return BasicSourceMapConsumer$1.fromSourceMap(aSourceMap, aSourceMapURL);
  35490. };
  35491. /**
  35492. * The version of the source mapping spec that we are consuming.
  35493. */
  35494. SourceMapConsumer$2.prototype._version = 3;
  35495. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  35496. // parsed mapping coordinates from the source map's "mappings" attribute. They
  35497. // are lazily instantiated, accessed via the `_generatedMappings` and
  35498. // `_originalMappings` getters respectively, and we only parse the mappings
  35499. // and create these arrays once queried for a source location. We jump through
  35500. // these hoops because there can be many thousands of mappings, and parsing
  35501. // them is expensive, so we only want to do it if we must.
  35502. //
  35503. // Each object in the arrays is of the form:
  35504. //
  35505. // {
  35506. // generatedLine: The line number in the generated code,
  35507. // generatedColumn: The column number in the generated code,
  35508. // source: The path to the original source file that generated this
  35509. // chunk of code,
  35510. // originalLine: The line number in the original source that
  35511. // corresponds to this chunk of generated code,
  35512. // originalColumn: The column number in the original source that
  35513. // corresponds to this chunk of generated code,
  35514. // name: The name of the original symbol which generated this chunk of
  35515. // code.
  35516. // }
  35517. //
  35518. // All properties except for `generatedLine` and `generatedColumn` can be
  35519. // `null`.
  35520. //
  35521. // `_generatedMappings` is ordered by the generated positions.
  35522. //
  35523. // `_originalMappings` is ordered by the original positions.
  35524. SourceMapConsumer$2.prototype.__generatedMappings = null;
  35525. Object.defineProperty(SourceMapConsumer$2.prototype, '_generatedMappings', {
  35526. configurable: true,
  35527. enumerable: true,
  35528. get: function () {
  35529. if (!this.__generatedMappings) {
  35530. this._parseMappings(this._mappings, this.sourceRoot);
  35531. }
  35532. return this.__generatedMappings;
  35533. }
  35534. });
  35535. SourceMapConsumer$2.prototype.__originalMappings = null;
  35536. Object.defineProperty(SourceMapConsumer$2.prototype, '_originalMappings', {
  35537. configurable: true,
  35538. enumerable: true,
  35539. get: function () {
  35540. if (!this.__originalMappings) {
  35541. this._parseMappings(this._mappings, this.sourceRoot);
  35542. }
  35543. return this.__originalMappings;
  35544. }
  35545. });
  35546. SourceMapConsumer$2.prototype._charIsMappingSeparator =
  35547. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  35548. var c = aStr.charAt(index);
  35549. return c === ";" || c === ",";
  35550. };
  35551. /**
  35552. * Parse the mappings in a string in to a data structure which we can easily
  35553. * query (the ordered arrays in the `this.__generatedMappings` and
  35554. * `this.__originalMappings` properties).
  35555. */
  35556. SourceMapConsumer$2.prototype._parseMappings =
  35557. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  35558. throw new Error("Subclasses must implement _parseMappings");
  35559. };
  35560. SourceMapConsumer$2.GENERATED_ORDER = 1;
  35561. SourceMapConsumer$2.ORIGINAL_ORDER = 2;
  35562. SourceMapConsumer$2.GREATEST_LOWER_BOUND = 1;
  35563. SourceMapConsumer$2.LEAST_UPPER_BOUND = 2;
  35564. /**
  35565. * Iterate over each mapping between an original source/line/column and a
  35566. * generated line/column in this source map.
  35567. *
  35568. * @param Function aCallback
  35569. * The function that is called with each mapping.
  35570. * @param Object aContext
  35571. * Optional. If specified, this object will be the value of `this` every
  35572. * time that `aCallback` is called.
  35573. * @param aOrder
  35574. * Either `SourceMapConsumer.GENERATED_ORDER` or
  35575. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  35576. * iterate over the mappings sorted by the generated file's line/column
  35577. * order or the original's source/line/column order, respectively. Defaults to
  35578. * `SourceMapConsumer.GENERATED_ORDER`.
  35579. */
  35580. SourceMapConsumer$2.prototype.eachMapping =
  35581. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  35582. var context = aContext || null;
  35583. var order = aOrder || SourceMapConsumer$2.GENERATED_ORDER;
  35584. var mappings;
  35585. switch (order) {
  35586. case SourceMapConsumer$2.GENERATED_ORDER:
  35587. mappings = this._generatedMappings;
  35588. break;
  35589. case SourceMapConsumer$2.ORIGINAL_ORDER:
  35590. mappings = this._originalMappings;
  35591. break;
  35592. default:
  35593. throw new Error("Unknown order of iteration.");
  35594. }
  35595. var sourceRoot = this.sourceRoot;
  35596. var boundCallback = aCallback.bind(context);
  35597. var names = this._names;
  35598. var sources = this._sources;
  35599. var sourceMapURL = this._sourceMapURL;
  35600. for (var i = 0, n = mappings.length; i < n; i++) {
  35601. var mapping = mappings[i];
  35602. var source = mapping.source === null ? null : sources.at(mapping.source);
  35603. source = util$1.computeSourceURL(sourceRoot, source, sourceMapURL);
  35604. boundCallback({
  35605. source: source,
  35606. generatedLine: mapping.generatedLine,
  35607. generatedColumn: mapping.generatedColumn,
  35608. originalLine: mapping.originalLine,
  35609. originalColumn: mapping.originalColumn,
  35610. name: mapping.name === null ? null : names.at(mapping.name)
  35611. });
  35612. }
  35613. };
  35614. /**
  35615. * Returns all generated line and column information for the original source,
  35616. * line, and column provided. If no column is provided, returns all mappings
  35617. * corresponding to a either the line we are searching for or the next
  35618. * closest line that has any mappings. Otherwise, returns all mappings
  35619. * corresponding to the given line and either the column we are searching for
  35620. * or the next closest column that has any offsets.
  35621. *
  35622. * The only argument is an object with the following properties:
  35623. *
  35624. * - source: The filename of the original source.
  35625. * - line: The line number in the original source. The line number is 1-based.
  35626. * - column: Optional. the column number in the original source.
  35627. * The column number is 0-based.
  35628. *
  35629. * and an array of objects is returned, each with the following properties:
  35630. *
  35631. * - line: The line number in the generated source, or null. The
  35632. * line number is 1-based.
  35633. * - column: The column number in the generated source, or null.
  35634. * The column number is 0-based.
  35635. */
  35636. SourceMapConsumer$2.prototype.allGeneratedPositionsFor =
  35637. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  35638. var line = util$1.getArg(aArgs, 'line');
  35639. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  35640. // returns the index of the closest mapping less than the needle. By
  35641. // setting needle.originalColumn to 0, we thus find the last mapping for
  35642. // the given line, provided such a mapping exists.
  35643. var needle = {
  35644. source: util$1.getArg(aArgs, 'source'),
  35645. originalLine: line,
  35646. originalColumn: util$1.getArg(aArgs, 'column', 0)
  35647. };
  35648. needle.source = this._findSourceIndex(needle.source);
  35649. if (needle.source < 0) {
  35650. return [];
  35651. }
  35652. var mappings = [];
  35653. var index = this._findMapping(needle,
  35654. this._originalMappings,
  35655. "originalLine",
  35656. "originalColumn",
  35657. util$1.compareByOriginalPositions,
  35658. binarySearch$1.LEAST_UPPER_BOUND);
  35659. if (index >= 0) {
  35660. var mapping = this._originalMappings[index];
  35661. if (aArgs.column === undefined) {
  35662. var originalLine = mapping.originalLine;
  35663. // Iterate until either we run out of mappings, or we run into
  35664. // a mapping for a different line than the one we found. Since
  35665. // mappings are sorted, this is guaranteed to find all mappings for
  35666. // the line we found.
  35667. while (mapping && mapping.originalLine === originalLine) {
  35668. mappings.push({
  35669. line: util$1.getArg(mapping, 'generatedLine', null),
  35670. column: util$1.getArg(mapping, 'generatedColumn', null),
  35671. lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
  35672. });
  35673. mapping = this._originalMappings[++index];
  35674. }
  35675. } else {
  35676. var originalColumn = mapping.originalColumn;
  35677. // Iterate until either we run out of mappings, or we run into
  35678. // a mapping for a different line than the one we were searching for.
  35679. // Since mappings are sorted, this is guaranteed to find all mappings for
  35680. // the line we are searching for.
  35681. while (mapping &&
  35682. mapping.originalLine === line &&
  35683. mapping.originalColumn == originalColumn) {
  35684. mappings.push({
  35685. line: util$1.getArg(mapping, 'generatedLine', null),
  35686. column: util$1.getArg(mapping, 'generatedColumn', null),
  35687. lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
  35688. });
  35689. mapping = this._originalMappings[++index];
  35690. }
  35691. }
  35692. }
  35693. return mappings;
  35694. };
  35695. var SourceMapConsumer_1$1 = SourceMapConsumer$2;
  35696. /**
  35697. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  35698. * query for information about the original file positions by giving it a file
  35699. * position in the generated source.
  35700. *
  35701. * The first parameter is the raw source map (either as a JSON string, or
  35702. * already parsed to an object). According to the spec, source maps have the
  35703. * following attributes:
  35704. *
  35705. * - version: Which version of the source map spec this map is following.
  35706. * - sources: An array of URLs to the original source files.
  35707. * - names: An array of identifiers which can be referrenced by individual mappings.
  35708. * - sourceRoot: Optional. The URL root from which all sources are relative.
  35709. * - sourcesContent: Optional. An array of contents of the original source files.
  35710. * - mappings: A string of base64 VLQs which contain the actual mappings.
  35711. * - file: Optional. The generated file this source map is associated with.
  35712. *
  35713. * Here is an example source map, taken from the source map spec[0]:
  35714. *
  35715. * {
  35716. * version : 3,
  35717. * file: "out.js",
  35718. * sourceRoot : "",
  35719. * sources: ["foo.js", "bar.js"],
  35720. * names: ["src", "maps", "are", "fun"],
  35721. * mappings: "AA,AB;;ABCDE;"
  35722. * }
  35723. *
  35724. * The second parameter, if given, is a string whose value is the URL
  35725. * at which the source map was found. This URL is used to compute the
  35726. * sources array.
  35727. *
  35728. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  35729. */
  35730. function BasicSourceMapConsumer$1(aSourceMap, aSourceMapURL) {
  35731. var sourceMap = aSourceMap;
  35732. if (typeof aSourceMap === 'string') {
  35733. sourceMap = util$1.parseSourceMapInput(aSourceMap);
  35734. }
  35735. var version = util$1.getArg(sourceMap, 'version');
  35736. var sources = util$1.getArg(sourceMap, 'sources');
  35737. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  35738. // requires the array) to play nice here.
  35739. var names = util$1.getArg(sourceMap, 'names', []);
  35740. var sourceRoot = util$1.getArg(sourceMap, 'sourceRoot', null);
  35741. var sourcesContent = util$1.getArg(sourceMap, 'sourcesContent', null);
  35742. var mappings = util$1.getArg(sourceMap, 'mappings');
  35743. var file = util$1.getArg(sourceMap, 'file', null);
  35744. // Once again, Sass deviates from the spec and supplies the version as a
  35745. // string rather than a number, so we use loose equality checking here.
  35746. if (version != this._version) {
  35747. throw new Error('Unsupported version: ' + version);
  35748. }
  35749. if (sourceRoot) {
  35750. sourceRoot = util$1.normalize(sourceRoot);
  35751. }
  35752. sources = sources
  35753. .map(String)
  35754. // Some source maps produce relative source paths like "./foo.js" instead of
  35755. // "foo.js". Normalize these first so that future comparisons will succeed.
  35756. // See bugzil.la/1090768.
  35757. .map(util$1.normalize)
  35758. // Always ensure that absolute sources are internally stored relative to
  35759. // the source root, if the source root is absolute. Not doing this would
  35760. // be particularly problematic when the source root is a prefix of the
  35761. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  35762. .map(function (source) {
  35763. return sourceRoot && util$1.isAbsolute(sourceRoot) && util$1.isAbsolute(source)
  35764. ? util$1.relative(sourceRoot, source)
  35765. : source;
  35766. });
  35767. // Pass `true` below to allow duplicate names and sources. While source maps
  35768. // are intended to be compressed and deduplicated, the TypeScript compiler
  35769. // sometimes generates source maps with duplicates in them. See Github issue
  35770. // #72 and bugzil.la/889492.
  35771. this._names = ArraySet$5.fromArray(names.map(String), true);
  35772. this._sources = ArraySet$5.fromArray(sources, true);
  35773. this._absoluteSources = this._sources.toArray().map(function (s) {
  35774. return util$1.computeSourceURL(sourceRoot, s, aSourceMapURL);
  35775. });
  35776. this.sourceRoot = sourceRoot;
  35777. this.sourcesContent = sourcesContent;
  35778. this._mappings = mappings;
  35779. this._sourceMapURL = aSourceMapURL;
  35780. this.file = file;
  35781. }
  35782. BasicSourceMapConsumer$1.prototype = Object.create(SourceMapConsumer$2.prototype);
  35783. BasicSourceMapConsumer$1.prototype.consumer = SourceMapConsumer$2;
  35784. /**
  35785. * Utility function to find the index of a source. Returns -1 if not
  35786. * found.
  35787. */
  35788. BasicSourceMapConsumer$1.prototype._findSourceIndex = function(aSource) {
  35789. var relativeSource = aSource;
  35790. if (this.sourceRoot != null) {
  35791. relativeSource = util$1.relative(this.sourceRoot, relativeSource);
  35792. }
  35793. if (this._sources.has(relativeSource)) {
  35794. return this._sources.indexOf(relativeSource);
  35795. }
  35796. // Maybe aSource is an absolute URL as returned by |sources|. In
  35797. // this case we can't simply undo the transform.
  35798. var i;
  35799. for (i = 0; i < this._absoluteSources.length; ++i) {
  35800. if (this._absoluteSources[i] == aSource) {
  35801. return i;
  35802. }
  35803. }
  35804. return -1;
  35805. };
  35806. /**
  35807. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  35808. *
  35809. * @param SourceMapGenerator aSourceMap
  35810. * The source map that will be consumed.
  35811. * @param String aSourceMapURL
  35812. * The URL at which the source map can be found (optional)
  35813. * @returns BasicSourceMapConsumer
  35814. */
  35815. BasicSourceMapConsumer$1.fromSourceMap =
  35816. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  35817. var smc = Object.create(BasicSourceMapConsumer$1.prototype);
  35818. var names = smc._names = ArraySet$5.fromArray(aSourceMap._names.toArray(), true);
  35819. var sources = smc._sources = ArraySet$5.fromArray(aSourceMap._sources.toArray(), true);
  35820. smc.sourceRoot = aSourceMap._sourceRoot;
  35821. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  35822. smc.sourceRoot);
  35823. smc.file = aSourceMap._file;
  35824. smc._sourceMapURL = aSourceMapURL;
  35825. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  35826. return util$1.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  35827. });
  35828. // Because we are modifying the entries (by converting string sources and
  35829. // names to indices into the sources and names ArraySets), we have to make
  35830. // a copy of the entry or else bad things happen. Shared mutable state
  35831. // strikes again! See github issue #191.
  35832. var generatedMappings = aSourceMap._mappings.toArray().slice();
  35833. var destGeneratedMappings = smc.__generatedMappings = [];
  35834. var destOriginalMappings = smc.__originalMappings = [];
  35835. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  35836. var srcMapping = generatedMappings[i];
  35837. var destMapping = new Mapping$1;
  35838. destMapping.generatedLine = srcMapping.generatedLine;
  35839. destMapping.generatedColumn = srcMapping.generatedColumn;
  35840. if (srcMapping.source) {
  35841. destMapping.source = sources.indexOf(srcMapping.source);
  35842. destMapping.originalLine = srcMapping.originalLine;
  35843. destMapping.originalColumn = srcMapping.originalColumn;
  35844. if (srcMapping.name) {
  35845. destMapping.name = names.indexOf(srcMapping.name);
  35846. }
  35847. destOriginalMappings.push(destMapping);
  35848. }
  35849. destGeneratedMappings.push(destMapping);
  35850. }
  35851. quickSort$3(smc.__originalMappings, util$1.compareByOriginalPositions);
  35852. return smc;
  35853. };
  35854. /**
  35855. * The version of the source mapping spec that we are consuming.
  35856. */
  35857. BasicSourceMapConsumer$1.prototype._version = 3;
  35858. /**
  35859. * The list of original sources.
  35860. */
  35861. Object.defineProperty(BasicSourceMapConsumer$1.prototype, 'sources', {
  35862. get: function () {
  35863. return this._absoluteSources.slice();
  35864. }
  35865. });
  35866. /**
  35867. * Provide the JIT with a nice shape / hidden class.
  35868. */
  35869. function Mapping$1() {
  35870. this.generatedLine = 0;
  35871. this.generatedColumn = 0;
  35872. this.source = null;
  35873. this.originalLine = null;
  35874. this.originalColumn = null;
  35875. this.name = null;
  35876. }
  35877. /**
  35878. * Parse the mappings in a string in to a data structure which we can easily
  35879. * query (the ordered arrays in the `this.__generatedMappings` and
  35880. * `this.__originalMappings` properties).
  35881. */
  35882. const compareGenerated = util$1.compareByGeneratedPositionsDeflatedNoLine;
  35883. function sortGenerated(array, start) {
  35884. let l = array.length;
  35885. let n = array.length - start;
  35886. if (n <= 1) {
  35887. return;
  35888. } else if (n == 2) {
  35889. let a = array[start];
  35890. let b = array[start + 1];
  35891. if (compareGenerated(a, b) > 0) {
  35892. array[start] = b;
  35893. array[start + 1] = a;
  35894. }
  35895. } else if (n < 20) {
  35896. for (let i = start; i < l; i++) {
  35897. for (let j = i; j > start; j--) {
  35898. let a = array[j - 1];
  35899. let b = array[j];
  35900. if (compareGenerated(a, b) <= 0) {
  35901. break;
  35902. }
  35903. array[j - 1] = b;
  35904. array[j] = a;
  35905. }
  35906. }
  35907. } else {
  35908. quickSort$3(array, compareGenerated, start);
  35909. }
  35910. }
  35911. BasicSourceMapConsumer$1.prototype._parseMappings =
  35912. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  35913. var generatedLine = 1;
  35914. var previousGeneratedColumn = 0;
  35915. var previousOriginalLine = 0;
  35916. var previousOriginalColumn = 0;
  35917. var previousSource = 0;
  35918. var previousName = 0;
  35919. var length = aStr.length;
  35920. var index = 0;
  35921. var temp = {};
  35922. var originalMappings = [];
  35923. var generatedMappings = [];
  35924. var mapping, segment, end, value;
  35925. let subarrayStart = 0;
  35926. while (index < length) {
  35927. if (aStr.charAt(index) === ';') {
  35928. generatedLine++;
  35929. index++;
  35930. previousGeneratedColumn = 0;
  35931. sortGenerated(generatedMappings, subarrayStart);
  35932. subarrayStart = generatedMappings.length;
  35933. }
  35934. else if (aStr.charAt(index) === ',') {
  35935. index++;
  35936. }
  35937. else {
  35938. mapping = new Mapping$1();
  35939. mapping.generatedLine = generatedLine;
  35940. for (end = index; end < length; end++) {
  35941. if (this._charIsMappingSeparator(aStr, end)) {
  35942. break;
  35943. }
  35944. }
  35945. aStr.slice(index, end);
  35946. segment = [];
  35947. while (index < end) {
  35948. base64Vlq$1.decode(aStr, index, temp);
  35949. value = temp.value;
  35950. index = temp.rest;
  35951. segment.push(value);
  35952. }
  35953. if (segment.length === 2) {
  35954. throw new Error('Found a source, but no line and column');
  35955. }
  35956. if (segment.length === 3) {
  35957. throw new Error('Found a source and line, but no column');
  35958. }
  35959. // Generated column.
  35960. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  35961. previousGeneratedColumn = mapping.generatedColumn;
  35962. if (segment.length > 1) {
  35963. // Original source.
  35964. mapping.source = previousSource + segment[1];
  35965. previousSource += segment[1];
  35966. // Original line.
  35967. mapping.originalLine = previousOriginalLine + segment[2];
  35968. previousOriginalLine = mapping.originalLine;
  35969. // Lines are stored 0-based
  35970. mapping.originalLine += 1;
  35971. // Original column.
  35972. mapping.originalColumn = previousOriginalColumn + segment[3];
  35973. previousOriginalColumn = mapping.originalColumn;
  35974. if (segment.length > 4) {
  35975. // Original name.
  35976. mapping.name = previousName + segment[4];
  35977. previousName += segment[4];
  35978. }
  35979. }
  35980. generatedMappings.push(mapping);
  35981. if (typeof mapping.originalLine === 'number') {
  35982. let currentSource = mapping.source;
  35983. while (originalMappings.length <= currentSource) {
  35984. originalMappings.push(null);
  35985. }
  35986. if (originalMappings[currentSource] === null) {
  35987. originalMappings[currentSource] = [];
  35988. }
  35989. originalMappings[currentSource].push(mapping);
  35990. }
  35991. }
  35992. }
  35993. sortGenerated(generatedMappings, subarrayStart);
  35994. this.__generatedMappings = generatedMappings;
  35995. for (var i = 0; i < originalMappings.length; i++) {
  35996. if (originalMappings[i] != null) {
  35997. quickSort$3(originalMappings[i], util$1.compareByOriginalPositionsNoSource);
  35998. }
  35999. }
  36000. this.__originalMappings = [].concat(...originalMappings);
  36001. };
  36002. /**
  36003. * Find the mapping that best matches the hypothetical "needle" mapping that
  36004. * we are searching for in the given "haystack" of mappings.
  36005. */
  36006. BasicSourceMapConsumer$1.prototype._findMapping =
  36007. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  36008. aColumnName, aComparator, aBias) {
  36009. // To return the position we are searching for, we must first find the
  36010. // mapping for the given position and then return the opposite position it
  36011. // points to. Because the mappings are sorted, we can use binary search to
  36012. // find the best mapping.
  36013. if (aNeedle[aLineName] <= 0) {
  36014. throw new TypeError('Line must be greater than or equal to 1, got '
  36015. + aNeedle[aLineName]);
  36016. }
  36017. if (aNeedle[aColumnName] < 0) {
  36018. throw new TypeError('Column must be greater than or equal to 0, got '
  36019. + aNeedle[aColumnName]);
  36020. }
  36021. return binarySearch$1.search(aNeedle, aMappings, aComparator, aBias);
  36022. };
  36023. /**
  36024. * Compute the last column for each generated mapping. The last column is
  36025. * inclusive.
  36026. */
  36027. BasicSourceMapConsumer$1.prototype.computeColumnSpans =
  36028. function SourceMapConsumer_computeColumnSpans() {
  36029. for (var index = 0; index < this._generatedMappings.length; ++index) {
  36030. var mapping = this._generatedMappings[index];
  36031. // Mappings do not contain a field for the last generated columnt. We
  36032. // can come up with an optimistic estimate, however, by assuming that
  36033. // mappings are contiguous (i.e. given two consecutive mappings, the
  36034. // first mapping ends where the second one starts).
  36035. if (index + 1 < this._generatedMappings.length) {
  36036. var nextMapping = this._generatedMappings[index + 1];
  36037. if (mapping.generatedLine === nextMapping.generatedLine) {
  36038. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  36039. continue;
  36040. }
  36041. }
  36042. // The last mapping for each line spans the entire line.
  36043. mapping.lastGeneratedColumn = Infinity;
  36044. }
  36045. };
  36046. /**
  36047. * Returns the original source, line, and column information for the generated
  36048. * source's line and column positions provided. The only argument is an object
  36049. * with the following properties:
  36050. *
  36051. * - line: The line number in the generated source. The line number
  36052. * is 1-based.
  36053. * - column: The column number in the generated source. The column
  36054. * number is 0-based.
  36055. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  36056. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  36057. * closest element that is smaller than or greater than the one we are
  36058. * searching for, respectively, if the exact element cannot be found.
  36059. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  36060. *
  36061. * and an object is returned with the following properties:
  36062. *
  36063. * - source: The original source file, or null.
  36064. * - line: The line number in the original source, or null. The
  36065. * line number is 1-based.
  36066. * - column: The column number in the original source, or null. The
  36067. * column number is 0-based.
  36068. * - name: The original identifier, or null.
  36069. */
  36070. BasicSourceMapConsumer$1.prototype.originalPositionFor =
  36071. function SourceMapConsumer_originalPositionFor(aArgs) {
  36072. var needle = {
  36073. generatedLine: util$1.getArg(aArgs, 'line'),
  36074. generatedColumn: util$1.getArg(aArgs, 'column')
  36075. };
  36076. var index = this._findMapping(
  36077. needle,
  36078. this._generatedMappings,
  36079. "generatedLine",
  36080. "generatedColumn",
  36081. util$1.compareByGeneratedPositionsDeflated,
  36082. util$1.getArg(aArgs, 'bias', SourceMapConsumer$2.GREATEST_LOWER_BOUND)
  36083. );
  36084. if (index >= 0) {
  36085. var mapping = this._generatedMappings[index];
  36086. if (mapping.generatedLine === needle.generatedLine) {
  36087. var source = util$1.getArg(mapping, 'source', null);
  36088. if (source !== null) {
  36089. source = this._sources.at(source);
  36090. source = util$1.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  36091. }
  36092. var name = util$1.getArg(mapping, 'name', null);
  36093. if (name !== null) {
  36094. name = this._names.at(name);
  36095. }
  36096. return {
  36097. source: source,
  36098. line: util$1.getArg(mapping, 'originalLine', null),
  36099. column: util$1.getArg(mapping, 'originalColumn', null),
  36100. name: name
  36101. };
  36102. }
  36103. }
  36104. return {
  36105. source: null,
  36106. line: null,
  36107. column: null,
  36108. name: null
  36109. };
  36110. };
  36111. /**
  36112. * Return true if we have the source content for every source in the source
  36113. * map, false otherwise.
  36114. */
  36115. BasicSourceMapConsumer$1.prototype.hasContentsOfAllSources =
  36116. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  36117. if (!this.sourcesContent) {
  36118. return false;
  36119. }
  36120. return this.sourcesContent.length >= this._sources.size() &&
  36121. !this.sourcesContent.some(function (sc) { return sc == null; });
  36122. };
  36123. /**
  36124. * Returns the original source content. The only argument is the url of the
  36125. * original source file. Returns null if no original source content is
  36126. * available.
  36127. */
  36128. BasicSourceMapConsumer$1.prototype.sourceContentFor =
  36129. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  36130. if (!this.sourcesContent) {
  36131. return null;
  36132. }
  36133. var index = this._findSourceIndex(aSource);
  36134. if (index >= 0) {
  36135. return this.sourcesContent[index];
  36136. }
  36137. var relativeSource = aSource;
  36138. if (this.sourceRoot != null) {
  36139. relativeSource = util$1.relative(this.sourceRoot, relativeSource);
  36140. }
  36141. var url;
  36142. if (this.sourceRoot != null
  36143. && (url = util$1.urlParse(this.sourceRoot))) {
  36144. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  36145. // many users. We can help them out when they expect file:// URIs to
  36146. // behave like it would if they were running a local HTTP server. See
  36147. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  36148. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  36149. if (url.scheme == "file"
  36150. && this._sources.has(fileUriAbsPath)) {
  36151. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  36152. }
  36153. if ((!url.path || url.path == "/")
  36154. && this._sources.has("/" + relativeSource)) {
  36155. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  36156. }
  36157. }
  36158. // This function is used recursively from
  36159. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  36160. // don't want to throw if we can't find the source - we just want to
  36161. // return null, so we provide a flag to exit gracefully.
  36162. if (nullOnMissing) {
  36163. return null;
  36164. }
  36165. else {
  36166. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  36167. }
  36168. };
  36169. /**
  36170. * Returns the generated line and column information for the original source,
  36171. * line, and column positions provided. The only argument is an object with
  36172. * the following properties:
  36173. *
  36174. * - source: The filename of the original source.
  36175. * - line: The line number in the original source. The line number
  36176. * is 1-based.
  36177. * - column: The column number in the original source. The column
  36178. * number is 0-based.
  36179. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  36180. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  36181. * closest element that is smaller than or greater than the one we are
  36182. * searching for, respectively, if the exact element cannot be found.
  36183. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  36184. *
  36185. * and an object is returned with the following properties:
  36186. *
  36187. * - line: The line number in the generated source, or null. The
  36188. * line number is 1-based.
  36189. * - column: The column number in the generated source, or null.
  36190. * The column number is 0-based.
  36191. */
  36192. BasicSourceMapConsumer$1.prototype.generatedPositionFor =
  36193. function SourceMapConsumer_generatedPositionFor(aArgs) {
  36194. var source = util$1.getArg(aArgs, 'source');
  36195. source = this._findSourceIndex(source);
  36196. if (source < 0) {
  36197. return {
  36198. line: null,
  36199. column: null,
  36200. lastColumn: null
  36201. };
  36202. }
  36203. var needle = {
  36204. source: source,
  36205. originalLine: util$1.getArg(aArgs, 'line'),
  36206. originalColumn: util$1.getArg(aArgs, 'column')
  36207. };
  36208. var index = this._findMapping(
  36209. needle,
  36210. this._originalMappings,
  36211. "originalLine",
  36212. "originalColumn",
  36213. util$1.compareByOriginalPositions,
  36214. util$1.getArg(aArgs, 'bias', SourceMapConsumer$2.GREATEST_LOWER_BOUND)
  36215. );
  36216. if (index >= 0) {
  36217. var mapping = this._originalMappings[index];
  36218. if (mapping.source === needle.source) {
  36219. return {
  36220. line: util$1.getArg(mapping, 'generatedLine', null),
  36221. column: util$1.getArg(mapping, 'generatedColumn', null),
  36222. lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
  36223. };
  36224. }
  36225. }
  36226. return {
  36227. line: null,
  36228. column: null,
  36229. lastColumn: null
  36230. };
  36231. };
  36232. var BasicSourceMapConsumer_1$1 = BasicSourceMapConsumer$1;
  36233. /**
  36234. * An IndexedSourceMapConsumer instance represents a parsed source map which
  36235. * we can query for information. It differs from BasicSourceMapConsumer in
  36236. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  36237. * input.
  36238. *
  36239. * The first parameter is a raw source map (either as a JSON string, or already
  36240. * parsed to an object). According to the spec for indexed source maps, they
  36241. * have the following attributes:
  36242. *
  36243. * - version: Which version of the source map spec this map is following.
  36244. * - file: Optional. The generated file this source map is associated with.
  36245. * - sections: A list of section definitions.
  36246. *
  36247. * Each value under the "sections" field has two fields:
  36248. * - offset: The offset into the original specified at which this section
  36249. * begins to apply, defined as an object with a "line" and "column"
  36250. * field.
  36251. * - map: A source map definition. This source map could also be indexed,
  36252. * but doesn't have to be.
  36253. *
  36254. * Instead of the "map" field, it's also possible to have a "url" field
  36255. * specifying a URL to retrieve a source map from, but that's currently
  36256. * unsupported.
  36257. *
  36258. * Here's an example source map, taken from the source map spec[0], but
  36259. * modified to omit a section which uses the "url" field.
  36260. *
  36261. * {
  36262. * version : 3,
  36263. * file: "app.js",
  36264. * sections: [{
  36265. * offset: {line:100, column:10},
  36266. * map: {
  36267. * version : 3,
  36268. * file: "section.js",
  36269. * sources: ["foo.js", "bar.js"],
  36270. * names: ["src", "maps", "are", "fun"],
  36271. * mappings: "AAAA,E;;ABCDE;"
  36272. * }
  36273. * }],
  36274. * }
  36275. *
  36276. * The second parameter, if given, is a string whose value is the URL
  36277. * at which the source map was found. This URL is used to compute the
  36278. * sources array.
  36279. *
  36280. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  36281. */
  36282. function IndexedSourceMapConsumer$1(aSourceMap, aSourceMapURL) {
  36283. var sourceMap = aSourceMap;
  36284. if (typeof aSourceMap === 'string') {
  36285. sourceMap = util$1.parseSourceMapInput(aSourceMap);
  36286. }
  36287. var version = util$1.getArg(sourceMap, 'version');
  36288. var sections = util$1.getArg(sourceMap, 'sections');
  36289. if (version != this._version) {
  36290. throw new Error('Unsupported version: ' + version);
  36291. }
  36292. this._sources = new ArraySet$5();
  36293. this._names = new ArraySet$5();
  36294. var lastOffset = {
  36295. line: -1,
  36296. column: 0
  36297. };
  36298. this._sections = sections.map(function (s) {
  36299. if (s.url) {
  36300. // The url field will require support for asynchronicity.
  36301. // See https://github.com/mozilla/source-map/issues/16
  36302. throw new Error('Support for url field in sections not implemented.');
  36303. }
  36304. var offset = util$1.getArg(s, 'offset');
  36305. var offsetLine = util$1.getArg(offset, 'line');
  36306. var offsetColumn = util$1.getArg(offset, 'column');
  36307. if (offsetLine < lastOffset.line ||
  36308. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  36309. throw new Error('Section offsets must be ordered and non-overlapping.');
  36310. }
  36311. lastOffset = offset;
  36312. return {
  36313. generatedOffset: {
  36314. // The offset fields are 0-based, but we use 1-based indices when
  36315. // encoding/decoding from VLQ.
  36316. generatedLine: offsetLine + 1,
  36317. generatedColumn: offsetColumn + 1
  36318. },
  36319. consumer: new SourceMapConsumer$2(util$1.getArg(s, 'map'), aSourceMapURL)
  36320. }
  36321. });
  36322. }
  36323. IndexedSourceMapConsumer$1.prototype = Object.create(SourceMapConsumer$2.prototype);
  36324. IndexedSourceMapConsumer$1.prototype.constructor = SourceMapConsumer$2;
  36325. /**
  36326. * The version of the source mapping spec that we are consuming.
  36327. */
  36328. IndexedSourceMapConsumer$1.prototype._version = 3;
  36329. /**
  36330. * The list of original sources.
  36331. */
  36332. Object.defineProperty(IndexedSourceMapConsumer$1.prototype, 'sources', {
  36333. get: function () {
  36334. var sources = [];
  36335. for (var i = 0; i < this._sections.length; i++) {
  36336. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  36337. sources.push(this._sections[i].consumer.sources[j]);
  36338. }
  36339. }
  36340. return sources;
  36341. }
  36342. });
  36343. /**
  36344. * Returns the original source, line, and column information for the generated
  36345. * source's line and column positions provided. The only argument is an object
  36346. * with the following properties:
  36347. *
  36348. * - line: The line number in the generated source. The line number
  36349. * is 1-based.
  36350. * - column: The column number in the generated source. The column
  36351. * number is 0-based.
  36352. *
  36353. * and an object is returned with the following properties:
  36354. *
  36355. * - source: The original source file, or null.
  36356. * - line: The line number in the original source, or null. The
  36357. * line number is 1-based.
  36358. * - column: The column number in the original source, or null. The
  36359. * column number is 0-based.
  36360. * - name: The original identifier, or null.
  36361. */
  36362. IndexedSourceMapConsumer$1.prototype.originalPositionFor =
  36363. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  36364. var needle = {
  36365. generatedLine: util$1.getArg(aArgs, 'line'),
  36366. generatedColumn: util$1.getArg(aArgs, 'column')
  36367. };
  36368. // Find the section containing the generated position we're trying to map
  36369. // to an original position.
  36370. var sectionIndex = binarySearch$1.search(needle, this._sections,
  36371. function(needle, section) {
  36372. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  36373. if (cmp) {
  36374. return cmp;
  36375. }
  36376. return (needle.generatedColumn -
  36377. section.generatedOffset.generatedColumn);
  36378. });
  36379. var section = this._sections[sectionIndex];
  36380. if (!section) {
  36381. return {
  36382. source: null,
  36383. line: null,
  36384. column: null,
  36385. name: null
  36386. };
  36387. }
  36388. return section.consumer.originalPositionFor({
  36389. line: needle.generatedLine -
  36390. (section.generatedOffset.generatedLine - 1),
  36391. column: needle.generatedColumn -
  36392. (section.generatedOffset.generatedLine === needle.generatedLine
  36393. ? section.generatedOffset.generatedColumn - 1
  36394. : 0),
  36395. bias: aArgs.bias
  36396. });
  36397. };
  36398. /**
  36399. * Return true if we have the source content for every source in the source
  36400. * map, false otherwise.
  36401. */
  36402. IndexedSourceMapConsumer$1.prototype.hasContentsOfAllSources =
  36403. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  36404. return this._sections.every(function (s) {
  36405. return s.consumer.hasContentsOfAllSources();
  36406. });
  36407. };
  36408. /**
  36409. * Returns the original source content. The only argument is the url of the
  36410. * original source file. Returns null if no original source content is
  36411. * available.
  36412. */
  36413. IndexedSourceMapConsumer$1.prototype.sourceContentFor =
  36414. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  36415. for (var i = 0; i < this._sections.length; i++) {
  36416. var section = this._sections[i];
  36417. var content = section.consumer.sourceContentFor(aSource, true);
  36418. if (content) {
  36419. return content;
  36420. }
  36421. }
  36422. if (nullOnMissing) {
  36423. return null;
  36424. }
  36425. else {
  36426. throw new Error('"' + aSource + '" is not in the SourceMap.');
  36427. }
  36428. };
  36429. /**
  36430. * Returns the generated line and column information for the original source,
  36431. * line, and column positions provided. The only argument is an object with
  36432. * the following properties:
  36433. *
  36434. * - source: The filename of the original source.
  36435. * - line: The line number in the original source. The line number
  36436. * is 1-based.
  36437. * - column: The column number in the original source. The column
  36438. * number is 0-based.
  36439. *
  36440. * and an object is returned with the following properties:
  36441. *
  36442. * - line: The line number in the generated source, or null. The
  36443. * line number is 1-based.
  36444. * - column: The column number in the generated source, or null.
  36445. * The column number is 0-based.
  36446. */
  36447. IndexedSourceMapConsumer$1.prototype.generatedPositionFor =
  36448. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  36449. for (var i = 0; i < this._sections.length; i++) {
  36450. var section = this._sections[i];
  36451. // Only consider this section if the requested source is in the list of
  36452. // sources of the consumer.
  36453. if (section.consumer._findSourceIndex(util$1.getArg(aArgs, 'source')) === -1) {
  36454. continue;
  36455. }
  36456. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  36457. if (generatedPosition) {
  36458. var ret = {
  36459. line: generatedPosition.line +
  36460. (section.generatedOffset.generatedLine - 1),
  36461. column: generatedPosition.column +
  36462. (section.generatedOffset.generatedLine === generatedPosition.line
  36463. ? section.generatedOffset.generatedColumn - 1
  36464. : 0)
  36465. };
  36466. return ret;
  36467. }
  36468. }
  36469. return {
  36470. line: null,
  36471. column: null
  36472. };
  36473. };
  36474. /**
  36475. * Parse the mappings in a string in to a data structure which we can easily
  36476. * query (the ordered arrays in the `this.__generatedMappings` and
  36477. * `this.__originalMappings` properties).
  36478. */
  36479. IndexedSourceMapConsumer$1.prototype._parseMappings =
  36480. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  36481. this.__generatedMappings = [];
  36482. this.__originalMappings = [];
  36483. for (var i = 0; i < this._sections.length; i++) {
  36484. var section = this._sections[i];
  36485. var sectionMappings = section.consumer._generatedMappings;
  36486. for (var j = 0; j < sectionMappings.length; j++) {
  36487. var mapping = sectionMappings[j];
  36488. var source = section.consumer._sources.at(mapping.source);
  36489. source = util$1.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  36490. this._sources.add(source);
  36491. source = this._sources.indexOf(source);
  36492. var name = null;
  36493. if (mapping.name) {
  36494. name = section.consumer._names.at(mapping.name);
  36495. this._names.add(name);
  36496. name = this._names.indexOf(name);
  36497. }
  36498. // The mappings coming from the consumer for the section have
  36499. // generated positions relative to the start of the section, so we
  36500. // need to offset them to be relative to the start of the concatenated
  36501. // generated file.
  36502. var adjustedMapping = {
  36503. source: source,
  36504. generatedLine: mapping.generatedLine +
  36505. (section.generatedOffset.generatedLine - 1),
  36506. generatedColumn: mapping.generatedColumn +
  36507. (section.generatedOffset.generatedLine === mapping.generatedLine
  36508. ? section.generatedOffset.generatedColumn - 1
  36509. : 0),
  36510. originalLine: mapping.originalLine,
  36511. originalColumn: mapping.originalColumn,
  36512. name: name
  36513. };
  36514. this.__generatedMappings.push(adjustedMapping);
  36515. if (typeof adjustedMapping.originalLine === 'number') {
  36516. this.__originalMappings.push(adjustedMapping);
  36517. }
  36518. }
  36519. }
  36520. quickSort$3(this.__generatedMappings, util$1.compareByGeneratedPositionsDeflated);
  36521. quickSort$3(this.__originalMappings, util$1.compareByOriginalPositions);
  36522. };
  36523. var IndexedSourceMapConsumer_1$1 = IndexedSourceMapConsumer$1;
  36524. var sourceMapConsumer$1 = {
  36525. SourceMapConsumer: SourceMapConsumer_1$1,
  36526. BasicSourceMapConsumer: BasicSourceMapConsumer_1$1,
  36527. IndexedSourceMapConsumer: IndexedSourceMapConsumer_1$1
  36528. };
  36529. /* -*- Mode: js; js-indent-level: 2; -*- */
  36530. /*
  36531. * Copyright 2011 Mozilla Foundation and contributors
  36532. * Licensed under the New BSD license. See LICENSE or:
  36533. * http://opensource.org/licenses/BSD-3-Clause
  36534. */
  36535. var SourceMapGenerator$4 = sourceMapGenerator$1.SourceMapGenerator;
  36536. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  36537. // operating systems these days (capturing the result).
  36538. var REGEX_NEWLINE$1 = /(\r?\n)/;
  36539. // Newline character code for charCodeAt() comparisons
  36540. var NEWLINE_CODE$1 = 10;
  36541. // Private symbol for identifying `SourceNode`s when multiple versions of
  36542. // the source-map library are loaded. This MUST NOT CHANGE across
  36543. // versions!
  36544. var isSourceNode$1 = "$$$isSourceNode$$$";
  36545. /**
  36546. * SourceNodes provide a way to abstract over interpolating/concatenating
  36547. * snippets of generated JavaScript source code while maintaining the line and
  36548. * column information associated with the original source code.
  36549. *
  36550. * @param aLine The original line number.
  36551. * @param aColumn The original column number.
  36552. * @param aSource The original source's filename.
  36553. * @param aChunks Optional. An array of strings which are snippets of
  36554. * generated JS, or other SourceNodes.
  36555. * @param aName The original identifier.
  36556. */
  36557. function SourceNode$2(aLine, aColumn, aSource, aChunks, aName) {
  36558. this.children = [];
  36559. this.sourceContents = {};
  36560. this.line = aLine == null ? null : aLine;
  36561. this.column = aColumn == null ? null : aColumn;
  36562. this.source = aSource == null ? null : aSource;
  36563. this.name = aName == null ? null : aName;
  36564. this[isSourceNode$1] = true;
  36565. if (aChunks != null) this.add(aChunks);
  36566. }
  36567. /**
  36568. * Creates a SourceNode from generated code and a SourceMapConsumer.
  36569. *
  36570. * @param aGeneratedCode The generated code
  36571. * @param aSourceMapConsumer The SourceMap for the generated code
  36572. * @param aRelativePath Optional. The path that relative sources in the
  36573. * SourceMapConsumer should be relative to.
  36574. */
  36575. SourceNode$2.fromStringWithSourceMap =
  36576. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  36577. // The SourceNode we want to fill with the generated code
  36578. // and the SourceMap
  36579. var node = new SourceNode$2();
  36580. // All even indices of this array are one line of the generated code,
  36581. // while all odd indices are the newlines between two adjacent lines
  36582. // (since `REGEX_NEWLINE` captures its match).
  36583. // Processed fragments are accessed by calling `shiftNextLine`.
  36584. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE$1);
  36585. var remainingLinesIndex = 0;
  36586. var shiftNextLine = function() {
  36587. var lineContents = getNextLine();
  36588. // The last line of a file might not have a newline.
  36589. var newLine = getNextLine() || "";
  36590. return lineContents + newLine;
  36591. function getNextLine() {
  36592. return remainingLinesIndex < remainingLines.length ?
  36593. remainingLines[remainingLinesIndex++] : undefined;
  36594. }
  36595. };
  36596. // We need to remember the position of "remainingLines"
  36597. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  36598. // The generate SourceNodes we need a code range.
  36599. // To extract it current and last mapping is used.
  36600. // Here we store the last mapping.
  36601. var lastMapping = null;
  36602. aSourceMapConsumer.eachMapping(function (mapping) {
  36603. if (lastMapping !== null) {
  36604. // We add the code from "lastMapping" to "mapping":
  36605. // First check if there is a new line in between.
  36606. if (lastGeneratedLine < mapping.generatedLine) {
  36607. // Associate first line with "lastMapping"
  36608. addMappingWithCode(lastMapping, shiftNextLine());
  36609. lastGeneratedLine++;
  36610. lastGeneratedColumn = 0;
  36611. // The remaining code is added without mapping
  36612. } else {
  36613. // There is no new line in between.
  36614. // Associate the code between "lastGeneratedColumn" and
  36615. // "mapping.generatedColumn" with "lastMapping"
  36616. var nextLine = remainingLines[remainingLinesIndex] || '';
  36617. var code = nextLine.substr(0, mapping.generatedColumn -
  36618. lastGeneratedColumn);
  36619. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  36620. lastGeneratedColumn);
  36621. lastGeneratedColumn = mapping.generatedColumn;
  36622. addMappingWithCode(lastMapping, code);
  36623. // No more remaining code, continue
  36624. lastMapping = mapping;
  36625. return;
  36626. }
  36627. }
  36628. // We add the generated code until the first mapping
  36629. // to the SourceNode without any mapping.
  36630. // Each line is added as separate string.
  36631. while (lastGeneratedLine < mapping.generatedLine) {
  36632. node.add(shiftNextLine());
  36633. lastGeneratedLine++;
  36634. }
  36635. if (lastGeneratedColumn < mapping.generatedColumn) {
  36636. var nextLine = remainingLines[remainingLinesIndex] || '';
  36637. node.add(nextLine.substr(0, mapping.generatedColumn));
  36638. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  36639. lastGeneratedColumn = mapping.generatedColumn;
  36640. }
  36641. lastMapping = mapping;
  36642. }, this);
  36643. // We have processed all mappings.
  36644. if (remainingLinesIndex < remainingLines.length) {
  36645. if (lastMapping) {
  36646. // Associate the remaining code in the current line with "lastMapping"
  36647. addMappingWithCode(lastMapping, shiftNextLine());
  36648. }
  36649. // and add the remaining lines without any mapping
  36650. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  36651. }
  36652. // Copy sourcesContent into SourceNode
  36653. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  36654. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  36655. if (content != null) {
  36656. if (aRelativePath != null) {
  36657. sourceFile = util$1.join(aRelativePath, sourceFile);
  36658. }
  36659. node.setSourceContent(sourceFile, content);
  36660. }
  36661. });
  36662. return node;
  36663. function addMappingWithCode(mapping, code) {
  36664. if (mapping === null || mapping.source === undefined) {
  36665. node.add(code);
  36666. } else {
  36667. var source = aRelativePath
  36668. ? util$1.join(aRelativePath, mapping.source)
  36669. : mapping.source;
  36670. node.add(new SourceNode$2(mapping.originalLine,
  36671. mapping.originalColumn,
  36672. source,
  36673. code,
  36674. mapping.name));
  36675. }
  36676. }
  36677. };
  36678. /**
  36679. * Add a chunk of generated JS to this source node.
  36680. *
  36681. * @param aChunk A string snippet of generated JS code, another instance of
  36682. * SourceNode, or an array where each member is one of those things.
  36683. */
  36684. SourceNode$2.prototype.add = function SourceNode_add(aChunk) {
  36685. if (Array.isArray(aChunk)) {
  36686. aChunk.forEach(function (chunk) {
  36687. this.add(chunk);
  36688. }, this);
  36689. }
  36690. else if (aChunk[isSourceNode$1] || typeof aChunk === "string") {
  36691. if (aChunk) {
  36692. this.children.push(aChunk);
  36693. }
  36694. }
  36695. else {
  36696. throw new TypeError(
  36697. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  36698. );
  36699. }
  36700. return this;
  36701. };
  36702. /**
  36703. * Add a chunk of generated JS to the beginning of this source node.
  36704. *
  36705. * @param aChunk A string snippet of generated JS code, another instance of
  36706. * SourceNode, or an array where each member is one of those things.
  36707. */
  36708. SourceNode$2.prototype.prepend = function SourceNode_prepend(aChunk) {
  36709. if (Array.isArray(aChunk)) {
  36710. for (var i = aChunk.length-1; i >= 0; i--) {
  36711. this.prepend(aChunk[i]);
  36712. }
  36713. }
  36714. else if (aChunk[isSourceNode$1] || typeof aChunk === "string") {
  36715. this.children.unshift(aChunk);
  36716. }
  36717. else {
  36718. throw new TypeError(
  36719. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  36720. );
  36721. }
  36722. return this;
  36723. };
  36724. /**
  36725. * Walk over the tree of JS snippets in this node and its children. The
  36726. * walking function is called once for each snippet of JS and is passed that
  36727. * snippet and the its original associated source's line/column location.
  36728. *
  36729. * @param aFn The traversal function.
  36730. */
  36731. SourceNode$2.prototype.walk = function SourceNode_walk(aFn) {
  36732. var chunk;
  36733. for (var i = 0, len = this.children.length; i < len; i++) {
  36734. chunk = this.children[i];
  36735. if (chunk[isSourceNode$1]) {
  36736. chunk.walk(aFn);
  36737. }
  36738. else {
  36739. if (chunk !== '') {
  36740. aFn(chunk, { source: this.source,
  36741. line: this.line,
  36742. column: this.column,
  36743. name: this.name });
  36744. }
  36745. }
  36746. }
  36747. };
  36748. /**
  36749. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  36750. * each of `this.children`.
  36751. *
  36752. * @param aSep The separator.
  36753. */
  36754. SourceNode$2.prototype.join = function SourceNode_join(aSep) {
  36755. var newChildren;
  36756. var i;
  36757. var len = this.children.length;
  36758. if (len > 0) {
  36759. newChildren = [];
  36760. for (i = 0; i < len-1; i++) {
  36761. newChildren.push(this.children[i]);
  36762. newChildren.push(aSep);
  36763. }
  36764. newChildren.push(this.children[i]);
  36765. this.children = newChildren;
  36766. }
  36767. return this;
  36768. };
  36769. /**
  36770. * Call String.prototype.replace on the very right-most source snippet. Useful
  36771. * for trimming whitespace from the end of a source node, etc.
  36772. *
  36773. * @param aPattern The pattern to replace.
  36774. * @param aReplacement The thing to replace the pattern with.
  36775. */
  36776. SourceNode$2.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  36777. var lastChild = this.children[this.children.length - 1];
  36778. if (lastChild[isSourceNode$1]) {
  36779. lastChild.replaceRight(aPattern, aReplacement);
  36780. }
  36781. else if (typeof lastChild === 'string') {
  36782. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  36783. }
  36784. else {
  36785. this.children.push(''.replace(aPattern, aReplacement));
  36786. }
  36787. return this;
  36788. };
  36789. /**
  36790. * Set the source content for a source file. This will be added to the SourceMapGenerator
  36791. * in the sourcesContent field.
  36792. *
  36793. * @param aSourceFile The filename of the source file
  36794. * @param aSourceContent The content of the source file
  36795. */
  36796. SourceNode$2.prototype.setSourceContent =
  36797. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  36798. this.sourceContents[util$1.toSetString(aSourceFile)] = aSourceContent;
  36799. };
  36800. /**
  36801. * Walk over the tree of SourceNodes. The walking function is called for each
  36802. * source file content and is passed the filename and source content.
  36803. *
  36804. * @param aFn The traversal function.
  36805. */
  36806. SourceNode$2.prototype.walkSourceContents =
  36807. function SourceNode_walkSourceContents(aFn) {
  36808. for (var i = 0, len = this.children.length; i < len; i++) {
  36809. if (this.children[i][isSourceNode$1]) {
  36810. this.children[i].walkSourceContents(aFn);
  36811. }
  36812. }
  36813. var sources = Object.keys(this.sourceContents);
  36814. for (var i = 0, len = sources.length; i < len; i++) {
  36815. aFn(util$1.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  36816. }
  36817. };
  36818. /**
  36819. * Return the string representation of this source node. Walks over the tree
  36820. * and concatenates all the various snippets together to one string.
  36821. */
  36822. SourceNode$2.prototype.toString = function SourceNode_toString() {
  36823. var str = "";
  36824. this.walk(function (chunk) {
  36825. str += chunk;
  36826. });
  36827. return str;
  36828. };
  36829. /**
  36830. * Returns the string representation of this source node along with a source
  36831. * map.
  36832. */
  36833. SourceNode$2.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  36834. var generated = {
  36835. code: "",
  36836. line: 1,
  36837. column: 0
  36838. };
  36839. var map = new SourceMapGenerator$4(aArgs);
  36840. var sourceMappingActive = false;
  36841. var lastOriginalSource = null;
  36842. var lastOriginalLine = null;
  36843. var lastOriginalColumn = null;
  36844. var lastOriginalName = null;
  36845. this.walk(function (chunk, original) {
  36846. generated.code += chunk;
  36847. if (original.source !== null
  36848. && original.line !== null
  36849. && original.column !== null) {
  36850. if(lastOriginalSource !== original.source
  36851. || lastOriginalLine !== original.line
  36852. || lastOriginalColumn !== original.column
  36853. || lastOriginalName !== original.name) {
  36854. map.addMapping({
  36855. source: original.source,
  36856. original: {
  36857. line: original.line,
  36858. column: original.column
  36859. },
  36860. generated: {
  36861. line: generated.line,
  36862. column: generated.column
  36863. },
  36864. name: original.name
  36865. });
  36866. }
  36867. lastOriginalSource = original.source;
  36868. lastOriginalLine = original.line;
  36869. lastOriginalColumn = original.column;
  36870. lastOriginalName = original.name;
  36871. sourceMappingActive = true;
  36872. } else if (sourceMappingActive) {
  36873. map.addMapping({
  36874. generated: {
  36875. line: generated.line,
  36876. column: generated.column
  36877. }
  36878. });
  36879. lastOriginalSource = null;
  36880. sourceMappingActive = false;
  36881. }
  36882. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  36883. if (chunk.charCodeAt(idx) === NEWLINE_CODE$1) {
  36884. generated.line++;
  36885. generated.column = 0;
  36886. // Mappings end at eol
  36887. if (idx + 1 === length) {
  36888. lastOriginalSource = null;
  36889. sourceMappingActive = false;
  36890. } else if (sourceMappingActive) {
  36891. map.addMapping({
  36892. source: original.source,
  36893. original: {
  36894. line: original.line,
  36895. column: original.column
  36896. },
  36897. generated: {
  36898. line: generated.line,
  36899. column: generated.column
  36900. },
  36901. name: original.name
  36902. });
  36903. }
  36904. } else {
  36905. generated.column++;
  36906. }
  36907. }
  36908. });
  36909. this.walkSourceContents(function (sourceFile, sourceContent) {
  36910. map.setSourceContent(sourceFile, sourceContent);
  36911. });
  36912. return { code: generated.code, map: map };
  36913. };
  36914. var SourceNode_1$1 = SourceNode$2;
  36915. var sourceNode$1 = {
  36916. SourceNode: SourceNode_1$1
  36917. };
  36918. /*
  36919. * Copyright 2009-2011 Mozilla Foundation and contributors
  36920. * Licensed under the New BSD license. See LICENSE.txt or:
  36921. * http://opensource.org/licenses/BSD-3-Clause
  36922. */
  36923. var SourceMapGenerator$5 = sourceMapGenerator$1.SourceMapGenerator;
  36924. var SourceMapConsumer$3 = sourceMapConsumer$1.SourceMapConsumer;
  36925. var SourceNode$3 = sourceNode$1.SourceNode;
  36926. var sourceMap$1 = {
  36927. SourceMapGenerator: SourceMapGenerator$5,
  36928. SourceMapConsumer: SourceMapConsumer$3,
  36929. SourceNode: SourceNode$3
  36930. };
  36931. let urlAlphabet =
  36932. 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
  36933. let customAlphabet = (alphabet, size) => {
  36934. return () => {
  36935. let id = '';
  36936. let i = size;
  36937. while (i--) {
  36938. id += alphabet[(Math.random() * alphabet.length) | 0];
  36939. }
  36940. return id
  36941. }
  36942. };
  36943. let nanoid = (size = 21) => {
  36944. let id = '';
  36945. let i = size;
  36946. while (i--) {
  36947. id += urlAlphabet[(Math.random() * 64) | 0];
  36948. }
  36949. return id
  36950. };
  36951. var nonSecure = { nanoid, customAlphabet };
  36952. let { SourceMapConsumer: SourceMapConsumer$4, SourceMapGenerator: SourceMapGenerator$6 } = sourceMap$1;
  36953. let { existsSync, readFileSync } = _fs;
  36954. let { dirname: dirname$1, join: join$1 } = _path;
  36955. function fromBase64(str) {
  36956. if (Buffer) {
  36957. return Buffer.from(str, 'base64').toString()
  36958. } else {
  36959. /* c8 ignore next 2 */
  36960. return window.atob(str)
  36961. }
  36962. }
  36963. class PreviousMap {
  36964. constructor(css, opts) {
  36965. if (opts.map === false) return
  36966. this.loadAnnotation(css);
  36967. this.inline = this.startWith(this.annotation, 'data:');
  36968. let prev = opts.map ? opts.map.prev : undefined;
  36969. let text = this.loadMap(opts.from, prev);
  36970. if (!this.mapFile && opts.from) {
  36971. this.mapFile = opts.from;
  36972. }
  36973. if (this.mapFile) this.root = dirname$1(this.mapFile);
  36974. if (text) this.text = text;
  36975. }
  36976. consumer() {
  36977. if (!this.consumerCache) {
  36978. this.consumerCache = new SourceMapConsumer$4(this.text);
  36979. }
  36980. return this.consumerCache
  36981. }
  36982. withContent() {
  36983. return !!(
  36984. this.consumer().sourcesContent &&
  36985. this.consumer().sourcesContent.length > 0
  36986. )
  36987. }
  36988. startWith(string, start) {
  36989. if (!string) return false
  36990. return string.substr(0, start.length) === start
  36991. }
  36992. getAnnotationURL(sourceMapString) {
  36993. return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, '').trim()
  36994. }
  36995. loadAnnotation(css) {
  36996. let comments = css.match(/\/\*\s*# sourceMappingURL=/gm);
  36997. if (!comments) return
  36998. // sourceMappingURLs from comments, strings, etc.
  36999. let start = css.lastIndexOf(comments.pop());
  37000. let end = css.indexOf('*/', start);
  37001. if (start > -1 && end > -1) {
  37002. // Locate the last sourceMappingURL to avoid pickin
  37003. this.annotation = this.getAnnotationURL(css.substring(start, end));
  37004. }
  37005. }
  37006. decodeInline(text) {
  37007. let baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/;
  37008. let baseUri = /^data:application\/json;base64,/;
  37009. let charsetUri = /^data:application\/json;charset=utf-?8,/;
  37010. let uri = /^data:application\/json,/;
  37011. if (charsetUri.test(text) || uri.test(text)) {
  37012. return decodeURIComponent(text.substr(RegExp.lastMatch.length))
  37013. }
  37014. if (baseCharsetUri.test(text) || baseUri.test(text)) {
  37015. return fromBase64(text.substr(RegExp.lastMatch.length))
  37016. }
  37017. let encoding = text.match(/data:application\/json;([^,]+),/)[1];
  37018. throw new Error('Unsupported source map encoding ' + encoding)
  37019. }
  37020. loadFile(path) {
  37021. this.root = dirname$1(path);
  37022. if (existsSync(path)) {
  37023. this.mapFile = path;
  37024. return readFileSync(path, 'utf-8').toString().trim()
  37025. }
  37026. }
  37027. loadMap(file, prev) {
  37028. if (prev === false) return false
  37029. if (prev) {
  37030. if (typeof prev === 'string') {
  37031. return prev
  37032. } else if (typeof prev === 'function') {
  37033. let prevPath = prev(file);
  37034. if (prevPath) {
  37035. let map = this.loadFile(prevPath);
  37036. if (!map) {
  37037. throw new Error(
  37038. 'Unable to load previous source map: ' + prevPath.toString()
  37039. )
  37040. }
  37041. return map
  37042. }
  37043. } else if (prev instanceof SourceMapConsumer$4) {
  37044. return SourceMapGenerator$6.fromSourceMap(prev).toString()
  37045. } else if (prev instanceof SourceMapGenerator$6) {
  37046. return prev.toString()
  37047. } else if (this.isMap(prev)) {
  37048. return JSON.stringify(prev)
  37049. } else {
  37050. throw new Error(
  37051. 'Unsupported previous source map format: ' + prev.toString()
  37052. )
  37053. }
  37054. } else if (this.inline) {
  37055. return this.decodeInline(this.annotation)
  37056. } else if (this.annotation) {
  37057. let map = this.annotation;
  37058. if (file) map = join$1(dirname$1(file), map);
  37059. return this.loadFile(map)
  37060. }
  37061. }
  37062. isMap(map) {
  37063. if (typeof map !== 'object') return false
  37064. return (
  37065. typeof map.mappings === 'string' ||
  37066. typeof map._mappings === 'string' ||
  37067. Array.isArray(map.sections)
  37068. )
  37069. }
  37070. }
  37071. var previousMap = PreviousMap;
  37072. PreviousMap.default = PreviousMap;
  37073. var require$$2 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_url$1);
  37074. let { SourceMapConsumer: SourceMapConsumer$5, SourceMapGenerator: SourceMapGenerator$7 } = sourceMap$1;
  37075. let { fileURLToPath, pathToFileURL } = require$$2;
  37076. let { resolve: resolve$1, isAbsolute: isAbsolute$1 } = _path;
  37077. let { nanoid: nanoid$1 } = nonSecure;
  37078. let fromOffsetCache = Symbol('fromOffsetCache');
  37079. let sourceMapAvailable = Boolean(SourceMapConsumer$5 && SourceMapGenerator$7);
  37080. let pathAvailable = Boolean(resolve$1 && isAbsolute$1);
  37081. class Input$1 {
  37082. constructor(css, opts = {}) {
  37083. if (
  37084. css === null ||
  37085. typeof css === 'undefined' ||
  37086. (typeof css === 'object' && !css.toString)
  37087. ) {
  37088. throw new Error(`PostCSS received ${css} instead of CSS string`)
  37089. }
  37090. this.css = css.toString();
  37091. if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') {
  37092. this.hasBOM = true;
  37093. this.css = this.css.slice(1);
  37094. } else {
  37095. this.hasBOM = false;
  37096. }
  37097. if (opts.from) {
  37098. if (
  37099. !pathAvailable ||
  37100. /^\w+:\/\//.test(opts.from) ||
  37101. isAbsolute$1(opts.from)
  37102. ) {
  37103. this.file = opts.from;
  37104. } else {
  37105. this.file = resolve$1(opts.from);
  37106. }
  37107. }
  37108. if (pathAvailable && sourceMapAvailable) {
  37109. let map = new previousMap(this.css, opts);
  37110. if (map.text) {
  37111. this.map = map;
  37112. let file = map.consumer().file;
  37113. if (!this.file && file) this.file = this.mapResolve(file);
  37114. }
  37115. }
  37116. if (!this.file) {
  37117. this.id = '<input css ' + nanoid$1(6) + '>';
  37118. }
  37119. if (this.map) this.map.file = this.from;
  37120. }
  37121. fromOffset(offset) {
  37122. let lastLine, lineToIndex;
  37123. if (!this[fromOffsetCache]) {
  37124. let lines = this.css.split('\n');
  37125. lineToIndex = new Array(lines.length);
  37126. let prevIndex = 0;
  37127. for (let i = 0, l = lines.length; i < l; i++) {
  37128. lineToIndex[i] = prevIndex;
  37129. prevIndex += lines[i].length + 1;
  37130. }
  37131. this[fromOffsetCache] = lineToIndex;
  37132. } else {
  37133. lineToIndex = this[fromOffsetCache];
  37134. }
  37135. lastLine = lineToIndex[lineToIndex.length - 1];
  37136. let min = 0;
  37137. if (offset >= lastLine) {
  37138. min = lineToIndex.length - 1;
  37139. } else {
  37140. let max = lineToIndex.length - 2;
  37141. let mid;
  37142. while (min < max) {
  37143. mid = min + ((max - min) >> 1);
  37144. if (offset < lineToIndex[mid]) {
  37145. max = mid - 1;
  37146. } else if (offset >= lineToIndex[mid + 1]) {
  37147. min = mid + 1;
  37148. } else {
  37149. min = mid;
  37150. break
  37151. }
  37152. }
  37153. }
  37154. return {
  37155. line: min + 1,
  37156. col: offset - lineToIndex[min] + 1
  37157. }
  37158. }
  37159. error(message, line, column, opts = {}) {
  37160. let result, endLine, endColumn;
  37161. if (line && typeof line === 'object') {
  37162. let start = line;
  37163. let end = column;
  37164. if (typeof line.offset === 'number') {
  37165. let pos = this.fromOffset(start.offset);
  37166. line = pos.line;
  37167. column = pos.col;
  37168. } else {
  37169. line = start.line;
  37170. column = start.column;
  37171. }
  37172. if (typeof end.offset === 'number') {
  37173. let pos = this.fromOffset(end.offset);
  37174. endLine = pos.line;
  37175. endColumn = pos.col;
  37176. } else {
  37177. endLine = end.line;
  37178. endColumn = end.column;
  37179. }
  37180. } else if (!column) {
  37181. let pos = this.fromOffset(line);
  37182. line = pos.line;
  37183. column = pos.col;
  37184. }
  37185. let origin = this.origin(line, column, endLine, endColumn);
  37186. if (origin) {
  37187. result = new cssSyntaxError(
  37188. message,
  37189. origin.endLine === undefined
  37190. ? origin.line
  37191. : { line: origin.line, column: origin.column },
  37192. origin.endLine === undefined
  37193. ? origin.column
  37194. : { line: origin.endLine, column: origin.endColumn },
  37195. origin.source,
  37196. origin.file,
  37197. opts.plugin
  37198. );
  37199. } else {
  37200. result = new cssSyntaxError(
  37201. message,
  37202. endLine === undefined ? line : { line, column },
  37203. endLine === undefined ? column : { line: endLine, column: endColumn },
  37204. this.css,
  37205. this.file,
  37206. opts.plugin
  37207. );
  37208. }
  37209. result.input = { line, column, endLine, endColumn, source: this.css };
  37210. if (this.file) {
  37211. if (pathToFileURL) {
  37212. result.input.url = pathToFileURL(this.file).toString();
  37213. }
  37214. result.input.file = this.file;
  37215. }
  37216. return result
  37217. }
  37218. origin(line, column, endLine, endColumn) {
  37219. if (!this.map) return false
  37220. let consumer = this.map.consumer();
  37221. let from = consumer.originalPositionFor({ line, column });
  37222. if (!from.source) return false
  37223. let to;
  37224. if (typeof endLine === 'number') {
  37225. to = consumer.originalPositionFor({ line: endLine, column: endColumn });
  37226. }
  37227. let fromUrl;
  37228. if (isAbsolute$1(from.source)) {
  37229. fromUrl = pathToFileURL(from.source);
  37230. } else {
  37231. fromUrl = new URL(
  37232. from.source,
  37233. this.map.consumer().sourceRoot || pathToFileURL(this.map.mapFile)
  37234. );
  37235. }
  37236. let result = {
  37237. url: fromUrl.toString(),
  37238. line: from.line,
  37239. column: from.column,
  37240. endLine: to && to.line,
  37241. endColumn: to && to.column
  37242. };
  37243. if (fromUrl.protocol === 'file:') {
  37244. if (fileURLToPath) {
  37245. result.file = fileURLToPath(fromUrl);
  37246. } else {
  37247. /* c8 ignore next 2 */
  37248. throw new Error(`file: protocol is not available in this PostCSS build`)
  37249. }
  37250. }
  37251. let source = consumer.sourceContentFor(from.source);
  37252. if (source) result.source = source;
  37253. return result
  37254. }
  37255. mapResolve(file) {
  37256. if (/^\w+:\/\//.test(file)) {
  37257. return file
  37258. }
  37259. return resolve$1(this.map.consumer().sourceRoot || this.map.root || '.', file)
  37260. }
  37261. get from() {
  37262. return this.file || this.id
  37263. }
  37264. toJSON() {
  37265. let json = {};
  37266. for (let name of ['hasBOM', 'css', 'file', 'id']) {
  37267. if (this[name] != null) {
  37268. json[name] = this[name];
  37269. }
  37270. }
  37271. if (this.map) {
  37272. json.map = { ...this.map };
  37273. if (json.map.consumerCache) {
  37274. json.map.consumerCache = undefined;
  37275. }
  37276. }
  37277. return json
  37278. }
  37279. }
  37280. var input = Input$1;
  37281. Input$1.default = Input$1;
  37282. if (terminalHighlight_1 && terminalHighlight_1.registerInput) {
  37283. terminalHighlight_1.registerInput(Input$1);
  37284. }
  37285. let { SourceMapConsumer: SourceMapConsumer$6, SourceMapGenerator: SourceMapGenerator$8 } = sourceMap$1;
  37286. let { dirname: dirname$2, resolve: resolve$2, relative: relative$1, sep: sep$1 } = _path;
  37287. let { pathToFileURL: pathToFileURL$1 } = require$$2;
  37288. let sourceMapAvailable$1 = Boolean(SourceMapConsumer$6 && SourceMapGenerator$8);
  37289. let pathAvailable$1 = Boolean(dirname$2 && resolve$2 && relative$1 && sep$1);
  37290. class MapGenerator {
  37291. constructor(stringify, root, opts, cssString) {
  37292. this.stringify = stringify;
  37293. this.mapOpts = opts.map || {};
  37294. this.root = root;
  37295. this.opts = opts;
  37296. this.css = cssString;
  37297. }
  37298. isMap() {
  37299. if (typeof this.opts.map !== 'undefined') {
  37300. return !!this.opts.map
  37301. }
  37302. return this.previous().length > 0
  37303. }
  37304. previous() {
  37305. if (!this.previousMaps) {
  37306. this.previousMaps = [];
  37307. if (this.root) {
  37308. this.root.walk(node => {
  37309. if (node.source && node.source.input.map) {
  37310. let map = node.source.input.map;
  37311. if (!this.previousMaps.includes(map)) {
  37312. this.previousMaps.push(map);
  37313. }
  37314. }
  37315. });
  37316. } else {
  37317. let input$1 = new input(this.css, this.opts);
  37318. if (input$1.map) this.previousMaps.push(input$1.map);
  37319. }
  37320. }
  37321. return this.previousMaps
  37322. }
  37323. isInline() {
  37324. if (typeof this.mapOpts.inline !== 'undefined') {
  37325. return this.mapOpts.inline
  37326. }
  37327. let annotation = this.mapOpts.annotation;
  37328. if (typeof annotation !== 'undefined' && annotation !== true) {
  37329. return false
  37330. }
  37331. if (this.previous().length) {
  37332. return this.previous().some(i => i.inline)
  37333. }
  37334. return true
  37335. }
  37336. isSourcesContent() {
  37337. if (typeof this.mapOpts.sourcesContent !== 'undefined') {
  37338. return this.mapOpts.sourcesContent
  37339. }
  37340. if (this.previous().length) {
  37341. return this.previous().some(i => i.withContent())
  37342. }
  37343. return true
  37344. }
  37345. clearAnnotation() {
  37346. if (this.mapOpts.annotation === false) return
  37347. if (this.root) {
  37348. let node;
  37349. for (let i = this.root.nodes.length - 1; i >= 0; i--) {
  37350. node = this.root.nodes[i];
  37351. if (node.type !== 'comment') continue
  37352. if (node.text.indexOf('# sourceMappingURL=') === 0) {
  37353. this.root.removeChild(i);
  37354. }
  37355. }
  37356. } else if (this.css) {
  37357. this.css = this.css.replace(/(\n)?\/\*#[\S\s]*?\*\/$/gm, '');
  37358. }
  37359. }
  37360. setSourcesContent() {
  37361. let already = {};
  37362. if (this.root) {
  37363. this.root.walk(node => {
  37364. if (node.source) {
  37365. let from = node.source.input.from;
  37366. if (from && !already[from]) {
  37367. already[from] = true;
  37368. this.map.setSourceContent(
  37369. this.toUrl(this.path(from)),
  37370. node.source.input.css
  37371. );
  37372. }
  37373. }
  37374. });
  37375. } else if (this.css) {
  37376. let from = this.opts.from
  37377. ? this.toUrl(this.path(this.opts.from))
  37378. : '<no source>';
  37379. this.map.setSourceContent(from, this.css);
  37380. }
  37381. }
  37382. applyPrevMaps() {
  37383. for (let prev of this.previous()) {
  37384. let from = this.toUrl(this.path(prev.file));
  37385. let root = prev.root || dirname$2(prev.file);
  37386. let map;
  37387. if (this.mapOpts.sourcesContent === false) {
  37388. map = new SourceMapConsumer$6(prev.text);
  37389. if (map.sourcesContent) {
  37390. map.sourcesContent = map.sourcesContent.map(() => null);
  37391. }
  37392. } else {
  37393. map = prev.consumer();
  37394. }
  37395. this.map.applySourceMap(map, from, this.toUrl(this.path(root)));
  37396. }
  37397. }
  37398. isAnnotation() {
  37399. if (this.isInline()) {
  37400. return true
  37401. }
  37402. if (typeof this.mapOpts.annotation !== 'undefined') {
  37403. return this.mapOpts.annotation
  37404. }
  37405. if (this.previous().length) {
  37406. return this.previous().some(i => i.annotation)
  37407. }
  37408. return true
  37409. }
  37410. toBase64(str) {
  37411. if (Buffer) {
  37412. return Buffer.from(str).toString('base64')
  37413. } else {
  37414. return window.btoa(unescape(encodeURIComponent(str)))
  37415. }
  37416. }
  37417. addAnnotation() {
  37418. let content;
  37419. if (this.isInline()) {
  37420. content =
  37421. 'data:application/json;base64,' + this.toBase64(this.map.toString());
  37422. } else if (typeof this.mapOpts.annotation === 'string') {
  37423. content = this.mapOpts.annotation;
  37424. } else if (typeof this.mapOpts.annotation === 'function') {
  37425. content = this.mapOpts.annotation(this.opts.to, this.root);
  37426. } else {
  37427. content = this.outputFile() + '.map';
  37428. }
  37429. let eol = '\n';
  37430. if (this.css.includes('\r\n')) eol = '\r\n';
  37431. this.css += eol + '/*# sourceMappingURL=' + content + ' */';
  37432. }
  37433. outputFile() {
  37434. if (this.opts.to) {
  37435. return this.path(this.opts.to)
  37436. } else if (this.opts.from) {
  37437. return this.path(this.opts.from)
  37438. } else {
  37439. return 'to.css'
  37440. }
  37441. }
  37442. generateMap() {
  37443. if (this.root) {
  37444. this.generateString();
  37445. } else if (this.previous().length === 1) {
  37446. let prev = this.previous()[0].consumer();
  37447. prev.file = this.outputFile();
  37448. this.map = SourceMapGenerator$8.fromSourceMap(prev);
  37449. } else {
  37450. this.map = new SourceMapGenerator$8({ file: this.outputFile() });
  37451. this.map.addMapping({
  37452. source: this.opts.from
  37453. ? this.toUrl(this.path(this.opts.from))
  37454. : '<no source>',
  37455. generated: { line: 1, column: 0 },
  37456. original: { line: 1, column: 0 }
  37457. });
  37458. }
  37459. if (this.isSourcesContent()) this.setSourcesContent();
  37460. if (this.root && this.previous().length > 0) this.applyPrevMaps();
  37461. if (this.isAnnotation()) this.addAnnotation();
  37462. if (this.isInline()) {
  37463. return [this.css]
  37464. } else {
  37465. return [this.css, this.map]
  37466. }
  37467. }
  37468. path(file) {
  37469. if (file.indexOf('<') === 0) return file
  37470. if (/^\w+:\/\//.test(file)) return file
  37471. if (this.mapOpts.absolute) return file
  37472. let from = this.opts.to ? dirname$2(this.opts.to) : '.';
  37473. if (typeof this.mapOpts.annotation === 'string') {
  37474. from = dirname$2(resolve$2(from, this.mapOpts.annotation));
  37475. }
  37476. file = relative$1(from, file);
  37477. return file
  37478. }
  37479. toUrl(path) {
  37480. if (sep$1 === '\\') {
  37481. path = path.replace(/\\/g, '/');
  37482. }
  37483. return encodeURI(path).replace(/[#?]/g, encodeURIComponent)
  37484. }
  37485. sourcePath(node) {
  37486. if (this.mapOpts.from) {
  37487. return this.toUrl(this.mapOpts.from)
  37488. } else if (this.mapOpts.absolute) {
  37489. if (pathToFileURL$1) {
  37490. return pathToFileURL$1(node.source.input.from).toString()
  37491. } else {
  37492. throw new Error(
  37493. '`map.absolute` option is not available in this PostCSS build'
  37494. )
  37495. }
  37496. } else {
  37497. return this.toUrl(this.path(node.source.input.from))
  37498. }
  37499. }
  37500. generateString() {
  37501. this.css = '';
  37502. this.map = new SourceMapGenerator$8({ file: this.outputFile() });
  37503. let line = 1;
  37504. let column = 1;
  37505. let noSource = '<no source>';
  37506. let mapping = {
  37507. source: '',
  37508. generated: { line: 0, column: 0 },
  37509. original: { line: 0, column: 0 }
  37510. };
  37511. let lines, last;
  37512. this.stringify(this.root, (str, node, type) => {
  37513. this.css += str;
  37514. if (node && type !== 'end') {
  37515. mapping.generated.line = line;
  37516. mapping.generated.column = column - 1;
  37517. if (node.source && node.source.start) {
  37518. mapping.source = this.sourcePath(node);
  37519. mapping.original.line = node.source.start.line;
  37520. mapping.original.column = node.source.start.column - 1;
  37521. this.map.addMapping(mapping);
  37522. } else {
  37523. mapping.source = noSource;
  37524. mapping.original.line = 1;
  37525. mapping.original.column = 0;
  37526. this.map.addMapping(mapping);
  37527. }
  37528. }
  37529. lines = str.match(/\n/g);
  37530. if (lines) {
  37531. line += lines.length;
  37532. last = str.lastIndexOf('\n');
  37533. column = str.length - last;
  37534. } else {
  37535. column += str.length;
  37536. }
  37537. if (node && type !== 'start') {
  37538. let p = node.parent || { raws: {} };
  37539. if (node.type !== 'decl' || node !== p.last || p.raws.semicolon) {
  37540. if (node.source && node.source.end) {
  37541. mapping.source = this.sourcePath(node);
  37542. mapping.original.line = node.source.end.line;
  37543. mapping.original.column = node.source.end.column - 1;
  37544. mapping.generated.line = line;
  37545. mapping.generated.column = column - 2;
  37546. this.map.addMapping(mapping);
  37547. } else {
  37548. mapping.source = noSource;
  37549. mapping.original.line = 1;
  37550. mapping.original.column = 0;
  37551. mapping.generated.line = line;
  37552. mapping.generated.column = column - 1;
  37553. this.map.addMapping(mapping);
  37554. }
  37555. }
  37556. }
  37557. });
  37558. }
  37559. generate() {
  37560. this.clearAnnotation();
  37561. if (pathAvailable$1 && sourceMapAvailable$1 && this.isMap()) {
  37562. return this.generateMap()
  37563. } else {
  37564. let result = '';
  37565. this.stringify(this.root, i => {
  37566. result += i;
  37567. });
  37568. return [result]
  37569. }
  37570. }
  37571. }
  37572. var mapGenerator = MapGenerator;
  37573. class Comment extends node_1 {
  37574. constructor(defaults) {
  37575. super(defaults);
  37576. this.type = 'comment';
  37577. }
  37578. }
  37579. var comment = Comment;
  37580. Comment.default = Comment;
  37581. let { isClean: isClean$2, my: my$2 } = symbols;
  37582. let parse$5, Rule, AtRule;
  37583. function cleanSource(nodes) {
  37584. return nodes.map(i => {
  37585. if (i.nodes) i.nodes = cleanSource(i.nodes);
  37586. delete i.source;
  37587. return i
  37588. })
  37589. }
  37590. function markDirtyUp(node) {
  37591. node[isClean$2] = false;
  37592. if (node.proxyOf.nodes) {
  37593. for (let i of node.proxyOf.nodes) {
  37594. markDirtyUp(i);
  37595. }
  37596. }
  37597. }
  37598. class Container extends node_1 {
  37599. push(child) {
  37600. child.parent = this;
  37601. this.proxyOf.nodes.push(child);
  37602. return this
  37603. }
  37604. each(callback) {
  37605. if (!this.proxyOf.nodes) return undefined
  37606. let iterator = this.getIterator();
  37607. let index, result;
  37608. while (this.indexes[iterator] < this.proxyOf.nodes.length) {
  37609. index = this.indexes[iterator];
  37610. result = callback(this.proxyOf.nodes[index], index);
  37611. if (result === false) break
  37612. this.indexes[iterator] += 1;
  37613. }
  37614. delete this.indexes[iterator];
  37615. return result
  37616. }
  37617. walk(callback) {
  37618. return this.each((child, i) => {
  37619. let result;
  37620. try {
  37621. result = callback(child, i);
  37622. } catch (e) {
  37623. throw child.addToError(e)
  37624. }
  37625. if (result !== false && child.walk) {
  37626. result = child.walk(callback);
  37627. }
  37628. return result
  37629. })
  37630. }
  37631. walkDecls(prop, callback) {
  37632. if (!callback) {
  37633. callback = prop;
  37634. return this.walk((child, i) => {
  37635. if (child.type === 'decl') {
  37636. return callback(child, i)
  37637. }
  37638. })
  37639. }
  37640. if (prop instanceof RegExp) {
  37641. return this.walk((child, i) => {
  37642. if (child.type === 'decl' && prop.test(child.prop)) {
  37643. return callback(child, i)
  37644. }
  37645. })
  37646. }
  37647. return this.walk((child, i) => {
  37648. if (child.type === 'decl' && child.prop === prop) {
  37649. return callback(child, i)
  37650. }
  37651. })
  37652. }
  37653. walkRules(selector, callback) {
  37654. if (!callback) {
  37655. callback = selector;
  37656. return this.walk((child, i) => {
  37657. if (child.type === 'rule') {
  37658. return callback(child, i)
  37659. }
  37660. })
  37661. }
  37662. if (selector instanceof RegExp) {
  37663. return this.walk((child, i) => {
  37664. if (child.type === 'rule' && selector.test(child.selector)) {
  37665. return callback(child, i)
  37666. }
  37667. })
  37668. }
  37669. return this.walk((child, i) => {
  37670. if (child.type === 'rule' && child.selector === selector) {
  37671. return callback(child, i)
  37672. }
  37673. })
  37674. }
  37675. walkAtRules(name, callback) {
  37676. if (!callback) {
  37677. callback = name;
  37678. return this.walk((child, i) => {
  37679. if (child.type === 'atrule') {
  37680. return callback(child, i)
  37681. }
  37682. })
  37683. }
  37684. if (name instanceof RegExp) {
  37685. return this.walk((child, i) => {
  37686. if (child.type === 'atrule' && name.test(child.name)) {
  37687. return callback(child, i)
  37688. }
  37689. })
  37690. }
  37691. return this.walk((child, i) => {
  37692. if (child.type === 'atrule' && child.name === name) {
  37693. return callback(child, i)
  37694. }
  37695. })
  37696. }
  37697. walkComments(callback) {
  37698. return this.walk((child, i) => {
  37699. if (child.type === 'comment') {
  37700. return callback(child, i)
  37701. }
  37702. })
  37703. }
  37704. append(...children) {
  37705. for (let child of children) {
  37706. let nodes = this.normalize(child, this.last);
  37707. for (let node of nodes) this.proxyOf.nodes.push(node);
  37708. }
  37709. this.markDirty();
  37710. return this
  37711. }
  37712. prepend(...children) {
  37713. children = children.reverse();
  37714. for (let child of children) {
  37715. let nodes = this.normalize(child, this.first, 'prepend').reverse();
  37716. for (let node of nodes) this.proxyOf.nodes.unshift(node);
  37717. for (let id in this.indexes) {
  37718. this.indexes[id] = this.indexes[id] + nodes.length;
  37719. }
  37720. }
  37721. this.markDirty();
  37722. return this
  37723. }
  37724. cleanRaws(keepBetween) {
  37725. super.cleanRaws(keepBetween);
  37726. if (this.nodes) {
  37727. for (let node of this.nodes) node.cleanRaws(keepBetween);
  37728. }
  37729. }
  37730. insertBefore(exist, add) {
  37731. exist = this.index(exist);
  37732. let type = exist === 0 ? 'prepend' : false;
  37733. let nodes = this.normalize(add, this.proxyOf.nodes[exist], type).reverse();
  37734. for (let node of nodes) this.proxyOf.nodes.splice(exist, 0, node);
  37735. let index;
  37736. for (let id in this.indexes) {
  37737. index = this.indexes[id];
  37738. if (exist <= index) {
  37739. this.indexes[id] = index + nodes.length;
  37740. }
  37741. }
  37742. this.markDirty();
  37743. return this
  37744. }
  37745. insertAfter(exist, add) {
  37746. exist = this.index(exist);
  37747. let nodes = this.normalize(add, this.proxyOf.nodes[exist]).reverse();
  37748. for (let node of nodes) this.proxyOf.nodes.splice(exist + 1, 0, node);
  37749. let index;
  37750. for (let id in this.indexes) {
  37751. index = this.indexes[id];
  37752. if (exist < index) {
  37753. this.indexes[id] = index + nodes.length;
  37754. }
  37755. }
  37756. this.markDirty();
  37757. return this
  37758. }
  37759. removeChild(child) {
  37760. child = this.index(child);
  37761. this.proxyOf.nodes[child].parent = undefined;
  37762. this.proxyOf.nodes.splice(child, 1);
  37763. let index;
  37764. for (let id in this.indexes) {
  37765. index = this.indexes[id];
  37766. if (index >= child) {
  37767. this.indexes[id] = index - 1;
  37768. }
  37769. }
  37770. this.markDirty();
  37771. return this
  37772. }
  37773. removeAll() {
  37774. for (let node of this.proxyOf.nodes) node.parent = undefined;
  37775. this.proxyOf.nodes = [];
  37776. this.markDirty();
  37777. return this
  37778. }
  37779. replaceValues(pattern, opts, callback) {
  37780. if (!callback) {
  37781. callback = opts;
  37782. opts = {};
  37783. }
  37784. this.walkDecls(decl => {
  37785. if (opts.props && !opts.props.includes(decl.prop)) return
  37786. if (opts.fast && !decl.value.includes(opts.fast)) return
  37787. decl.value = decl.value.replace(pattern, callback);
  37788. });
  37789. this.markDirty();
  37790. return this
  37791. }
  37792. every(condition) {
  37793. return this.nodes.every(condition)
  37794. }
  37795. some(condition) {
  37796. return this.nodes.some(condition)
  37797. }
  37798. index(child) {
  37799. if (typeof child === 'number') return child
  37800. if (child.proxyOf) child = child.proxyOf;
  37801. return this.proxyOf.nodes.indexOf(child)
  37802. }
  37803. get first() {
  37804. if (!this.proxyOf.nodes) return undefined
  37805. return this.proxyOf.nodes[0]
  37806. }
  37807. get last() {
  37808. if (!this.proxyOf.nodes) return undefined
  37809. return this.proxyOf.nodes[this.proxyOf.nodes.length - 1]
  37810. }
  37811. normalize(nodes, sample) {
  37812. if (typeof nodes === 'string') {
  37813. nodes = cleanSource(parse$5(nodes).nodes);
  37814. } else if (Array.isArray(nodes)) {
  37815. nodes = nodes.slice(0);
  37816. for (let i of nodes) {
  37817. if (i.parent) i.parent.removeChild(i, 'ignore');
  37818. }
  37819. } else if (nodes.type === 'root' && this.type !== 'document') {
  37820. nodes = nodes.nodes.slice(0);
  37821. for (let i of nodes) {
  37822. if (i.parent) i.parent.removeChild(i, 'ignore');
  37823. }
  37824. } else if (nodes.type) {
  37825. nodes = [nodes];
  37826. } else if (nodes.prop) {
  37827. if (typeof nodes.value === 'undefined') {
  37828. throw new Error('Value field is missed in node creation')
  37829. } else if (typeof nodes.value !== 'string') {
  37830. nodes.value = String(nodes.value);
  37831. }
  37832. nodes = [new declaration(nodes)];
  37833. } else if (nodes.selector) {
  37834. nodes = [new Rule(nodes)];
  37835. } else if (nodes.name) {
  37836. nodes = [new AtRule(nodes)];
  37837. } else if (nodes.text) {
  37838. nodes = [new comment(nodes)];
  37839. } else {
  37840. throw new Error('Unknown node type in node creation')
  37841. }
  37842. let processed = nodes.map(i => {
  37843. /* c8 ignore next */
  37844. if (!i[my$2]) Container.rebuild(i);
  37845. i = i.proxyOf;
  37846. if (i.parent) i.parent.removeChild(i);
  37847. if (i[isClean$2]) markDirtyUp(i);
  37848. if (typeof i.raws.before === 'undefined') {
  37849. if (sample && typeof sample.raws.before !== 'undefined') {
  37850. i.raws.before = sample.raws.before.replace(/\S/g, '');
  37851. }
  37852. }
  37853. i.parent = this;
  37854. return i
  37855. });
  37856. return processed
  37857. }
  37858. getProxyProcessor() {
  37859. return {
  37860. set(node, prop, value) {
  37861. if (node[prop] === value) return true
  37862. node[prop] = value;
  37863. if (prop === 'name' || prop === 'params' || prop === 'selector') {
  37864. node.markDirty();
  37865. }
  37866. return true
  37867. },
  37868. get(node, prop) {
  37869. if (prop === 'proxyOf') {
  37870. return node
  37871. } else if (!node[prop]) {
  37872. return node[prop]
  37873. } else if (
  37874. prop === 'each' ||
  37875. (typeof prop === 'string' && prop.startsWith('walk'))
  37876. ) {
  37877. return (...args) => {
  37878. return node[prop](
  37879. ...args.map(i => {
  37880. if (typeof i === 'function') {
  37881. return (child, index) => i(child.toProxy(), index)
  37882. } else {
  37883. return i
  37884. }
  37885. })
  37886. )
  37887. }
  37888. } else if (prop === 'every' || prop === 'some') {
  37889. return cb => {
  37890. return node[prop]((child, ...other) =>
  37891. cb(child.toProxy(), ...other)
  37892. )
  37893. }
  37894. } else if (prop === 'root') {
  37895. return () => node.root().toProxy()
  37896. } else if (prop === 'nodes') {
  37897. return node.nodes.map(i => i.toProxy())
  37898. } else if (prop === 'first' || prop === 'last') {
  37899. return node[prop].toProxy()
  37900. } else {
  37901. return node[prop]
  37902. }
  37903. }
  37904. }
  37905. }
  37906. getIterator() {
  37907. if (!this.lastEach) this.lastEach = 0;
  37908. if (!this.indexes) this.indexes = {};
  37909. this.lastEach += 1;
  37910. let iterator = this.lastEach;
  37911. this.indexes[iterator] = 0;
  37912. return iterator
  37913. }
  37914. }
  37915. Container.registerParse = dependant => {
  37916. parse$5 = dependant;
  37917. };
  37918. Container.registerRule = dependant => {
  37919. Rule = dependant;
  37920. };
  37921. Container.registerAtRule = dependant => {
  37922. AtRule = dependant;
  37923. };
  37924. var container = Container;
  37925. Container.default = Container;
  37926. /* c8 ignore start */
  37927. Container.rebuild = node => {
  37928. if (node.type === 'atrule') {
  37929. Object.setPrototypeOf(node, AtRule.prototype);
  37930. } else if (node.type === 'rule') {
  37931. Object.setPrototypeOf(node, Rule.prototype);
  37932. } else if (node.type === 'decl') {
  37933. Object.setPrototypeOf(node, declaration.prototype);
  37934. } else if (node.type === 'comment') {
  37935. Object.setPrototypeOf(node, comment.prototype);
  37936. }
  37937. node[my$2] = true;
  37938. if (node.nodes) {
  37939. node.nodes.forEach(child => {
  37940. Container.rebuild(child);
  37941. });
  37942. }
  37943. };
  37944. let LazyResult, Processor;
  37945. class Document extends container {
  37946. constructor(defaults) {
  37947. // type needs to be passed to super, otherwise child roots won't be normalized correctly
  37948. super({ type: 'document', ...defaults });
  37949. if (!this.nodes) {
  37950. this.nodes = [];
  37951. }
  37952. }
  37953. toResult(opts = {}) {
  37954. let lazy = new LazyResult(new Processor(), this, opts);
  37955. return lazy.stringify()
  37956. }
  37957. }
  37958. Document.registerLazyResult = dependant => {
  37959. LazyResult = dependant;
  37960. };
  37961. Document.registerProcessor = dependant => {
  37962. Processor = dependant;
  37963. };
  37964. var document = Document;
  37965. Document.default = Document;
  37966. /* eslint-disable no-console */
  37967. let printed = {};
  37968. var warnOnce$2 = function warnOnce(message) {
  37969. if (printed[message]) return
  37970. printed[message] = true;
  37971. if (typeof console !== 'undefined' && console.warn) {
  37972. console.warn(message);
  37973. }
  37974. };
  37975. class Warning {
  37976. constructor(text, opts = {}) {
  37977. this.type = 'warning';
  37978. this.text = text;
  37979. if (opts.node && opts.node.source) {
  37980. let range = opts.node.rangeBy(opts);
  37981. this.line = range.start.line;
  37982. this.column = range.start.column;
  37983. this.endLine = range.end.line;
  37984. this.endColumn = range.end.column;
  37985. }
  37986. for (let opt in opts) this[opt] = opts[opt];
  37987. }
  37988. toString() {
  37989. if (this.node) {
  37990. return this.node.error(this.text, {
  37991. plugin: this.plugin,
  37992. index: this.index,
  37993. word: this.word
  37994. }).message
  37995. }
  37996. if (this.plugin) {
  37997. return this.plugin + ': ' + this.text
  37998. }
  37999. return this.text
  38000. }
  38001. }
  38002. var warning = Warning;
  38003. Warning.default = Warning;
  38004. class Result {
  38005. constructor(processor, root, opts) {
  38006. this.processor = processor;
  38007. this.messages = [];
  38008. this.root = root;
  38009. this.opts = opts;
  38010. this.css = undefined;
  38011. this.map = undefined;
  38012. }
  38013. toString() {
  38014. return this.css
  38015. }
  38016. warn(text, opts = {}) {
  38017. if (!opts.plugin) {
  38018. if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
  38019. opts.plugin = this.lastPlugin.postcssPlugin;
  38020. }
  38021. }
  38022. let warning$1 = new warning(text, opts);
  38023. this.messages.push(warning$1);
  38024. return warning$1
  38025. }
  38026. warnings() {
  38027. return this.messages.filter(i => i.type === 'warning')
  38028. }
  38029. get content() {
  38030. return this.css
  38031. }
  38032. }
  38033. var result = Result;
  38034. Result.default = Result;
  38035. class AtRule$1 extends container {
  38036. constructor(defaults) {
  38037. super(defaults);
  38038. this.type = 'atrule';
  38039. }
  38040. append(...children) {
  38041. if (!this.proxyOf.nodes) this.nodes = [];
  38042. return super.append(...children)
  38043. }
  38044. prepend(...children) {
  38045. if (!this.proxyOf.nodes) this.nodes = [];
  38046. return super.prepend(...children)
  38047. }
  38048. }
  38049. var atRule = AtRule$1;
  38050. AtRule$1.default = AtRule$1;
  38051. container.registerAtRule(AtRule$1);
  38052. let LazyResult$1, Processor$1;
  38053. class Root extends container {
  38054. constructor(defaults) {
  38055. super(defaults);
  38056. this.type = 'root';
  38057. if (!this.nodes) this.nodes = [];
  38058. }
  38059. removeChild(child, ignore) {
  38060. let index = this.index(child);
  38061. if (!ignore && index === 0 && this.nodes.length > 1) {
  38062. this.nodes[1].raws.before = this.nodes[index].raws.before;
  38063. }
  38064. return super.removeChild(child)
  38065. }
  38066. normalize(child, sample, type) {
  38067. let nodes = super.normalize(child);
  38068. if (sample) {
  38069. if (type === 'prepend') {
  38070. if (this.nodes.length > 1) {
  38071. sample.raws.before = this.nodes[1].raws.before;
  38072. } else {
  38073. delete sample.raws.before;
  38074. }
  38075. } else if (this.first !== sample) {
  38076. for (let node of nodes) {
  38077. node.raws.before = sample.raws.before;
  38078. }
  38079. }
  38080. }
  38081. return nodes
  38082. }
  38083. toResult(opts = {}) {
  38084. let lazy = new LazyResult$1(new Processor$1(), this, opts);
  38085. return lazy.stringify()
  38086. }
  38087. }
  38088. Root.registerLazyResult = dependant => {
  38089. LazyResult$1 = dependant;
  38090. };
  38091. Root.registerProcessor = dependant => {
  38092. Processor$1 = dependant;
  38093. };
  38094. var root = Root;
  38095. Root.default = Root;
  38096. let list = {
  38097. split(string, separators, last) {
  38098. let array = [];
  38099. let current = '';
  38100. let split = false;
  38101. let func = 0;
  38102. let quote = false;
  38103. let escape = false;
  38104. for (let letter of string) {
  38105. if (escape) {
  38106. escape = false;
  38107. } else if (letter === '\\') {
  38108. escape = true;
  38109. } else if (quote) {
  38110. if (letter === quote) {
  38111. quote = false;
  38112. }
  38113. } else if (letter === '"' || letter === "'") {
  38114. quote = letter;
  38115. } else if (letter === '(') {
  38116. func += 1;
  38117. } else if (letter === ')') {
  38118. if (func > 0) func -= 1;
  38119. } else if (func === 0) {
  38120. if (separators.includes(letter)) split = true;
  38121. }
  38122. if (split) {
  38123. if (current !== '') array.push(current.trim());
  38124. current = '';
  38125. split = false;
  38126. } else {
  38127. current += letter;
  38128. }
  38129. }
  38130. if (last || current !== '') array.push(current.trim());
  38131. return array
  38132. },
  38133. space(string) {
  38134. let spaces = [' ', '\n', '\t'];
  38135. return list.split(string, spaces)
  38136. },
  38137. comma(string) {
  38138. return list.split(string, [','], true)
  38139. }
  38140. };
  38141. var list_1 = list;
  38142. list.default = list;
  38143. class Rule$1 extends container {
  38144. constructor(defaults) {
  38145. super(defaults);
  38146. this.type = 'rule';
  38147. if (!this.nodes) this.nodes = [];
  38148. }
  38149. get selectors() {
  38150. return list_1.comma(this.selector)
  38151. }
  38152. set selectors(values) {
  38153. let match = this.selector ? this.selector.match(/,\s*/) : null;
  38154. let sep = match ? match[0] : ',' + this.raw('between', 'beforeOpen');
  38155. this.selector = values.join(sep);
  38156. }
  38157. }
  38158. var rule = Rule$1;
  38159. Rule$1.default = Rule$1;
  38160. container.registerRule(Rule$1);
  38161. class Parser$1 {
  38162. constructor(input) {
  38163. this.input = input;
  38164. this.root = new root();
  38165. this.current = this.root;
  38166. this.spaces = '';
  38167. this.semicolon = false;
  38168. this.customProperty = false;
  38169. this.createTokenizer();
  38170. this.root.source = { input, start: { offset: 0, line: 1, column: 1 } };
  38171. }
  38172. createTokenizer() {
  38173. this.tokenizer = tokenize(this.input);
  38174. }
  38175. parse() {
  38176. let token;
  38177. while (!this.tokenizer.endOfFile()) {
  38178. token = this.tokenizer.nextToken();
  38179. switch (token[0]) {
  38180. case 'space':
  38181. this.spaces += token[1];
  38182. break
  38183. case ';':
  38184. this.freeSemicolon(token);
  38185. break
  38186. case '}':
  38187. this.end(token);
  38188. break
  38189. case 'comment':
  38190. this.comment(token);
  38191. break
  38192. case 'at-word':
  38193. this.atrule(token);
  38194. break
  38195. case '{':
  38196. this.emptyRule(token);
  38197. break
  38198. default:
  38199. this.other(token);
  38200. break
  38201. }
  38202. }
  38203. this.endFile();
  38204. }
  38205. comment(token) {
  38206. let node = new comment();
  38207. this.init(node, token[2]);
  38208. node.source.end = this.getPosition(token[3] || token[2]);
  38209. let text = token[1].slice(2, -2);
  38210. if (/^\s*$/.test(text)) {
  38211. node.text = '';
  38212. node.raws.left = text;
  38213. node.raws.right = '';
  38214. } else {
  38215. let match = text.match(/^(\s*)([^]*\S)(\s*)$/);
  38216. node.text = match[2];
  38217. node.raws.left = match[1];
  38218. node.raws.right = match[3];
  38219. }
  38220. }
  38221. emptyRule(token) {
  38222. let node = new rule();
  38223. this.init(node, token[2]);
  38224. node.selector = '';
  38225. node.raws.between = '';
  38226. this.current = node;
  38227. }
  38228. other(start) {
  38229. let end = false;
  38230. let type = null;
  38231. let colon = false;
  38232. let bracket = null;
  38233. let brackets = [];
  38234. let customProperty = start[1].startsWith('--');
  38235. let tokens = [];
  38236. let token = start;
  38237. while (token) {
  38238. type = token[0];
  38239. tokens.push(token);
  38240. if (type === '(' || type === '[') {
  38241. if (!bracket) bracket = token;
  38242. brackets.push(type === '(' ? ')' : ']');
  38243. } else if (customProperty && colon && type === '{') {
  38244. if (!bracket) bracket = token;
  38245. brackets.push('}');
  38246. } else if (brackets.length === 0) {
  38247. if (type === ';') {
  38248. if (colon) {
  38249. this.decl(tokens, customProperty);
  38250. return
  38251. } else {
  38252. break
  38253. }
  38254. } else if (type === '{') {
  38255. this.rule(tokens);
  38256. return
  38257. } else if (type === '}') {
  38258. this.tokenizer.back(tokens.pop());
  38259. end = true;
  38260. break
  38261. } else if (type === ':') {
  38262. colon = true;
  38263. }
  38264. } else if (type === brackets[brackets.length - 1]) {
  38265. brackets.pop();
  38266. if (brackets.length === 0) bracket = null;
  38267. }
  38268. token = this.tokenizer.nextToken();
  38269. }
  38270. if (this.tokenizer.endOfFile()) end = true;
  38271. if (brackets.length > 0) this.unclosedBracket(bracket);
  38272. if (end && colon) {
  38273. while (tokens.length) {
  38274. token = tokens[tokens.length - 1][0];
  38275. if (token !== 'space' && token !== 'comment') break
  38276. this.tokenizer.back(tokens.pop());
  38277. }
  38278. this.decl(tokens, customProperty);
  38279. } else {
  38280. this.unknownWord(tokens);
  38281. }
  38282. }
  38283. rule(tokens) {
  38284. tokens.pop();
  38285. let node = new rule();
  38286. this.init(node, tokens[0][2]);
  38287. node.raws.between = this.spacesAndCommentsFromEnd(tokens);
  38288. this.raw(node, 'selector', tokens);
  38289. this.current = node;
  38290. }
  38291. decl(tokens, customProperty) {
  38292. let node = new declaration();
  38293. this.init(node, tokens[0][2]);
  38294. let last = tokens[tokens.length - 1];
  38295. if (last[0] === ';') {
  38296. this.semicolon = true;
  38297. tokens.pop();
  38298. }
  38299. node.source.end = this.getPosition(last[3] || last[2]);
  38300. while (tokens[0][0] !== 'word') {
  38301. if (tokens.length === 1) this.unknownWord(tokens);
  38302. node.raws.before += tokens.shift()[1];
  38303. }
  38304. node.source.start = this.getPosition(tokens[0][2]);
  38305. node.prop = '';
  38306. while (tokens.length) {
  38307. let type = tokens[0][0];
  38308. if (type === ':' || type === 'space' || type === 'comment') {
  38309. break
  38310. }
  38311. node.prop += tokens.shift()[1];
  38312. }
  38313. node.raws.between = '';
  38314. let token;
  38315. while (tokens.length) {
  38316. token = tokens.shift();
  38317. if (token[0] === ':') {
  38318. node.raws.between += token[1];
  38319. break
  38320. } else {
  38321. if (token[0] === 'word' && /\w/.test(token[1])) {
  38322. this.unknownWord([token]);
  38323. }
  38324. node.raws.between += token[1];
  38325. }
  38326. }
  38327. if (node.prop[0] === '_' || node.prop[0] === '*') {
  38328. node.raws.before += node.prop[0];
  38329. node.prop = node.prop.slice(1);
  38330. }
  38331. let firstSpaces = this.spacesAndCommentsFromStart(tokens);
  38332. this.precheckMissedSemicolon(tokens);
  38333. for (let i = tokens.length - 1; i >= 0; i--) {
  38334. token = tokens[i];
  38335. if (token[1].toLowerCase() === '!important') {
  38336. node.important = true;
  38337. let string = this.stringFrom(tokens, i);
  38338. string = this.spacesFromEnd(tokens) + string;
  38339. if (string !== ' !important') node.raws.important = string;
  38340. break
  38341. } else if (token[1].toLowerCase() === 'important') {
  38342. let cache = tokens.slice(0);
  38343. let str = '';
  38344. for (let j = i; j > 0; j--) {
  38345. let type = cache[j][0];
  38346. if (str.trim().indexOf('!') === 0 && type !== 'space') {
  38347. break
  38348. }
  38349. str = cache.pop()[1] + str;
  38350. }
  38351. if (str.trim().indexOf('!') === 0) {
  38352. node.important = true;
  38353. node.raws.important = str;
  38354. tokens = cache;
  38355. }
  38356. }
  38357. if (token[0] !== 'space' && token[0] !== 'comment') {
  38358. break
  38359. }
  38360. }
  38361. let hasWord = tokens.some(i => i[0] !== 'space' && i[0] !== 'comment');
  38362. this.raw(node, 'value', tokens);
  38363. if (hasWord) {
  38364. node.raws.between += firstSpaces;
  38365. } else {
  38366. node.value = firstSpaces + node.value;
  38367. }
  38368. if (node.value.includes(':') && !customProperty) {
  38369. this.checkMissedSemicolon(tokens);
  38370. }
  38371. }
  38372. atrule(token) {
  38373. let node = new atRule();
  38374. node.name = token[1].slice(1);
  38375. if (node.name === '') {
  38376. this.unnamedAtrule(node, token);
  38377. }
  38378. this.init(node, token[2]);
  38379. let type;
  38380. let prev;
  38381. let shift;
  38382. let last = false;
  38383. let open = false;
  38384. let params = [];
  38385. let brackets = [];
  38386. while (!this.tokenizer.endOfFile()) {
  38387. token = this.tokenizer.nextToken();
  38388. type = token[0];
  38389. if (type === '(' || type === '[') {
  38390. brackets.push(type === '(' ? ')' : ']');
  38391. } else if (type === '{' && brackets.length > 0) {
  38392. brackets.push('}');
  38393. } else if (type === brackets[brackets.length - 1]) {
  38394. brackets.pop();
  38395. }
  38396. if (brackets.length === 0) {
  38397. if (type === ';') {
  38398. node.source.end = this.getPosition(token[2]);
  38399. this.semicolon = true;
  38400. break
  38401. } else if (type === '{') {
  38402. open = true;
  38403. break
  38404. } else if (type === '}') {
  38405. if (params.length > 0) {
  38406. shift = params.length - 1;
  38407. prev = params[shift];
  38408. while (prev && prev[0] === 'space') {
  38409. prev = params[--shift];
  38410. }
  38411. if (prev) {
  38412. node.source.end = this.getPosition(prev[3] || prev[2]);
  38413. }
  38414. }
  38415. this.end(token);
  38416. break
  38417. } else {
  38418. params.push(token);
  38419. }
  38420. } else {
  38421. params.push(token);
  38422. }
  38423. if (this.tokenizer.endOfFile()) {
  38424. last = true;
  38425. break
  38426. }
  38427. }
  38428. node.raws.between = this.spacesAndCommentsFromEnd(params);
  38429. if (params.length) {
  38430. node.raws.afterName = this.spacesAndCommentsFromStart(params);
  38431. this.raw(node, 'params', params);
  38432. if (last) {
  38433. token = params[params.length - 1];
  38434. node.source.end = this.getPosition(token[3] || token[2]);
  38435. this.spaces = node.raws.between;
  38436. node.raws.between = '';
  38437. }
  38438. } else {
  38439. node.raws.afterName = '';
  38440. node.params = '';
  38441. }
  38442. if (open) {
  38443. node.nodes = [];
  38444. this.current = node;
  38445. }
  38446. }
  38447. end(token) {
  38448. if (this.current.nodes && this.current.nodes.length) {
  38449. this.current.raws.semicolon = this.semicolon;
  38450. }
  38451. this.semicolon = false;
  38452. this.current.raws.after = (this.current.raws.after || '') + this.spaces;
  38453. this.spaces = '';
  38454. if (this.current.parent) {
  38455. this.current.source.end = this.getPosition(token[2]);
  38456. this.current = this.current.parent;
  38457. } else {
  38458. this.unexpectedClose(token);
  38459. }
  38460. }
  38461. endFile() {
  38462. if (this.current.parent) this.unclosedBlock();
  38463. if (this.current.nodes && this.current.nodes.length) {
  38464. this.current.raws.semicolon = this.semicolon;
  38465. }
  38466. this.current.raws.after = (this.current.raws.after || '') + this.spaces;
  38467. }
  38468. freeSemicolon(token) {
  38469. this.spaces += token[1];
  38470. if (this.current.nodes) {
  38471. let prev = this.current.nodes[this.current.nodes.length - 1];
  38472. if (prev && prev.type === 'rule' && !prev.raws.ownSemicolon) {
  38473. prev.raws.ownSemicolon = this.spaces;
  38474. this.spaces = '';
  38475. }
  38476. }
  38477. }
  38478. // Helpers
  38479. getPosition(offset) {
  38480. let pos = this.input.fromOffset(offset);
  38481. return {
  38482. offset,
  38483. line: pos.line,
  38484. column: pos.col
  38485. }
  38486. }
  38487. init(node, offset) {
  38488. this.current.push(node);
  38489. node.source = {
  38490. start: this.getPosition(offset),
  38491. input: this.input
  38492. };
  38493. node.raws.before = this.spaces;
  38494. this.spaces = '';
  38495. if (node.type !== 'comment') this.semicolon = false;
  38496. }
  38497. raw(node, prop, tokens) {
  38498. let token, type;
  38499. let length = tokens.length;
  38500. let value = '';
  38501. let clean = true;
  38502. let next, prev;
  38503. let pattern = /^([#.|])?(\w)+/i;
  38504. for (let i = 0; i < length; i += 1) {
  38505. token = tokens[i];
  38506. type = token[0];
  38507. if (type === 'comment' && node.type === 'rule') {
  38508. prev = tokens[i - 1];
  38509. next = tokens[i + 1];
  38510. if (
  38511. prev[0] !== 'space' &&
  38512. next[0] !== 'space' &&
  38513. pattern.test(prev[1]) &&
  38514. pattern.test(next[1])
  38515. ) {
  38516. value += token[1];
  38517. } else {
  38518. clean = false;
  38519. }
  38520. continue
  38521. }
  38522. if (type === 'comment' || (type === 'space' && i === length - 1)) {
  38523. clean = false;
  38524. } else {
  38525. value += token[1];
  38526. }
  38527. }
  38528. if (!clean) {
  38529. let raw = tokens.reduce((all, i) => all + i[1], '');
  38530. node.raws[prop] = { value, raw };
  38531. }
  38532. node[prop] = value;
  38533. }
  38534. spacesAndCommentsFromEnd(tokens) {
  38535. let lastTokenType;
  38536. let spaces = '';
  38537. while (tokens.length) {
  38538. lastTokenType = tokens[tokens.length - 1][0];
  38539. if (lastTokenType !== 'space' && lastTokenType !== 'comment') break
  38540. spaces = tokens.pop()[1] + spaces;
  38541. }
  38542. return spaces
  38543. }
  38544. spacesAndCommentsFromStart(tokens) {
  38545. let next;
  38546. let spaces = '';
  38547. while (tokens.length) {
  38548. next = tokens[0][0];
  38549. if (next !== 'space' && next !== 'comment') break
  38550. spaces += tokens.shift()[1];
  38551. }
  38552. return spaces
  38553. }
  38554. spacesFromEnd(tokens) {
  38555. let lastTokenType;
  38556. let spaces = '';
  38557. while (tokens.length) {
  38558. lastTokenType = tokens[tokens.length - 1][0];
  38559. if (lastTokenType !== 'space') break
  38560. spaces = tokens.pop()[1] + spaces;
  38561. }
  38562. return spaces
  38563. }
  38564. stringFrom(tokens, from) {
  38565. let result = '';
  38566. for (let i = from; i < tokens.length; i++) {
  38567. result += tokens[i][1];
  38568. }
  38569. tokens.splice(from, tokens.length - from);
  38570. return result
  38571. }
  38572. colon(tokens) {
  38573. let brackets = 0;
  38574. let token, type, prev;
  38575. for (let [i, element] of tokens.entries()) {
  38576. token = element;
  38577. type = token[0];
  38578. if (type === '(') {
  38579. brackets += 1;
  38580. }
  38581. if (type === ')') {
  38582. brackets -= 1;
  38583. }
  38584. if (brackets === 0 && type === ':') {
  38585. if (!prev) {
  38586. this.doubleColon(token);
  38587. } else if (prev[0] === 'word' && prev[1] === 'progid') {
  38588. continue
  38589. } else {
  38590. return i
  38591. }
  38592. }
  38593. prev = token;
  38594. }
  38595. return false
  38596. }
  38597. // Errors
  38598. unclosedBracket(bracket) {
  38599. throw this.input.error(
  38600. 'Unclosed bracket',
  38601. { offset: bracket[2] },
  38602. { offset: bracket[2] + 1 }
  38603. )
  38604. }
  38605. unknownWord(tokens) {
  38606. throw this.input.error(
  38607. 'Unknown word',
  38608. { offset: tokens[0][2] },
  38609. { offset: tokens[0][2] + tokens[0][1].length }
  38610. )
  38611. }
  38612. unexpectedClose(token) {
  38613. throw this.input.error(
  38614. 'Unexpected }',
  38615. { offset: token[2] },
  38616. { offset: token[2] + 1 }
  38617. )
  38618. }
  38619. unclosedBlock() {
  38620. let pos = this.current.source.start;
  38621. throw this.input.error('Unclosed block', pos.line, pos.column)
  38622. }
  38623. doubleColon(token) {
  38624. throw this.input.error(
  38625. 'Double colon',
  38626. { offset: token[2] },
  38627. { offset: token[2] + token[1].length }
  38628. )
  38629. }
  38630. unnamedAtrule(node, token) {
  38631. throw this.input.error(
  38632. 'At-rule without name',
  38633. { offset: token[2] },
  38634. { offset: token[2] + token[1].length }
  38635. )
  38636. }
  38637. precheckMissedSemicolon(/* tokens */) {
  38638. // Hook for Safe Parser
  38639. }
  38640. checkMissedSemicolon(tokens) {
  38641. let colon = this.colon(tokens);
  38642. if (colon === false) return
  38643. let founded = 0;
  38644. let token;
  38645. for (let j = colon - 1; j >= 0; j--) {
  38646. token = tokens[j];
  38647. if (token[0] !== 'space') {
  38648. founded += 1;
  38649. if (founded === 2) break
  38650. }
  38651. }
  38652. // If the token is a word, e.g. `!important`, `red` or any other valid property's value.
  38653. // Then we need to return the colon after that word token. [3] is the "end" colon of that word.
  38654. // And because we need it after that one we do +1 to get the next one.
  38655. throw this.input.error(
  38656. 'Missed semicolon',
  38657. token[0] === 'word' ? token[3] + 1 : token[2]
  38658. )
  38659. }
  38660. }
  38661. var parser = Parser$1;
  38662. function parse$6(css, opts) {
  38663. let input$1 = new input(css, opts);
  38664. let parser$1 = new parser(input$1);
  38665. try {
  38666. parser$1.parse();
  38667. } catch (e) {
  38668. {
  38669. if (e.name === 'CssSyntaxError' && opts && opts.from) {
  38670. if (/\.scss$/i.test(opts.from)) {
  38671. e.message +=
  38672. '\nYou tried to parse SCSS with ' +
  38673. 'the standard CSS parser; ' +
  38674. 'try again with the postcss-scss parser';
  38675. } else if (/\.sass/i.test(opts.from)) {
  38676. e.message +=
  38677. '\nYou tried to parse Sass with ' +
  38678. 'the standard CSS parser; ' +
  38679. 'try again with the postcss-sass parser';
  38680. } else if (/\.less$/i.test(opts.from)) {
  38681. e.message +=
  38682. '\nYou tried to parse Less with ' +
  38683. 'the standard CSS parser; ' +
  38684. 'try again with the postcss-less parser';
  38685. }
  38686. }
  38687. }
  38688. throw e
  38689. }
  38690. return parser$1.root
  38691. }
  38692. var parse_1$1 = parse$6;
  38693. parse$6.default = parse$6;
  38694. container.registerParse(parse$6);
  38695. let { isClean: isClean$3, my: my$3 } = symbols;
  38696. const TYPE_TO_CLASS_NAME = {
  38697. document: 'Document',
  38698. root: 'Root',
  38699. atrule: 'AtRule',
  38700. rule: 'Rule',
  38701. decl: 'Declaration',
  38702. comment: 'Comment'
  38703. };
  38704. const PLUGIN_PROPS = {
  38705. postcssPlugin: true,
  38706. prepare: true,
  38707. Once: true,
  38708. Document: true,
  38709. Root: true,
  38710. Declaration: true,
  38711. Rule: true,
  38712. AtRule: true,
  38713. Comment: true,
  38714. DeclarationExit: true,
  38715. RuleExit: true,
  38716. AtRuleExit: true,
  38717. CommentExit: true,
  38718. RootExit: true,
  38719. DocumentExit: true,
  38720. OnceExit: true
  38721. };
  38722. const NOT_VISITORS = {
  38723. postcssPlugin: true,
  38724. prepare: true,
  38725. Once: true
  38726. };
  38727. const CHILDREN = 0;
  38728. function isPromise(obj) {
  38729. return typeof obj === 'object' && typeof obj.then === 'function'
  38730. }
  38731. function getEvents(node) {
  38732. let key = false;
  38733. let type = TYPE_TO_CLASS_NAME[node.type];
  38734. if (node.type === 'decl') {
  38735. key = node.prop.toLowerCase();
  38736. } else if (node.type === 'atrule') {
  38737. key = node.name.toLowerCase();
  38738. }
  38739. if (key && node.append) {
  38740. return [
  38741. type,
  38742. type + '-' + key,
  38743. CHILDREN,
  38744. type + 'Exit',
  38745. type + 'Exit-' + key
  38746. ]
  38747. } else if (key) {
  38748. return [type, type + '-' + key, type + 'Exit', type + 'Exit-' + key]
  38749. } else if (node.append) {
  38750. return [type, CHILDREN, type + 'Exit']
  38751. } else {
  38752. return [type, type + 'Exit']
  38753. }
  38754. }
  38755. function toStack(node) {
  38756. let events;
  38757. if (node.type === 'document') {
  38758. events = ['Document', CHILDREN, 'DocumentExit'];
  38759. } else if (node.type === 'root') {
  38760. events = ['Root', CHILDREN, 'RootExit'];
  38761. } else {
  38762. events = getEvents(node);
  38763. }
  38764. return {
  38765. node,
  38766. events,
  38767. eventIndex: 0,
  38768. visitors: [],
  38769. visitorIndex: 0,
  38770. iterator: 0
  38771. }
  38772. }
  38773. function cleanMarks(node) {
  38774. node[isClean$3] = false;
  38775. if (node.nodes) node.nodes.forEach(i => cleanMarks(i));
  38776. return node
  38777. }
  38778. let postcss = {};
  38779. class LazyResult$2 {
  38780. constructor(processor, css, opts) {
  38781. this.stringified = false;
  38782. this.processed = false;
  38783. let root;
  38784. if (
  38785. typeof css === 'object' &&
  38786. css !== null &&
  38787. (css.type === 'root' || css.type === 'document')
  38788. ) {
  38789. root = cleanMarks(css);
  38790. } else if (css instanceof LazyResult$2 || css instanceof result) {
  38791. root = cleanMarks(css.root);
  38792. if (css.map) {
  38793. if (typeof opts.map === 'undefined') opts.map = {};
  38794. if (!opts.map.inline) opts.map.inline = false;
  38795. opts.map.prev = css.map;
  38796. }
  38797. } else {
  38798. let parser = parse_1$1;
  38799. if (opts.syntax) parser = opts.syntax.parse;
  38800. if (opts.parser) parser = opts.parser;
  38801. if (parser.parse) parser = parser.parse;
  38802. try {
  38803. root = parser(css, opts);
  38804. } catch (error) {
  38805. this.processed = true;
  38806. this.error = error;
  38807. }
  38808. if (root && !root[my$3]) {
  38809. /* c8 ignore next 2 */
  38810. container.rebuild(root);
  38811. }
  38812. }
  38813. this.result = new result(processor, root, opts);
  38814. this.helpers = { ...postcss, result: this.result, postcss };
  38815. this.plugins = this.processor.plugins.map(plugin => {
  38816. if (typeof plugin === 'object' && plugin.prepare) {
  38817. return { ...plugin, ...plugin.prepare(this.result) }
  38818. } else {
  38819. return plugin
  38820. }
  38821. });
  38822. }
  38823. get [Symbol.toStringTag]() {
  38824. return 'LazyResult'
  38825. }
  38826. get processor() {
  38827. return this.result.processor
  38828. }
  38829. get opts() {
  38830. return this.result.opts
  38831. }
  38832. get css() {
  38833. return this.stringify().css
  38834. }
  38835. get content() {
  38836. return this.stringify().content
  38837. }
  38838. get map() {
  38839. return this.stringify().map
  38840. }
  38841. get root() {
  38842. return this.sync().root
  38843. }
  38844. get messages() {
  38845. return this.sync().messages
  38846. }
  38847. warnings() {
  38848. return this.sync().warnings()
  38849. }
  38850. toString() {
  38851. return this.css
  38852. }
  38853. then(onFulfilled, onRejected) {
  38854. {
  38855. if (!('from' in this.opts)) {
  38856. warnOnce$2(
  38857. 'Without `from` option PostCSS could generate wrong source map ' +
  38858. 'and will not find Browserslist config. Set it to CSS file path ' +
  38859. 'or to `undefined` to prevent this warning.'
  38860. );
  38861. }
  38862. }
  38863. return this.async().then(onFulfilled, onRejected)
  38864. }
  38865. catch(onRejected) {
  38866. return this.async().catch(onRejected)
  38867. }
  38868. finally(onFinally) {
  38869. return this.async().then(onFinally, onFinally)
  38870. }
  38871. async() {
  38872. if (this.error) return Promise.reject(this.error)
  38873. if (this.processed) return Promise.resolve(this.result)
  38874. if (!this.processing) {
  38875. this.processing = this.runAsync();
  38876. }
  38877. return this.processing
  38878. }
  38879. sync() {
  38880. if (this.error) throw this.error
  38881. if (this.processed) return this.result
  38882. this.processed = true;
  38883. if (this.processing) {
  38884. throw this.getAsyncError()
  38885. }
  38886. for (let plugin of this.plugins) {
  38887. let promise = this.runOnRoot(plugin);
  38888. if (isPromise(promise)) {
  38889. throw this.getAsyncError()
  38890. }
  38891. }
  38892. this.prepareVisitors();
  38893. if (this.hasListener) {
  38894. let root = this.result.root;
  38895. while (!root[isClean$3]) {
  38896. root[isClean$3] = true;
  38897. this.walkSync(root);
  38898. }
  38899. if (this.listeners.OnceExit) {
  38900. if (root.type === 'document') {
  38901. for (let subRoot of root.nodes) {
  38902. this.visitSync(this.listeners.OnceExit, subRoot);
  38903. }
  38904. } else {
  38905. this.visitSync(this.listeners.OnceExit, root);
  38906. }
  38907. }
  38908. }
  38909. return this.result
  38910. }
  38911. stringify() {
  38912. if (this.error) throw this.error
  38913. if (this.stringified) return this.result
  38914. this.stringified = true;
  38915. this.sync();
  38916. let opts = this.result.opts;
  38917. let str = stringify_1;
  38918. if (opts.syntax) str = opts.syntax.stringify;
  38919. if (opts.stringifier) str = opts.stringifier;
  38920. if (str.stringify) str = str.stringify;
  38921. let map = new mapGenerator(str, this.result.root, this.result.opts);
  38922. let data = map.generate();
  38923. this.result.css = data[0];
  38924. this.result.map = data[1];
  38925. return this.result
  38926. }
  38927. walkSync(node) {
  38928. node[isClean$3] = true;
  38929. let events = getEvents(node);
  38930. for (let event of events) {
  38931. if (event === CHILDREN) {
  38932. if (node.nodes) {
  38933. node.each(child => {
  38934. if (!child[isClean$3]) this.walkSync(child);
  38935. });
  38936. }
  38937. } else {
  38938. let visitors = this.listeners[event];
  38939. if (visitors) {
  38940. if (this.visitSync(visitors, node.toProxy())) return
  38941. }
  38942. }
  38943. }
  38944. }
  38945. visitSync(visitors, node) {
  38946. for (let [plugin, visitor] of visitors) {
  38947. this.result.lastPlugin = plugin;
  38948. let promise;
  38949. try {
  38950. promise = visitor(node, this.helpers);
  38951. } catch (e) {
  38952. throw this.handleError(e, node.proxyOf)
  38953. }
  38954. if (node.type !== 'root' && node.type !== 'document' && !node.parent) {
  38955. return true
  38956. }
  38957. if (isPromise(promise)) {
  38958. throw this.getAsyncError()
  38959. }
  38960. }
  38961. }
  38962. runOnRoot(plugin) {
  38963. this.result.lastPlugin = plugin;
  38964. try {
  38965. if (typeof plugin === 'object' && plugin.Once) {
  38966. if (this.result.root.type === 'document') {
  38967. let roots = this.result.root.nodes.map(root =>
  38968. plugin.Once(root, this.helpers)
  38969. );
  38970. if (isPromise(roots[0])) {
  38971. return Promise.all(roots)
  38972. }
  38973. return roots
  38974. }
  38975. return plugin.Once(this.result.root, this.helpers)
  38976. } else if (typeof plugin === 'function') {
  38977. return plugin(this.result.root, this.result)
  38978. }
  38979. } catch (error) {
  38980. throw this.handleError(error)
  38981. }
  38982. }
  38983. getAsyncError() {
  38984. throw new Error('Use process(css).then(cb) to work with async plugins')
  38985. }
  38986. handleError(error, node) {
  38987. let plugin = this.result.lastPlugin;
  38988. try {
  38989. if (node) node.addToError(error);
  38990. this.error = error;
  38991. if (error.name === 'CssSyntaxError' && !error.plugin) {
  38992. error.plugin = plugin.postcssPlugin;
  38993. error.setMessage();
  38994. } else if (plugin.postcssVersion) {
  38995. if (({}).NODE_ENV !== 'production') {
  38996. let pluginName = plugin.postcssPlugin;
  38997. let pluginVer = plugin.postcssVersion;
  38998. let runtimeVer = this.result.processor.version;
  38999. let a = pluginVer.split('.');
  39000. let b = runtimeVer.split('.');
  39001. if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) {
  39002. // eslint-disable-next-line no-console
  39003. console.error(
  39004. 'Unknown error from PostCSS plugin. Your current PostCSS ' +
  39005. 'version is ' +
  39006. runtimeVer +
  39007. ', but ' +
  39008. pluginName +
  39009. ' uses ' +
  39010. pluginVer +
  39011. '. Perhaps this is the source of the error below.'
  39012. );
  39013. }
  39014. }
  39015. }
  39016. } catch (err) {
  39017. /* c8 ignore next 3 */
  39018. // eslint-disable-next-line no-console
  39019. if (console && console.error) console.error(err);
  39020. }
  39021. return error
  39022. }
  39023. async runAsync() {
  39024. this.plugin = 0;
  39025. for (let i = 0; i < this.plugins.length; i++) {
  39026. let plugin = this.plugins[i];
  39027. let promise = this.runOnRoot(plugin);
  39028. if (isPromise(promise)) {
  39029. try {
  39030. await promise;
  39031. } catch (error) {
  39032. throw this.handleError(error)
  39033. }
  39034. }
  39035. }
  39036. this.prepareVisitors();
  39037. if (this.hasListener) {
  39038. let root = this.result.root;
  39039. while (!root[isClean$3]) {
  39040. root[isClean$3] = true;
  39041. let stack = [toStack(root)];
  39042. while (stack.length > 0) {
  39043. let promise = this.visitTick(stack);
  39044. if (isPromise(promise)) {
  39045. try {
  39046. await promise;
  39047. } catch (e) {
  39048. let node = stack[stack.length - 1].node;
  39049. throw this.handleError(e, node)
  39050. }
  39051. }
  39052. }
  39053. }
  39054. if (this.listeners.OnceExit) {
  39055. for (let [plugin, visitor] of this.listeners.OnceExit) {
  39056. this.result.lastPlugin = plugin;
  39057. try {
  39058. if (root.type === 'document') {
  39059. let roots = root.nodes.map(subRoot =>
  39060. visitor(subRoot, this.helpers)
  39061. );
  39062. await Promise.all(roots);
  39063. } else {
  39064. await visitor(root, this.helpers);
  39065. }
  39066. } catch (e) {
  39067. throw this.handleError(e)
  39068. }
  39069. }
  39070. }
  39071. }
  39072. this.processed = true;
  39073. return this.stringify()
  39074. }
  39075. prepareVisitors() {
  39076. this.listeners = {};
  39077. let add = (plugin, type, cb) => {
  39078. if (!this.listeners[type]) this.listeners[type] = [];
  39079. this.listeners[type].push([plugin, cb]);
  39080. };
  39081. for (let plugin of this.plugins) {
  39082. if (typeof plugin === 'object') {
  39083. for (let event in plugin) {
  39084. if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) {
  39085. throw new Error(
  39086. `Unknown event ${event} in ${plugin.postcssPlugin}. ` +
  39087. `Try to update PostCSS (${this.processor.version} now).`
  39088. )
  39089. }
  39090. if (!NOT_VISITORS[event]) {
  39091. if (typeof plugin[event] === 'object') {
  39092. for (let filter in plugin[event]) {
  39093. if (filter === '*') {
  39094. add(plugin, event, plugin[event][filter]);
  39095. } else {
  39096. add(
  39097. plugin,
  39098. event + '-' + filter.toLowerCase(),
  39099. plugin[event][filter]
  39100. );
  39101. }
  39102. }
  39103. } else if (typeof plugin[event] === 'function') {
  39104. add(plugin, event, plugin[event]);
  39105. }
  39106. }
  39107. }
  39108. }
  39109. }
  39110. this.hasListener = Object.keys(this.listeners).length > 0;
  39111. }
  39112. visitTick(stack) {
  39113. let visit = stack[stack.length - 1];
  39114. let { node, visitors } = visit;
  39115. if (node.type !== 'root' && node.type !== 'document' && !node.parent) {
  39116. stack.pop();
  39117. return
  39118. }
  39119. if (visitors.length > 0 && visit.visitorIndex < visitors.length) {
  39120. let [plugin, visitor] = visitors[visit.visitorIndex];
  39121. visit.visitorIndex += 1;
  39122. if (visit.visitorIndex === visitors.length) {
  39123. visit.visitors = [];
  39124. visit.visitorIndex = 0;
  39125. }
  39126. this.result.lastPlugin = plugin;
  39127. try {
  39128. return visitor(node.toProxy(), this.helpers)
  39129. } catch (e) {
  39130. throw this.handleError(e, node)
  39131. }
  39132. }
  39133. if (visit.iterator !== 0) {
  39134. let iterator = visit.iterator;
  39135. let child;
  39136. while ((child = node.nodes[node.indexes[iterator]])) {
  39137. node.indexes[iterator] += 1;
  39138. if (!child[isClean$3]) {
  39139. child[isClean$3] = true;
  39140. stack.push(toStack(child));
  39141. return
  39142. }
  39143. }
  39144. visit.iterator = 0;
  39145. delete node.indexes[iterator];
  39146. }
  39147. let events = visit.events;
  39148. while (visit.eventIndex < events.length) {
  39149. let event = events[visit.eventIndex];
  39150. visit.eventIndex += 1;
  39151. if (event === CHILDREN) {
  39152. if (node.nodes && node.nodes.length) {
  39153. node[isClean$3] = true;
  39154. visit.iterator = node.getIterator();
  39155. }
  39156. return
  39157. } else if (this.listeners[event]) {
  39158. visit.visitors = this.listeners[event];
  39159. return
  39160. }
  39161. }
  39162. stack.pop();
  39163. }
  39164. }
  39165. LazyResult$2.registerPostcss = dependant => {
  39166. postcss = dependant;
  39167. };
  39168. var lazyResult = LazyResult$2;
  39169. LazyResult$2.default = LazyResult$2;
  39170. root.registerLazyResult(LazyResult$2);
  39171. document.registerLazyResult(LazyResult$2);
  39172. class NoWorkResult {
  39173. constructor(processor, css, opts) {
  39174. css = css.toString();
  39175. this.stringified = false;
  39176. this._processor = processor;
  39177. this._css = css;
  39178. this._opts = opts;
  39179. this._map = undefined;
  39180. let root;
  39181. let str = stringify_1;
  39182. this.result = new result(this._processor, root, this._opts);
  39183. this.result.css = css;
  39184. let self = this;
  39185. Object.defineProperty(this.result, 'root', {
  39186. get() {
  39187. return self.root
  39188. }
  39189. });
  39190. let map = new mapGenerator(str, root, this._opts, css);
  39191. if (map.isMap()) {
  39192. let [generatedCSS, generatedMap] = map.generate();
  39193. if (generatedCSS) {
  39194. this.result.css = generatedCSS;
  39195. }
  39196. if (generatedMap) {
  39197. this.result.map = generatedMap;
  39198. }
  39199. }
  39200. }
  39201. get [Symbol.toStringTag]() {
  39202. return 'NoWorkResult'
  39203. }
  39204. get processor() {
  39205. return this.result.processor
  39206. }
  39207. get opts() {
  39208. return this.result.opts
  39209. }
  39210. get css() {
  39211. return this.result.css
  39212. }
  39213. get content() {
  39214. return this.result.css
  39215. }
  39216. get map() {
  39217. return this.result.map
  39218. }
  39219. get root() {
  39220. if (this._root) {
  39221. return this._root
  39222. }
  39223. let root;
  39224. let parser = parse_1$1;
  39225. try {
  39226. root = parser(this._css, this._opts);
  39227. } catch (error) {
  39228. this.error = error;
  39229. }
  39230. this._root = root;
  39231. return root
  39232. }
  39233. get messages() {
  39234. return []
  39235. }
  39236. warnings() {
  39237. return []
  39238. }
  39239. toString() {
  39240. return this._css
  39241. }
  39242. then(onFulfilled, onRejected) {
  39243. {
  39244. if (!('from' in this._opts)) {
  39245. warnOnce$2(
  39246. 'Without `from` option PostCSS could generate wrong source map ' +
  39247. 'and will not find Browserslist config. Set it to CSS file path ' +
  39248. 'or to `undefined` to prevent this warning.'
  39249. );
  39250. }
  39251. }
  39252. return this.async().then(onFulfilled, onRejected)
  39253. }
  39254. catch(onRejected) {
  39255. return this.async().catch(onRejected)
  39256. }
  39257. finally(onFinally) {
  39258. return this.async().then(onFinally, onFinally)
  39259. }
  39260. async() {
  39261. if (this.error) return Promise.reject(this.error)
  39262. return Promise.resolve(this.result)
  39263. }
  39264. sync() {
  39265. if (this.error) throw this.error
  39266. return this.result
  39267. }
  39268. }
  39269. var noWorkResult = NoWorkResult;
  39270. NoWorkResult.default = NoWorkResult;
  39271. class Processor$2 {
  39272. constructor(plugins = []) {
  39273. this.version = '8.4.4';
  39274. this.plugins = this.normalize(plugins);
  39275. }
  39276. use(plugin) {
  39277. this.plugins = this.plugins.concat(this.normalize([plugin]));
  39278. return this
  39279. }
  39280. process(css, opts = {}) {
  39281. if (
  39282. this.plugins.length === 0 &&
  39283. typeof opts.parser === 'undefined' &&
  39284. typeof opts.stringifier === 'undefined' &&
  39285. typeof opts.syntax === 'undefined'
  39286. ) {
  39287. return new noWorkResult(this, css, opts)
  39288. } else {
  39289. return new lazyResult(this, css, opts)
  39290. }
  39291. }
  39292. normalize(plugins) {
  39293. let normalized = [];
  39294. for (let i of plugins) {
  39295. if (i.postcss === true) {
  39296. i = i();
  39297. } else if (i.postcss) {
  39298. i = i.postcss;
  39299. }
  39300. if (typeof i === 'object' && Array.isArray(i.plugins)) {
  39301. normalized = normalized.concat(i.plugins);
  39302. } else if (typeof i === 'object' && i.postcssPlugin) {
  39303. normalized.push(i);
  39304. } else if (typeof i === 'function') {
  39305. normalized.push(i);
  39306. } else if (typeof i === 'object' && (i.parse || i.stringify)) {
  39307. {
  39308. throw new Error(
  39309. 'PostCSS syntaxes cannot be used as plugins. Instead, please use ' +
  39310. 'one of the syntax/parser/stringifier options as outlined ' +
  39311. 'in your PostCSS runner documentation.'
  39312. )
  39313. }
  39314. } else {
  39315. throw new Error(i + ' is not a PostCSS plugin')
  39316. }
  39317. }
  39318. return normalized
  39319. }
  39320. }
  39321. var processor = Processor$2;
  39322. Processor$2.default = Processor$2;
  39323. root.registerProcessor(Processor$2);
  39324. document.registerProcessor(Processor$2);
  39325. function fromJSON(json, inputs) {
  39326. if (Array.isArray(json)) return json.map(n => fromJSON(n))
  39327. let { inputs: ownInputs, ...defaults } = json;
  39328. if (ownInputs) {
  39329. inputs = [];
  39330. for (let input$1 of ownInputs) {
  39331. let inputHydrated = { ...input$1, __proto__: input.prototype };
  39332. if (inputHydrated.map) {
  39333. inputHydrated.map = {
  39334. ...inputHydrated.map,
  39335. __proto__: previousMap.prototype
  39336. };
  39337. }
  39338. inputs.push(inputHydrated);
  39339. }
  39340. }
  39341. if (defaults.nodes) {
  39342. defaults.nodes = json.nodes.map(n => fromJSON(n, inputs));
  39343. }
  39344. if (defaults.source) {
  39345. let { inputId, ...source } = defaults.source;
  39346. defaults.source = source;
  39347. if (inputId != null) {
  39348. defaults.source.input = inputs[inputId];
  39349. }
  39350. }
  39351. if (defaults.type === 'root') {
  39352. return new root(defaults)
  39353. } else if (defaults.type === 'decl') {
  39354. return new declaration(defaults)
  39355. } else if (defaults.type === 'rule') {
  39356. return new rule(defaults)
  39357. } else if (defaults.type === 'comment') {
  39358. return new comment(defaults)
  39359. } else if (defaults.type === 'atrule') {
  39360. return new atRule(defaults)
  39361. } else {
  39362. throw new Error('Unknown node type: ' + json.type)
  39363. }
  39364. }
  39365. var fromJSON_1 = fromJSON;
  39366. fromJSON.default = fromJSON;
  39367. function postcss$1(...plugins) {
  39368. if (plugins.length === 1 && Array.isArray(plugins[0])) {
  39369. plugins = plugins[0];
  39370. }
  39371. return new processor(plugins)
  39372. }
  39373. postcss$1.plugin = function plugin(name, initializer) {
  39374. // eslint-disable-next-line no-console
  39375. if (console && console.warn) {
  39376. // eslint-disable-next-line no-console
  39377. console.warn(
  39378. name +
  39379. ': postcss.plugin was deprecated. Migration guide:\n' +
  39380. 'https://evilmartians.com/chronicles/postcss-8-plugin-migration'
  39381. );
  39382. }
  39383. function creator(...args) {
  39384. let transformer = initializer(...args);
  39385. transformer.postcssPlugin = name;
  39386. transformer.postcssVersion = new processor().version;
  39387. return transformer
  39388. }
  39389. let cache;
  39390. Object.defineProperty(creator, 'postcss', {
  39391. get() {
  39392. if (!cache) cache = creator();
  39393. return cache
  39394. }
  39395. });
  39396. creator.process = function (css, processOpts, pluginOpts) {
  39397. return postcss$1([creator(pluginOpts)]).process(css, processOpts)
  39398. };
  39399. return creator
  39400. };
  39401. postcss$1.stringify = stringify_1;
  39402. postcss$1.parse = parse_1$1;
  39403. postcss$1.fromJSON = fromJSON_1;
  39404. postcss$1.list = list_1;
  39405. postcss$1.comment = defaults => new comment(defaults);
  39406. postcss$1.atRule = defaults => new atRule(defaults);
  39407. postcss$1.decl = defaults => new declaration(defaults);
  39408. postcss$1.rule = defaults => new rule(defaults);
  39409. postcss$1.root = defaults => new root(defaults);
  39410. postcss$1.document = defaults => new document(defaults);
  39411. postcss$1.CssSyntaxError = cssSyntaxError;
  39412. postcss$1.Declaration = declaration;
  39413. postcss$1.Container = container;
  39414. postcss$1.Processor = processor;
  39415. postcss$1.Document = document;
  39416. postcss$1.Comment = comment;
  39417. postcss$1.Warning = warning;
  39418. postcss$1.AtRule = atRule;
  39419. postcss$1.Result = result;
  39420. postcss$1.Input = input;
  39421. postcss$1.Rule = rule;
  39422. postcss$1.Root = root;
  39423. postcss$1.Node = node_1;
  39424. lazyResult.registerPostcss(postcss$1);
  39425. var postcss_1 = postcss$1;
  39426. postcss$1.default = postcss$1;
  39427. const trimPlugin = () => {
  39428. return {
  39429. postcssPlugin: 'vue-sfc-trim',
  39430. Once(root) {
  39431. root.walk(({ type, raws }) => {
  39432. if (type === 'rule' || type === 'atrule') {
  39433. if (raws.before)
  39434. raws.before = '\n';
  39435. if ('after' in raws && raws.after)
  39436. raws.after = '\n';
  39437. }
  39438. });
  39439. }
  39440. };
  39441. };
  39442. trimPlugin.postcss = true;
  39443. var unesc_1 = createCommonjsModule(function (module, exports) {
  39444. exports.__esModule = true;
  39445. exports["default"] = unesc;
  39446. // Many thanks for this post which made this migration much easier.
  39447. // https://mathiasbynens.be/notes/css-escapes
  39448. /**
  39449. *
  39450. * @param {string} str
  39451. * @returns {[string, number]|undefined}
  39452. */
  39453. function gobbleHex(str) {
  39454. var lower = str.toLowerCase();
  39455. var hex = '';
  39456. var spaceTerminated = false;
  39457. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  39458. var code = lower.charCodeAt(i); // check to see if we are dealing with a valid hex char [a-f|0-9]
  39459. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57; // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  39460. spaceTerminated = code === 32;
  39461. if (!valid) {
  39462. break;
  39463. }
  39464. hex += lower[i];
  39465. }
  39466. if (hex.length === 0) {
  39467. return undefined;
  39468. }
  39469. var codePoint = parseInt(hex, 16);
  39470. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF; // Add special case for
  39471. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  39472. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  39473. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  39474. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  39475. }
  39476. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  39477. }
  39478. var CONTAINS_ESCAPE = /\\/;
  39479. function unesc(str) {
  39480. var needToProcess = CONTAINS_ESCAPE.test(str);
  39481. if (!needToProcess) {
  39482. return str;
  39483. }
  39484. var ret = "";
  39485. for (var i = 0; i < str.length; i++) {
  39486. if (str[i] === "\\") {
  39487. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  39488. if (gobbled !== undefined) {
  39489. ret += gobbled[0];
  39490. i += gobbled[1];
  39491. continue;
  39492. } // Retain a pair of \\ if double escaped `\\\\`
  39493. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  39494. if (str[i + 1] === "\\") {
  39495. ret += "\\";
  39496. i++;
  39497. continue;
  39498. } // if \\ is at the end of the string retain it
  39499. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  39500. if (str.length === i + 1) {
  39501. ret += str[i];
  39502. }
  39503. continue;
  39504. }
  39505. ret += str[i];
  39506. }
  39507. return ret;
  39508. }
  39509. module.exports = exports.default;
  39510. });
  39511. var getProp_1 = createCommonjsModule(function (module, exports) {
  39512. exports.__esModule = true;
  39513. exports["default"] = getProp;
  39514. function getProp(obj) {
  39515. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  39516. props[_key - 1] = arguments[_key];
  39517. }
  39518. while (props.length > 0) {
  39519. var prop = props.shift();
  39520. if (!obj[prop]) {
  39521. return undefined;
  39522. }
  39523. obj = obj[prop];
  39524. }
  39525. return obj;
  39526. }
  39527. module.exports = exports.default;
  39528. });
  39529. var ensureObject_1 = createCommonjsModule(function (module, exports) {
  39530. exports.__esModule = true;
  39531. exports["default"] = ensureObject;
  39532. function ensureObject(obj) {
  39533. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  39534. props[_key - 1] = arguments[_key];
  39535. }
  39536. while (props.length > 0) {
  39537. var prop = props.shift();
  39538. if (!obj[prop]) {
  39539. obj[prop] = {};
  39540. }
  39541. obj = obj[prop];
  39542. }
  39543. }
  39544. module.exports = exports.default;
  39545. });
  39546. var stripComments_1 = createCommonjsModule(function (module, exports) {
  39547. exports.__esModule = true;
  39548. exports["default"] = stripComments;
  39549. function stripComments(str) {
  39550. var s = "";
  39551. var commentStart = str.indexOf("/*");
  39552. var lastEnd = 0;
  39553. while (commentStart >= 0) {
  39554. s = s + str.slice(lastEnd, commentStart);
  39555. var commentEnd = str.indexOf("*/", commentStart + 2);
  39556. if (commentEnd < 0) {
  39557. return s;
  39558. }
  39559. lastEnd = commentEnd + 2;
  39560. commentStart = str.indexOf("/*", lastEnd);
  39561. }
  39562. s = s + str.slice(lastEnd);
  39563. return s;
  39564. }
  39565. module.exports = exports.default;
  39566. });
  39567. var util$2 = createCommonjsModule(function (module, exports) {
  39568. exports.__esModule = true;
  39569. exports.stripComments = exports.ensureObject = exports.getProp = exports.unesc = void 0;
  39570. var _unesc = _interopRequireDefault(unesc_1);
  39571. exports.unesc = _unesc["default"];
  39572. var _getProp = _interopRequireDefault(getProp_1);
  39573. exports.getProp = _getProp["default"];
  39574. var _ensureObject = _interopRequireDefault(ensureObject_1);
  39575. exports.ensureObject = _ensureObject["default"];
  39576. var _stripComments = _interopRequireDefault(stripComments_1);
  39577. exports.stripComments = _stripComments["default"];
  39578. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  39579. });
  39580. var node = createCommonjsModule(function (module, exports) {
  39581. exports.__esModule = true;
  39582. exports["default"] = void 0;
  39583. 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); } }
  39584. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  39585. var cloneNode = function cloneNode(obj, parent) {
  39586. if (typeof obj !== 'object' || obj === null) {
  39587. return obj;
  39588. }
  39589. var cloned = new obj.constructor();
  39590. for (var i in obj) {
  39591. if (!obj.hasOwnProperty(i)) {
  39592. continue;
  39593. }
  39594. var value = obj[i];
  39595. var type = typeof value;
  39596. if (i === 'parent' && type === 'object') {
  39597. if (parent) {
  39598. cloned[i] = parent;
  39599. }
  39600. } else if (value instanceof Array) {
  39601. cloned[i] = value.map(function (j) {
  39602. return cloneNode(j, cloned);
  39603. });
  39604. } else {
  39605. cloned[i] = cloneNode(value, cloned);
  39606. }
  39607. }
  39608. return cloned;
  39609. };
  39610. var Node = /*#__PURE__*/function () {
  39611. function Node(opts) {
  39612. if (opts === void 0) {
  39613. opts = {};
  39614. }
  39615. Object.assign(this, opts);
  39616. this.spaces = this.spaces || {};
  39617. this.spaces.before = this.spaces.before || '';
  39618. this.spaces.after = this.spaces.after || '';
  39619. }
  39620. var _proto = Node.prototype;
  39621. _proto.remove = function remove() {
  39622. if (this.parent) {
  39623. this.parent.removeChild(this);
  39624. }
  39625. this.parent = undefined;
  39626. return this;
  39627. };
  39628. _proto.replaceWith = function replaceWith() {
  39629. if (this.parent) {
  39630. for (var index in arguments) {
  39631. this.parent.insertBefore(this, arguments[index]);
  39632. }
  39633. this.remove();
  39634. }
  39635. return this;
  39636. };
  39637. _proto.next = function next() {
  39638. return this.parent.at(this.parent.index(this) + 1);
  39639. };
  39640. _proto.prev = function prev() {
  39641. return this.parent.at(this.parent.index(this) - 1);
  39642. };
  39643. _proto.clone = function clone(overrides) {
  39644. if (overrides === void 0) {
  39645. overrides = {};
  39646. }
  39647. var cloned = cloneNode(this);
  39648. for (var name in overrides) {
  39649. cloned[name] = overrides[name];
  39650. }
  39651. return cloned;
  39652. }
  39653. /**
  39654. * Some non-standard syntax doesn't follow normal escaping rules for css.
  39655. * This allows non standard syntax to be appended to an existing property
  39656. * by specifying the escaped value. By specifying the escaped value,
  39657. * illegal characters are allowed to be directly inserted into css output.
  39658. * @param {string} name the property to set
  39659. * @param {any} value the unescaped value of the property
  39660. * @param {string} valueEscaped optional. the escaped value of the property.
  39661. */
  39662. ;
  39663. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  39664. if (!this.raws) {
  39665. this.raws = {};
  39666. }
  39667. var originalValue = this[name];
  39668. var originalEscaped = this.raws[name];
  39669. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  39670. if (originalEscaped || valueEscaped !== value) {
  39671. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  39672. } else {
  39673. delete this.raws[name]; // delete any escaped value that was created by the setter.
  39674. }
  39675. }
  39676. /**
  39677. * Some non-standard syntax doesn't follow normal escaping rules for css.
  39678. * This allows the escaped value to be specified directly, allowing illegal
  39679. * characters to be directly inserted into css output.
  39680. * @param {string} name the property to set
  39681. * @param {any} value the unescaped value of the property
  39682. * @param {string} valueEscaped the escaped value of the property.
  39683. */
  39684. ;
  39685. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  39686. if (!this.raws) {
  39687. this.raws = {};
  39688. }
  39689. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  39690. this.raws[name] = valueEscaped;
  39691. }
  39692. /**
  39693. * When you want a value to passed through to CSS directly. This method
  39694. * deletes the corresponding raw value causing the stringifier to fallback
  39695. * to the unescaped value.
  39696. * @param {string} name the property to set.
  39697. * @param {any} value The value that is both escaped and unescaped.
  39698. */
  39699. ;
  39700. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  39701. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  39702. if (this.raws) {
  39703. delete this.raws[name];
  39704. }
  39705. }
  39706. /**
  39707. *
  39708. * @param {number} line The number (starting with 1)
  39709. * @param {number} column The column number (starting with 1)
  39710. */
  39711. ;
  39712. _proto.isAtPosition = function isAtPosition(line, column) {
  39713. if (this.source && this.source.start && this.source.end) {
  39714. if (this.source.start.line > line) {
  39715. return false;
  39716. }
  39717. if (this.source.end.line < line) {
  39718. return false;
  39719. }
  39720. if (this.source.start.line === line && this.source.start.column > column) {
  39721. return false;
  39722. }
  39723. if (this.source.end.line === line && this.source.end.column < column) {
  39724. return false;
  39725. }
  39726. return true;
  39727. }
  39728. return undefined;
  39729. };
  39730. _proto.stringifyProperty = function stringifyProperty(name) {
  39731. return this.raws && this.raws[name] || this[name];
  39732. };
  39733. _proto.valueToString = function valueToString() {
  39734. return String(this.stringifyProperty("value"));
  39735. };
  39736. _proto.toString = function toString() {
  39737. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  39738. };
  39739. _createClass(Node, [{
  39740. key: "rawSpaceBefore",
  39741. get: function get() {
  39742. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  39743. if (rawSpace === undefined) {
  39744. rawSpace = this.spaces && this.spaces.before;
  39745. }
  39746. return rawSpace || "";
  39747. },
  39748. set: function set(raw) {
  39749. (0, util$2.ensureObject)(this, "raws", "spaces");
  39750. this.raws.spaces.before = raw;
  39751. }
  39752. }, {
  39753. key: "rawSpaceAfter",
  39754. get: function get() {
  39755. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  39756. if (rawSpace === undefined) {
  39757. rawSpace = this.spaces.after;
  39758. }
  39759. return rawSpace || "";
  39760. },
  39761. set: function set(raw) {
  39762. (0, util$2.ensureObject)(this, "raws", "spaces");
  39763. this.raws.spaces.after = raw;
  39764. }
  39765. }]);
  39766. return Node;
  39767. }();
  39768. exports["default"] = Node;
  39769. module.exports = exports.default;
  39770. });
  39771. var types$1 = createCommonjsModule(function (module, exports) {
  39772. exports.__esModule = true;
  39773. 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;
  39774. var TAG = 'tag';
  39775. exports.TAG = TAG;
  39776. var STRING = 'string';
  39777. exports.STRING = STRING;
  39778. var SELECTOR = 'selector';
  39779. exports.SELECTOR = SELECTOR;
  39780. var ROOT = 'root';
  39781. exports.ROOT = ROOT;
  39782. var PSEUDO = 'pseudo';
  39783. exports.PSEUDO = PSEUDO;
  39784. var NESTING = 'nesting';
  39785. exports.NESTING = NESTING;
  39786. var ID = 'id';
  39787. exports.ID = ID;
  39788. var COMMENT = 'comment';
  39789. exports.COMMENT = COMMENT;
  39790. var COMBINATOR = 'combinator';
  39791. exports.COMBINATOR = COMBINATOR;
  39792. var CLASS = 'class';
  39793. exports.CLASS = CLASS;
  39794. var ATTRIBUTE = 'attribute';
  39795. exports.ATTRIBUTE = ATTRIBUTE;
  39796. var UNIVERSAL = 'universal';
  39797. exports.UNIVERSAL = UNIVERSAL;
  39798. });
  39799. var container$1 = createCommonjsModule(function (module, exports) {
  39800. exports.__esModule = true;
  39801. exports["default"] = void 0;
  39802. var _node = _interopRequireDefault(node);
  39803. var types = _interopRequireWildcard(types$1);
  39804. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  39805. 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; }
  39806. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  39807. 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); }
  39808. 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); }
  39809. 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; }
  39810. 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); } }
  39811. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  39812. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  39813. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  39814. var Container = /*#__PURE__*/function (_Node) {
  39815. _inheritsLoose(Container, _Node);
  39816. function Container(opts) {
  39817. var _this;
  39818. _this = _Node.call(this, opts) || this;
  39819. if (!_this.nodes) {
  39820. _this.nodes = [];
  39821. }
  39822. return _this;
  39823. }
  39824. var _proto = Container.prototype;
  39825. _proto.append = function append(selector) {
  39826. selector.parent = this;
  39827. this.nodes.push(selector);
  39828. return this;
  39829. };
  39830. _proto.prepend = function prepend(selector) {
  39831. selector.parent = this;
  39832. this.nodes.unshift(selector);
  39833. return this;
  39834. };
  39835. _proto.at = function at(index) {
  39836. return this.nodes[index];
  39837. };
  39838. _proto.index = function index(child) {
  39839. if (typeof child === 'number') {
  39840. return child;
  39841. }
  39842. return this.nodes.indexOf(child);
  39843. };
  39844. _proto.removeChild = function removeChild(child) {
  39845. child = this.index(child);
  39846. this.at(child).parent = undefined;
  39847. this.nodes.splice(child, 1);
  39848. var index;
  39849. for (var id in this.indexes) {
  39850. index = this.indexes[id];
  39851. if (index >= child) {
  39852. this.indexes[id] = index - 1;
  39853. }
  39854. }
  39855. return this;
  39856. };
  39857. _proto.removeAll = function removeAll() {
  39858. for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
  39859. var node = _step.value;
  39860. node.parent = undefined;
  39861. }
  39862. this.nodes = [];
  39863. return this;
  39864. };
  39865. _proto.empty = function empty() {
  39866. return this.removeAll();
  39867. };
  39868. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  39869. newNode.parent = this;
  39870. var oldIndex = this.index(oldNode);
  39871. this.nodes.splice(oldIndex + 1, 0, newNode);
  39872. newNode.parent = this;
  39873. var index;
  39874. for (var id in this.indexes) {
  39875. index = this.indexes[id];
  39876. if (oldIndex <= index) {
  39877. this.indexes[id] = index + 1;
  39878. }
  39879. }
  39880. return this;
  39881. };
  39882. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  39883. newNode.parent = this;
  39884. var oldIndex = this.index(oldNode);
  39885. this.nodes.splice(oldIndex, 0, newNode);
  39886. newNode.parent = this;
  39887. var index;
  39888. for (var id in this.indexes) {
  39889. index = this.indexes[id];
  39890. if (index <= oldIndex) {
  39891. this.indexes[id] = index + 1;
  39892. }
  39893. }
  39894. return this;
  39895. };
  39896. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  39897. var found = undefined;
  39898. this.each(function (node) {
  39899. if (node.atPosition) {
  39900. var foundChild = node.atPosition(line, col);
  39901. if (foundChild) {
  39902. found = foundChild;
  39903. return false;
  39904. }
  39905. } else if (node.isAtPosition(line, col)) {
  39906. found = node;
  39907. return false;
  39908. }
  39909. });
  39910. return found;
  39911. }
  39912. /**
  39913. * Return the most specific node at the line and column number given.
  39914. * The source location is based on the original parsed location, locations aren't
  39915. * updated as selector nodes are mutated.
  39916. *
  39917. * Note that this location is relative to the location of the first character
  39918. * of the selector, and not the location of the selector in the overall document
  39919. * when used in conjunction with postcss.
  39920. *
  39921. * If not found, returns undefined.
  39922. * @param {number} line The line number of the node to find. (1-based index)
  39923. * @param {number} col The column number of the node to find. (1-based index)
  39924. */
  39925. ;
  39926. _proto.atPosition = function atPosition(line, col) {
  39927. if (this.isAtPosition(line, col)) {
  39928. return this._findChildAtPosition(line, col) || this;
  39929. } else {
  39930. return undefined;
  39931. }
  39932. };
  39933. _proto._inferEndPosition = function _inferEndPosition() {
  39934. if (this.last && this.last.source && this.last.source.end) {
  39935. this.source = this.source || {};
  39936. this.source.end = this.source.end || {};
  39937. Object.assign(this.source.end, this.last.source.end);
  39938. }
  39939. };
  39940. _proto.each = function each(callback) {
  39941. if (!this.lastEach) {
  39942. this.lastEach = 0;
  39943. }
  39944. if (!this.indexes) {
  39945. this.indexes = {};
  39946. }
  39947. this.lastEach++;
  39948. var id = this.lastEach;
  39949. this.indexes[id] = 0;
  39950. if (!this.length) {
  39951. return undefined;
  39952. }
  39953. var index, result;
  39954. while (this.indexes[id] < this.length) {
  39955. index = this.indexes[id];
  39956. result = callback(this.at(index), index);
  39957. if (result === false) {
  39958. break;
  39959. }
  39960. this.indexes[id] += 1;
  39961. }
  39962. delete this.indexes[id];
  39963. if (result === false) {
  39964. return false;
  39965. }
  39966. };
  39967. _proto.walk = function walk(callback) {
  39968. return this.each(function (node, i) {
  39969. var result = callback(node, i);
  39970. if (result !== false && node.length) {
  39971. result = node.walk(callback);
  39972. }
  39973. if (result === false) {
  39974. return false;
  39975. }
  39976. });
  39977. };
  39978. _proto.walkAttributes = function walkAttributes(callback) {
  39979. var _this2 = this;
  39980. return this.walk(function (selector) {
  39981. if (selector.type === types.ATTRIBUTE) {
  39982. return callback.call(_this2, selector);
  39983. }
  39984. });
  39985. };
  39986. _proto.walkClasses = function walkClasses(callback) {
  39987. var _this3 = this;
  39988. return this.walk(function (selector) {
  39989. if (selector.type === types.CLASS) {
  39990. return callback.call(_this3, selector);
  39991. }
  39992. });
  39993. };
  39994. _proto.walkCombinators = function walkCombinators(callback) {
  39995. var _this4 = this;
  39996. return this.walk(function (selector) {
  39997. if (selector.type === types.COMBINATOR) {
  39998. return callback.call(_this4, selector);
  39999. }
  40000. });
  40001. };
  40002. _proto.walkComments = function walkComments(callback) {
  40003. var _this5 = this;
  40004. return this.walk(function (selector) {
  40005. if (selector.type === types.COMMENT) {
  40006. return callback.call(_this5, selector);
  40007. }
  40008. });
  40009. };
  40010. _proto.walkIds = function walkIds(callback) {
  40011. var _this6 = this;
  40012. return this.walk(function (selector) {
  40013. if (selector.type === types.ID) {
  40014. return callback.call(_this6, selector);
  40015. }
  40016. });
  40017. };
  40018. _proto.walkNesting = function walkNesting(callback) {
  40019. var _this7 = this;
  40020. return this.walk(function (selector) {
  40021. if (selector.type === types.NESTING) {
  40022. return callback.call(_this7, selector);
  40023. }
  40024. });
  40025. };
  40026. _proto.walkPseudos = function walkPseudos(callback) {
  40027. var _this8 = this;
  40028. return this.walk(function (selector) {
  40029. if (selector.type === types.PSEUDO) {
  40030. return callback.call(_this8, selector);
  40031. }
  40032. });
  40033. };
  40034. _proto.walkTags = function walkTags(callback) {
  40035. var _this9 = this;
  40036. return this.walk(function (selector) {
  40037. if (selector.type === types.TAG) {
  40038. return callback.call(_this9, selector);
  40039. }
  40040. });
  40041. };
  40042. _proto.walkUniversals = function walkUniversals(callback) {
  40043. var _this10 = this;
  40044. return this.walk(function (selector) {
  40045. if (selector.type === types.UNIVERSAL) {
  40046. return callback.call(_this10, selector);
  40047. }
  40048. });
  40049. };
  40050. _proto.split = function split(callback) {
  40051. var _this11 = this;
  40052. var current = [];
  40053. return this.reduce(function (memo, node, index) {
  40054. var split = callback.call(_this11, node);
  40055. current.push(node);
  40056. if (split) {
  40057. memo.push(current);
  40058. current = [];
  40059. } else if (index === _this11.length - 1) {
  40060. memo.push(current);
  40061. }
  40062. return memo;
  40063. }, []);
  40064. };
  40065. _proto.map = function map(callback) {
  40066. return this.nodes.map(callback);
  40067. };
  40068. _proto.reduce = function reduce(callback, memo) {
  40069. return this.nodes.reduce(callback, memo);
  40070. };
  40071. _proto.every = function every(callback) {
  40072. return this.nodes.every(callback);
  40073. };
  40074. _proto.some = function some(callback) {
  40075. return this.nodes.some(callback);
  40076. };
  40077. _proto.filter = function filter(callback) {
  40078. return this.nodes.filter(callback);
  40079. };
  40080. _proto.sort = function sort(callback) {
  40081. return this.nodes.sort(callback);
  40082. };
  40083. _proto.toString = function toString() {
  40084. return this.map(String).join('');
  40085. };
  40086. _createClass(Container, [{
  40087. key: "first",
  40088. get: function get() {
  40089. return this.at(0);
  40090. }
  40091. }, {
  40092. key: "last",
  40093. get: function get() {
  40094. return this.at(this.length - 1);
  40095. }
  40096. }, {
  40097. key: "length",
  40098. get: function get() {
  40099. return this.nodes.length;
  40100. }
  40101. }]);
  40102. return Container;
  40103. }(_node["default"]);
  40104. exports["default"] = Container;
  40105. module.exports = exports.default;
  40106. });
  40107. var root$1 = createCommonjsModule(function (module, exports) {
  40108. exports.__esModule = true;
  40109. exports["default"] = void 0;
  40110. var _container = _interopRequireDefault(container$1);
  40111. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40112. 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); } }
  40113. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  40114. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  40115. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  40116. var Root = /*#__PURE__*/function (_Container) {
  40117. _inheritsLoose(Root, _Container);
  40118. function Root(opts) {
  40119. var _this;
  40120. _this = _Container.call(this, opts) || this;
  40121. _this.type = types$1.ROOT;
  40122. return _this;
  40123. }
  40124. var _proto = Root.prototype;
  40125. _proto.toString = function toString() {
  40126. var str = this.reduce(function (memo, selector) {
  40127. memo.push(String(selector));
  40128. return memo;
  40129. }, []).join(',');
  40130. return this.trailingComma ? str + ',' : str;
  40131. };
  40132. _proto.error = function error(message, options) {
  40133. if (this._error) {
  40134. return this._error(message, options);
  40135. } else {
  40136. return new Error(message);
  40137. }
  40138. };
  40139. _createClass(Root, [{
  40140. key: "errorGenerator",
  40141. set: function set(handler) {
  40142. this._error = handler;
  40143. }
  40144. }]);
  40145. return Root;
  40146. }(_container["default"]);
  40147. exports["default"] = Root;
  40148. module.exports = exports.default;
  40149. });
  40150. var selector = createCommonjsModule(function (module, exports) {
  40151. exports.__esModule = true;
  40152. exports["default"] = void 0;
  40153. var _container = _interopRequireDefault(container$1);
  40154. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40155. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  40156. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  40157. var Selector = /*#__PURE__*/function (_Container) {
  40158. _inheritsLoose(Selector, _Container);
  40159. function Selector(opts) {
  40160. var _this;
  40161. _this = _Container.call(this, opts) || this;
  40162. _this.type = types$1.SELECTOR;
  40163. return _this;
  40164. }
  40165. return Selector;
  40166. }(_container["default"]);
  40167. exports["default"] = Selector;
  40168. module.exports = exports.default;
  40169. });
  40170. /*! https://mths.be/cssesc v3.0.0 by @mathias */
  40171. var object = {};
  40172. var hasOwnProperty$3 = object.hasOwnProperty;
  40173. var merge = function merge(options, defaults) {
  40174. if (!options) {
  40175. return defaults;
  40176. }
  40177. var result = {};
  40178. for (var key in defaults) {
  40179. // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
  40180. // only recognized option names are used.
  40181. result[key] = hasOwnProperty$3.call(options, key) ? options[key] : defaults[key];
  40182. }
  40183. return result;
  40184. };
  40185. var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
  40186. var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
  40187. var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
  40188. // https://mathiasbynens.be/notes/css-escapes#css
  40189. var cssesc = function cssesc(string, options) {
  40190. options = merge(options, cssesc.options);
  40191. if (options.quotes != 'single' && options.quotes != 'double') {
  40192. options.quotes = 'single';
  40193. }
  40194. var quote = options.quotes == 'double' ? '"' : '\'';
  40195. var isIdentifier = options.isIdentifier;
  40196. var firstChar = string.charAt(0);
  40197. var output = '';
  40198. var counter = 0;
  40199. var length = string.length;
  40200. while (counter < length) {
  40201. var character = string.charAt(counter++);
  40202. var codePoint = character.charCodeAt();
  40203. var value = void 0;
  40204. // If it’s not a printable ASCII character…
  40205. if (codePoint < 0x20 || codePoint > 0x7E) {
  40206. if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
  40207. // It’s a high surrogate, and there is a next character.
  40208. var extra = string.charCodeAt(counter++);
  40209. if ((extra & 0xFC00) == 0xDC00) {
  40210. // next character is low surrogate
  40211. codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
  40212. } else {
  40213. // It’s an unmatched surrogate; only append this code unit, in case
  40214. // the next code unit is the high surrogate of a surrogate pair.
  40215. counter--;
  40216. }
  40217. }
  40218. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  40219. } else {
  40220. if (options.escapeEverything) {
  40221. if (regexAnySingleEscape.test(character)) {
  40222. value = '\\' + character;
  40223. } else {
  40224. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  40225. }
  40226. } else if (/[\t\n\f\r\x0B]/.test(character)) {
  40227. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  40228. } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
  40229. value = '\\' + character;
  40230. } else {
  40231. value = character;
  40232. }
  40233. }
  40234. output += value;
  40235. }
  40236. if (isIdentifier) {
  40237. if (/^-[-\d]/.test(output)) {
  40238. output = '\\-' + output.slice(1);
  40239. } else if (/\d/.test(firstChar)) {
  40240. output = '\\3' + firstChar + ' ' + output.slice(1);
  40241. }
  40242. }
  40243. // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
  40244. // since they’re redundant. Note that this is only possible if the escape
  40245. // sequence isn’t preceded by an odd number of backslashes.
  40246. output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
  40247. if ($1 && $1.length % 2) {
  40248. // It’s not safe to remove the space, so don’t.
  40249. return $0;
  40250. }
  40251. // Strip the space.
  40252. return ($1 || '') + $2;
  40253. });
  40254. if (!isIdentifier && options.wrap) {
  40255. return quote + output + quote;
  40256. }
  40257. return output;
  40258. };
  40259. // Expose default options (so they can be overridden globally).
  40260. cssesc.options = {
  40261. 'escapeEverything': false,
  40262. 'isIdentifier': false,
  40263. 'quotes': 'single',
  40264. 'wrap': false
  40265. };
  40266. cssesc.version = '3.0.0';
  40267. var cssesc_1 = cssesc;
  40268. var className = createCommonjsModule(function (module, exports) {
  40269. exports.__esModule = true;
  40270. exports["default"] = void 0;
  40271. var _cssesc = _interopRequireDefault(cssesc_1);
  40272. var _node = _interopRequireDefault(node);
  40273. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40274. 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); } }
  40275. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  40276. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  40277. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  40278. var ClassName = /*#__PURE__*/function (_Node) {
  40279. _inheritsLoose(ClassName, _Node);
  40280. function ClassName(opts) {
  40281. var _this;
  40282. _this = _Node.call(this, opts) || this;
  40283. _this.type = types$1.CLASS;
  40284. _this._constructed = true;
  40285. return _this;
  40286. }
  40287. var _proto = ClassName.prototype;
  40288. _proto.valueToString = function valueToString() {
  40289. return '.' + _Node.prototype.valueToString.call(this);
  40290. };
  40291. _createClass(ClassName, [{
  40292. key: "value",
  40293. get: function get() {
  40294. return this._value;
  40295. },
  40296. set: function set(v) {
  40297. if (this._constructed) {
  40298. var escaped = (0, _cssesc["default"])(v, {
  40299. isIdentifier: true
  40300. });
  40301. if (escaped !== v) {
  40302. (0, util$2.ensureObject)(this, "raws");
  40303. this.raws.value = escaped;
  40304. } else if (this.raws) {
  40305. delete this.raws.value;
  40306. }
  40307. }
  40308. this._value = v;
  40309. }
  40310. }]);
  40311. return ClassName;
  40312. }(_node["default"]);
  40313. exports["default"] = ClassName;
  40314. module.exports = exports.default;
  40315. });
  40316. var comment$1 = createCommonjsModule(function (module, exports) {
  40317. exports.__esModule = true;
  40318. exports["default"] = void 0;
  40319. var _node = _interopRequireDefault(node);
  40320. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40321. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  40322. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  40323. var Comment = /*#__PURE__*/function (_Node) {
  40324. _inheritsLoose(Comment, _Node);
  40325. function Comment(opts) {
  40326. var _this;
  40327. _this = _Node.call(this, opts) || this;
  40328. _this.type = types$1.COMMENT;
  40329. return _this;
  40330. }
  40331. return Comment;
  40332. }(_node["default"]);
  40333. exports["default"] = Comment;
  40334. module.exports = exports.default;
  40335. });
  40336. var id = createCommonjsModule(function (module, exports) {
  40337. exports.__esModule = true;
  40338. exports["default"] = void 0;
  40339. var _node = _interopRequireDefault(node);
  40340. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40341. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  40342. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  40343. var ID = /*#__PURE__*/function (_Node) {
  40344. _inheritsLoose(ID, _Node);
  40345. function ID(opts) {
  40346. var _this;
  40347. _this = _Node.call(this, opts) || this;
  40348. _this.type = types$1.ID;
  40349. return _this;
  40350. }
  40351. var _proto = ID.prototype;
  40352. _proto.valueToString = function valueToString() {
  40353. return '#' + _Node.prototype.valueToString.call(this);
  40354. };
  40355. return ID;
  40356. }(_node["default"]);
  40357. exports["default"] = ID;
  40358. module.exports = exports.default;
  40359. });
  40360. var namespace = createCommonjsModule(function (module, exports) {
  40361. exports.__esModule = true;
  40362. exports["default"] = void 0;
  40363. var _cssesc = _interopRequireDefault(cssesc_1);
  40364. var _node = _interopRequireDefault(node);
  40365. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40366. 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); } }
  40367. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  40368. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  40369. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  40370. var Namespace = /*#__PURE__*/function (_Node) {
  40371. _inheritsLoose(Namespace, _Node);
  40372. function Namespace() {
  40373. return _Node.apply(this, arguments) || this;
  40374. }
  40375. var _proto = Namespace.prototype;
  40376. _proto.qualifiedName = function qualifiedName(value) {
  40377. if (this.namespace) {
  40378. return this.namespaceString + "|" + value;
  40379. } else {
  40380. return value;
  40381. }
  40382. };
  40383. _proto.valueToString = function valueToString() {
  40384. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  40385. };
  40386. _createClass(Namespace, [{
  40387. key: "namespace",
  40388. get: function get() {
  40389. return this._namespace;
  40390. },
  40391. set: function set(namespace) {
  40392. if (namespace === true || namespace === "*" || namespace === "&") {
  40393. this._namespace = namespace;
  40394. if (this.raws) {
  40395. delete this.raws.namespace;
  40396. }
  40397. return;
  40398. }
  40399. var escaped = (0, _cssesc["default"])(namespace, {
  40400. isIdentifier: true
  40401. });
  40402. this._namespace = namespace;
  40403. if (escaped !== namespace) {
  40404. (0, util$2.ensureObject)(this, "raws");
  40405. this.raws.namespace = escaped;
  40406. } else if (this.raws) {
  40407. delete this.raws.namespace;
  40408. }
  40409. }
  40410. }, {
  40411. key: "ns",
  40412. get: function get() {
  40413. return this._namespace;
  40414. },
  40415. set: function set(namespace) {
  40416. this.namespace = namespace;
  40417. }
  40418. }, {
  40419. key: "namespaceString",
  40420. get: function get() {
  40421. if (this.namespace) {
  40422. var ns = this.stringifyProperty("namespace");
  40423. if (ns === true) {
  40424. return '';
  40425. } else {
  40426. return ns;
  40427. }
  40428. } else {
  40429. return '';
  40430. }
  40431. }
  40432. }]);
  40433. return Namespace;
  40434. }(_node["default"]);
  40435. exports["default"] = Namespace;
  40436. module.exports = exports.default;
  40437. });
  40438. var tag = createCommonjsModule(function (module, exports) {
  40439. exports.__esModule = true;
  40440. exports["default"] = void 0;
  40441. var _namespace = _interopRequireDefault(namespace);
  40442. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40443. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  40444. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  40445. var Tag = /*#__PURE__*/function (_Namespace) {
  40446. _inheritsLoose(Tag, _Namespace);
  40447. function Tag(opts) {
  40448. var _this;
  40449. _this = _Namespace.call(this, opts) || this;
  40450. _this.type = types$1.TAG;
  40451. return _this;
  40452. }
  40453. return Tag;
  40454. }(_namespace["default"]);
  40455. exports["default"] = Tag;
  40456. module.exports = exports.default;
  40457. });
  40458. var string = createCommonjsModule(function (module, exports) {
  40459. exports.__esModule = true;
  40460. exports["default"] = void 0;
  40461. var _node = _interopRequireDefault(node);
  40462. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40463. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  40464. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  40465. var String = /*#__PURE__*/function (_Node) {
  40466. _inheritsLoose(String, _Node);
  40467. function String(opts) {
  40468. var _this;
  40469. _this = _Node.call(this, opts) || this;
  40470. _this.type = types$1.STRING;
  40471. return _this;
  40472. }
  40473. return String;
  40474. }(_node["default"]);
  40475. exports["default"] = String;
  40476. module.exports = exports.default;
  40477. });
  40478. var pseudo = createCommonjsModule(function (module, exports) {
  40479. exports.__esModule = true;
  40480. exports["default"] = void 0;
  40481. var _container = _interopRequireDefault(container$1);
  40482. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40483. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  40484. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  40485. var Pseudo = /*#__PURE__*/function (_Container) {
  40486. _inheritsLoose(Pseudo, _Container);
  40487. function Pseudo(opts) {
  40488. var _this;
  40489. _this = _Container.call(this, opts) || this;
  40490. _this.type = types$1.PSEUDO;
  40491. return _this;
  40492. }
  40493. var _proto = Pseudo.prototype;
  40494. _proto.toString = function toString() {
  40495. var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
  40496. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  40497. };
  40498. return Pseudo;
  40499. }(_container["default"]);
  40500. exports["default"] = Pseudo;
  40501. module.exports = exports.default;
  40502. });
  40503. /**
  40504. * For Node.js, simply re-export the core `util.deprecate` function.
  40505. */
  40506. var node$1 = require$$0.deprecate;
  40507. var attribute = createCommonjsModule(function (module, exports) {
  40508. exports.__esModule = true;
  40509. exports.unescapeValue = unescapeValue;
  40510. exports["default"] = void 0;
  40511. var _cssesc = _interopRequireDefault(cssesc_1);
  40512. var _unesc = _interopRequireDefault(unesc_1);
  40513. var _namespace = _interopRequireDefault(namespace);
  40514. var _CSSESC_QUOTE_OPTIONS;
  40515. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40516. 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); } }
  40517. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  40518. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  40519. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  40520. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  40521. var warnOfDeprecatedValueAssignment = node$1(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  40522. var warnOfDeprecatedQuotedAssignment = node$1(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  40523. var warnOfDeprecatedConstructor = node$1(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  40524. function unescapeValue(value) {
  40525. var deprecatedUsage = false;
  40526. var quoteMark = null;
  40527. var unescaped = value;
  40528. var m = unescaped.match(WRAPPED_IN_QUOTES);
  40529. if (m) {
  40530. quoteMark = m[1];
  40531. unescaped = m[2];
  40532. }
  40533. unescaped = (0, _unesc["default"])(unescaped);
  40534. if (unescaped !== value) {
  40535. deprecatedUsage = true;
  40536. }
  40537. return {
  40538. deprecatedUsage: deprecatedUsage,
  40539. unescaped: unescaped,
  40540. quoteMark: quoteMark
  40541. };
  40542. }
  40543. function handleDeprecatedContructorOpts(opts) {
  40544. if (opts.quoteMark !== undefined) {
  40545. return opts;
  40546. }
  40547. if (opts.value === undefined) {
  40548. return opts;
  40549. }
  40550. warnOfDeprecatedConstructor();
  40551. var _unescapeValue = unescapeValue(opts.value),
  40552. quoteMark = _unescapeValue.quoteMark,
  40553. unescaped = _unescapeValue.unescaped;
  40554. if (!opts.raws) {
  40555. opts.raws = {};
  40556. }
  40557. if (opts.raws.value === undefined) {
  40558. opts.raws.value = opts.value;
  40559. }
  40560. opts.value = unescaped;
  40561. opts.quoteMark = quoteMark;
  40562. return opts;
  40563. }
  40564. var Attribute = /*#__PURE__*/function (_Namespace) {
  40565. _inheritsLoose(Attribute, _Namespace);
  40566. function Attribute(opts) {
  40567. var _this;
  40568. if (opts === void 0) {
  40569. opts = {};
  40570. }
  40571. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  40572. _this.type = types$1.ATTRIBUTE;
  40573. _this.raws = _this.raws || {};
  40574. Object.defineProperty(_this.raws, 'unquoted', {
  40575. get: node$1(function () {
  40576. return _this.value;
  40577. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  40578. set: node$1(function () {
  40579. return _this.value;
  40580. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  40581. });
  40582. _this._constructed = true;
  40583. return _this;
  40584. }
  40585. /**
  40586. * Returns the Attribute's value quoted such that it would be legal to use
  40587. * in the value of a css file. The original value's quotation setting
  40588. * used for stringification is left unchanged. See `setValue(value, options)`
  40589. * if you want to control the quote settings of a new value for the attribute.
  40590. *
  40591. * You can also change the quotation used for the current value by setting quoteMark.
  40592. *
  40593. * Options:
  40594. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  40595. * option is not set, the original value for quoteMark will be used. If
  40596. * indeterminate, a double quote is used. The legal values are:
  40597. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  40598. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  40599. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  40600. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  40601. * over the quoteMark option value.
  40602. * * smart {boolean} - if true, will select a quote mark based on the value
  40603. * and the other options specified here. See the `smartQuoteMark()`
  40604. * method.
  40605. **/
  40606. var _proto = Attribute.prototype;
  40607. _proto.getQuotedValue = function getQuotedValue(options) {
  40608. if (options === void 0) {
  40609. options = {};
  40610. }
  40611. var quoteMark = this._determineQuoteMark(options);
  40612. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  40613. var escaped = (0, _cssesc["default"])(this._value, cssescopts);
  40614. return escaped;
  40615. };
  40616. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  40617. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  40618. }
  40619. /**
  40620. * Set the unescaped value with the specified quotation options. The value
  40621. * provided must not include any wrapping quote marks -- those quotes will
  40622. * be interpreted as part of the value and escaped accordingly.
  40623. */
  40624. ;
  40625. _proto.setValue = function setValue(value, options) {
  40626. if (options === void 0) {
  40627. options = {};
  40628. }
  40629. this._value = value;
  40630. this._quoteMark = this._determineQuoteMark(options);
  40631. this._syncRawValue();
  40632. }
  40633. /**
  40634. * Intelligently select a quoteMark value based on the value's contents. If
  40635. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  40636. * mark will be picked that minimizes the number of escapes.
  40637. *
  40638. * If there's no clear winner, the quote mark from these options is used,
  40639. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  40640. * true). If the quoteMark is unspecified, a double quote is used.
  40641. *
  40642. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  40643. * from the quoteValue method.
  40644. */
  40645. ;
  40646. _proto.smartQuoteMark = function smartQuoteMark(options) {
  40647. var v = this.value;
  40648. var numSingleQuotes = v.replace(/[^']/g, '').length;
  40649. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  40650. if (numSingleQuotes + numDoubleQuotes === 0) {
  40651. var escaped = (0, _cssesc["default"])(v, {
  40652. isIdentifier: true
  40653. });
  40654. if (escaped === v) {
  40655. return Attribute.NO_QUOTE;
  40656. } else {
  40657. var pref = this.preferredQuoteMark(options);
  40658. if (pref === Attribute.NO_QUOTE) {
  40659. // pick a quote mark that isn't none and see if it's smaller
  40660. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  40661. var opts = CSSESC_QUOTE_OPTIONS[quote];
  40662. var quoteValue = (0, _cssesc["default"])(v, opts);
  40663. if (quoteValue.length < escaped.length) {
  40664. return quote;
  40665. }
  40666. }
  40667. return pref;
  40668. }
  40669. } else if (numDoubleQuotes === numSingleQuotes) {
  40670. return this.preferredQuoteMark(options);
  40671. } else if (numDoubleQuotes < numSingleQuotes) {
  40672. return Attribute.DOUBLE_QUOTE;
  40673. } else {
  40674. return Attribute.SINGLE_QUOTE;
  40675. }
  40676. }
  40677. /**
  40678. * Selects the preferred quote mark based on the options and the current quote mark value.
  40679. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  40680. * instead.
  40681. */
  40682. ;
  40683. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  40684. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  40685. if (quoteMark === undefined) {
  40686. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  40687. }
  40688. if (quoteMark === undefined) {
  40689. quoteMark = Attribute.DOUBLE_QUOTE;
  40690. }
  40691. return quoteMark;
  40692. };
  40693. _proto._syncRawValue = function _syncRawValue() {
  40694. var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  40695. if (rawValue === this._value) {
  40696. if (this.raws) {
  40697. delete this.raws.value;
  40698. }
  40699. } else {
  40700. this.raws.value = rawValue;
  40701. }
  40702. };
  40703. _proto._handleEscapes = function _handleEscapes(prop, value) {
  40704. if (this._constructed) {
  40705. var escaped = (0, _cssesc["default"])(value, {
  40706. isIdentifier: true
  40707. });
  40708. if (escaped !== value) {
  40709. this.raws[prop] = escaped;
  40710. } else {
  40711. delete this.raws[prop];
  40712. }
  40713. }
  40714. };
  40715. _proto._spacesFor = function _spacesFor(name) {
  40716. var attrSpaces = {
  40717. before: '',
  40718. after: ''
  40719. };
  40720. var spaces = this.spaces[name] || {};
  40721. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  40722. return Object.assign(attrSpaces, spaces, rawSpaces);
  40723. };
  40724. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  40725. if (spaceName === void 0) {
  40726. spaceName = name;
  40727. }
  40728. if (concat === void 0) {
  40729. concat = defaultAttrConcat;
  40730. }
  40731. var attrSpaces = this._spacesFor(spaceName);
  40732. return concat(this.stringifyProperty(name), attrSpaces);
  40733. }
  40734. /**
  40735. * returns the offset of the attribute part specified relative to the
  40736. * start of the node of the output string.
  40737. *
  40738. * * "ns" - alias for "namespace"
  40739. * * "namespace" - the namespace if it exists.
  40740. * * "attribute" - the attribute name
  40741. * * "attributeNS" - the start of the attribute or its namespace
  40742. * * "operator" - the match operator of the attribute
  40743. * * "value" - The value (string or identifier)
  40744. * * "insensitive" - the case insensitivity flag;
  40745. * @param part One of the possible values inside an attribute.
  40746. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  40747. */
  40748. ;
  40749. _proto.offsetOf = function offsetOf(name) {
  40750. var count = 1;
  40751. var attributeSpaces = this._spacesFor("attribute");
  40752. count += attributeSpaces.before.length;
  40753. if (name === "namespace" || name === "ns") {
  40754. return this.namespace ? count : -1;
  40755. }
  40756. if (name === "attributeNS") {
  40757. return count;
  40758. }
  40759. count += this.namespaceString.length;
  40760. if (this.namespace) {
  40761. count += 1;
  40762. }
  40763. if (name === "attribute") {
  40764. return count;
  40765. }
  40766. count += this.stringifyProperty("attribute").length;
  40767. count += attributeSpaces.after.length;
  40768. var operatorSpaces = this._spacesFor("operator");
  40769. count += operatorSpaces.before.length;
  40770. var operator = this.stringifyProperty("operator");
  40771. if (name === "operator") {
  40772. return operator ? count : -1;
  40773. }
  40774. count += operator.length;
  40775. count += operatorSpaces.after.length;
  40776. var valueSpaces = this._spacesFor("value");
  40777. count += valueSpaces.before.length;
  40778. var value = this.stringifyProperty("value");
  40779. if (name === "value") {
  40780. return value ? count : -1;
  40781. }
  40782. count += value.length;
  40783. count += valueSpaces.after.length;
  40784. var insensitiveSpaces = this._spacesFor("insensitive");
  40785. count += insensitiveSpaces.before.length;
  40786. if (name === "insensitive") {
  40787. return this.insensitive ? count : -1;
  40788. }
  40789. return -1;
  40790. };
  40791. _proto.toString = function toString() {
  40792. var _this2 = this;
  40793. var selector = [this.rawSpaceBefore, '['];
  40794. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  40795. if (this.operator && (this.value || this.value === '')) {
  40796. selector.push(this._stringFor('operator'));
  40797. selector.push(this._stringFor('value'));
  40798. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  40799. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  40800. attrSpaces.before = " ";
  40801. }
  40802. return defaultAttrConcat(attrValue, attrSpaces);
  40803. }));
  40804. }
  40805. selector.push(']');
  40806. selector.push(this.rawSpaceAfter);
  40807. return selector.join('');
  40808. };
  40809. _createClass(Attribute, [{
  40810. key: "quoted",
  40811. get: function get() {
  40812. var qm = this.quoteMark;
  40813. return qm === "'" || qm === '"';
  40814. },
  40815. set: function set(value) {
  40816. warnOfDeprecatedQuotedAssignment();
  40817. }
  40818. /**
  40819. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  40820. * returns `null` if the value is not quoted.
  40821. * returns `undefined` if the quotation state is unknown (this can happen when
  40822. * the attribute is constructed without specifying a quote mark.)
  40823. */
  40824. }, {
  40825. key: "quoteMark",
  40826. get: function get() {
  40827. return this._quoteMark;
  40828. }
  40829. /**
  40830. * Set the quote mark to be used by this attribute's value.
  40831. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  40832. * value is updated accordingly.
  40833. *
  40834. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  40835. */
  40836. ,
  40837. set: function set(quoteMark) {
  40838. if (!this._constructed) {
  40839. this._quoteMark = quoteMark;
  40840. return;
  40841. }
  40842. if (this._quoteMark !== quoteMark) {
  40843. this._quoteMark = quoteMark;
  40844. this._syncRawValue();
  40845. }
  40846. }
  40847. }, {
  40848. key: "qualifiedAttribute",
  40849. get: function get() {
  40850. return this.qualifiedName(this.raws.attribute || this.attribute);
  40851. }
  40852. }, {
  40853. key: "insensitiveFlag",
  40854. get: function get() {
  40855. return this.insensitive ? 'i' : '';
  40856. }
  40857. }, {
  40858. key: "value",
  40859. get: function get() {
  40860. return this._value;
  40861. }
  40862. /**
  40863. * Before 3.0, the value had to be set to an escaped value including any wrapped
  40864. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  40865. * is unescaped during parsing and any quote marks are removed.
  40866. *
  40867. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  40868. * a deprecation warning is raised when the new value contains any characters that would
  40869. * require escaping (including if it contains wrapped quotes).
  40870. *
  40871. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  40872. * how the new value is quoted.
  40873. */
  40874. ,
  40875. set: function set(v) {
  40876. if (this._constructed) {
  40877. var _unescapeValue2 = unescapeValue(v),
  40878. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  40879. unescaped = _unescapeValue2.unescaped,
  40880. quoteMark = _unescapeValue2.quoteMark;
  40881. if (deprecatedUsage) {
  40882. warnOfDeprecatedValueAssignment();
  40883. }
  40884. if (unescaped === this._value && quoteMark === this._quoteMark) {
  40885. return;
  40886. }
  40887. this._value = unescaped;
  40888. this._quoteMark = quoteMark;
  40889. this._syncRawValue();
  40890. } else {
  40891. this._value = v;
  40892. }
  40893. }
  40894. }, {
  40895. key: "attribute",
  40896. get: function get() {
  40897. return this._attribute;
  40898. },
  40899. set: function set(name) {
  40900. this._handleEscapes("attribute", name);
  40901. this._attribute = name;
  40902. }
  40903. }]);
  40904. return Attribute;
  40905. }(_namespace["default"]);
  40906. exports["default"] = Attribute;
  40907. Attribute.NO_QUOTE = null;
  40908. Attribute.SINGLE_QUOTE = "'";
  40909. Attribute.DOUBLE_QUOTE = '"';
  40910. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  40911. "'": {
  40912. quotes: 'single',
  40913. wrap: true
  40914. },
  40915. '"': {
  40916. quotes: 'double',
  40917. wrap: true
  40918. }
  40919. }, _CSSESC_QUOTE_OPTIONS[null] = {
  40920. isIdentifier: true
  40921. }, _CSSESC_QUOTE_OPTIONS);
  40922. function defaultAttrConcat(attrValue, attrSpaces) {
  40923. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  40924. }
  40925. });
  40926. var universal = createCommonjsModule(function (module, exports) {
  40927. exports.__esModule = true;
  40928. exports["default"] = void 0;
  40929. var _namespace = _interopRequireDefault(namespace);
  40930. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40931. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  40932. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  40933. var Universal = /*#__PURE__*/function (_Namespace) {
  40934. _inheritsLoose(Universal, _Namespace);
  40935. function Universal(opts) {
  40936. var _this;
  40937. _this = _Namespace.call(this, opts) || this;
  40938. _this.type = types$1.UNIVERSAL;
  40939. _this.value = '*';
  40940. return _this;
  40941. }
  40942. return Universal;
  40943. }(_namespace["default"]);
  40944. exports["default"] = Universal;
  40945. module.exports = exports.default;
  40946. });
  40947. var combinator = createCommonjsModule(function (module, exports) {
  40948. exports.__esModule = true;
  40949. exports["default"] = void 0;
  40950. var _node = _interopRequireDefault(node);
  40951. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40952. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  40953. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  40954. var Combinator = /*#__PURE__*/function (_Node) {
  40955. _inheritsLoose(Combinator, _Node);
  40956. function Combinator(opts) {
  40957. var _this;
  40958. _this = _Node.call(this, opts) || this;
  40959. _this.type = types$1.COMBINATOR;
  40960. return _this;
  40961. }
  40962. return Combinator;
  40963. }(_node["default"]);
  40964. exports["default"] = Combinator;
  40965. module.exports = exports.default;
  40966. });
  40967. var nesting = createCommonjsModule(function (module, exports) {
  40968. exports.__esModule = true;
  40969. exports["default"] = void 0;
  40970. var _node = _interopRequireDefault(node);
  40971. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40972. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  40973. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  40974. var Nesting = /*#__PURE__*/function (_Node) {
  40975. _inheritsLoose(Nesting, _Node);
  40976. function Nesting(opts) {
  40977. var _this;
  40978. _this = _Node.call(this, opts) || this;
  40979. _this.type = types$1.NESTING;
  40980. _this.value = '&';
  40981. return _this;
  40982. }
  40983. return Nesting;
  40984. }(_node["default"]);
  40985. exports["default"] = Nesting;
  40986. module.exports = exports.default;
  40987. });
  40988. var sortAscending_1 = createCommonjsModule(function (module, exports) {
  40989. exports.__esModule = true;
  40990. exports["default"] = sortAscending;
  40991. function sortAscending(list) {
  40992. return list.sort(function (a, b) {
  40993. return a - b;
  40994. });
  40995. }
  40996. module.exports = exports.default;
  40997. });
  40998. var tokenTypes$1 = createCommonjsModule(function (module, exports) {
  40999. exports.__esModule = true;
  41000. 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;
  41001. var ampersand = 38; // `&`.charCodeAt(0);
  41002. exports.ampersand = ampersand;
  41003. var asterisk = 42; // `*`.charCodeAt(0);
  41004. exports.asterisk = asterisk;
  41005. var at = 64; // `@`.charCodeAt(0);
  41006. exports.at = at;
  41007. var comma = 44; // `,`.charCodeAt(0);
  41008. exports.comma = comma;
  41009. var colon = 58; // `:`.charCodeAt(0);
  41010. exports.colon = colon;
  41011. var semicolon = 59; // `;`.charCodeAt(0);
  41012. exports.semicolon = semicolon;
  41013. var openParenthesis = 40; // `(`.charCodeAt(0);
  41014. exports.openParenthesis = openParenthesis;
  41015. var closeParenthesis = 41; // `)`.charCodeAt(0);
  41016. exports.closeParenthesis = closeParenthesis;
  41017. var openSquare = 91; // `[`.charCodeAt(0);
  41018. exports.openSquare = openSquare;
  41019. var closeSquare = 93; // `]`.charCodeAt(0);
  41020. exports.closeSquare = closeSquare;
  41021. var dollar = 36; // `$`.charCodeAt(0);
  41022. exports.dollar = dollar;
  41023. var tilde = 126; // `~`.charCodeAt(0);
  41024. exports.tilde = tilde;
  41025. var caret = 94; // `^`.charCodeAt(0);
  41026. exports.caret = caret;
  41027. var plus = 43; // `+`.charCodeAt(0);
  41028. exports.plus = plus;
  41029. var equals = 61; // `=`.charCodeAt(0);
  41030. exports.equals = equals;
  41031. var pipe = 124; // `|`.charCodeAt(0);
  41032. exports.pipe = pipe;
  41033. var greaterThan = 62; // `>`.charCodeAt(0);
  41034. exports.greaterThan = greaterThan;
  41035. var space = 32; // ` `.charCodeAt(0);
  41036. exports.space = space;
  41037. var singleQuote = 39; // `'`.charCodeAt(0);
  41038. exports.singleQuote = singleQuote;
  41039. var doubleQuote = 34; // `"`.charCodeAt(0);
  41040. exports.doubleQuote = doubleQuote;
  41041. var slash = 47; // `/`.charCodeAt(0);
  41042. exports.slash = slash;
  41043. var bang = 33; // `!`.charCodeAt(0);
  41044. exports.bang = bang;
  41045. var backslash = 92; // '\\'.charCodeAt(0);
  41046. exports.backslash = backslash;
  41047. var cr = 13; // '\r'.charCodeAt(0);
  41048. exports.cr = cr;
  41049. var feed = 12; // '\f'.charCodeAt(0);
  41050. exports.feed = feed;
  41051. var newline = 10; // '\n'.charCodeAt(0);
  41052. exports.newline = newline;
  41053. var tab = 9; // '\t'.charCodeAt(0);
  41054. // Expose aliases primarily for readability.
  41055. exports.tab = tab;
  41056. var str = singleQuote; // No good single character representation!
  41057. exports.str = str;
  41058. var comment = -1;
  41059. exports.comment = comment;
  41060. var word = -2;
  41061. exports.word = word;
  41062. var combinator = -3;
  41063. exports.combinator = combinator;
  41064. });
  41065. var tokenize_1 = createCommonjsModule(function (module, exports) {
  41066. exports.__esModule = true;
  41067. exports["default"] = tokenize;
  41068. exports.FIELDS = void 0;
  41069. var t = _interopRequireWildcard(tokenTypes$1);
  41070. var _unescapable, _wordDelimiters;
  41071. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  41072. 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; }
  41073. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  41074. 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);
  41075. var hex = {};
  41076. var hexChars = "0123456789abcdefABCDEF";
  41077. for (var i = 0; i < hexChars.length; i++) {
  41078. hex[hexChars.charCodeAt(i)] = true;
  41079. }
  41080. /**
  41081. * Returns the last index of the bar css word
  41082. * @param {string} css The string in which the word begins
  41083. * @param {number} start The index into the string where word's first letter occurs
  41084. */
  41085. function consumeWord(css, start) {
  41086. var next = start;
  41087. var code;
  41088. do {
  41089. code = css.charCodeAt(next);
  41090. if (wordDelimiters[code]) {
  41091. return next - 1;
  41092. } else if (code === t.backslash) {
  41093. next = consumeEscape(css, next) + 1;
  41094. } else {
  41095. // All other characters are part of the word
  41096. next++;
  41097. }
  41098. } while (next < css.length);
  41099. return next - 1;
  41100. }
  41101. /**
  41102. * Returns the last index of the escape sequence
  41103. * @param {string} css The string in which the sequence begins
  41104. * @param {number} start The index into the string where escape character (`\`) occurs.
  41105. */
  41106. function consumeEscape(css, start) {
  41107. var next = start;
  41108. var code = css.charCodeAt(next + 1);
  41109. if (unescapable[code]) ; else if (hex[code]) {
  41110. var hexDigits = 0; // consume up to 6 hex chars
  41111. do {
  41112. next++;
  41113. hexDigits++;
  41114. code = css.charCodeAt(next + 1);
  41115. } while (hex[code] && hexDigits < 6); // if fewer than 6 hex chars, a trailing space ends the escape
  41116. if (hexDigits < 6 && code === t.space) {
  41117. next++;
  41118. }
  41119. } else {
  41120. // the next char is part of the current word
  41121. next++;
  41122. }
  41123. return next;
  41124. }
  41125. var FIELDS = {
  41126. TYPE: 0,
  41127. START_LINE: 1,
  41128. START_COL: 2,
  41129. END_LINE: 3,
  41130. END_COL: 4,
  41131. START_POS: 5,
  41132. END_POS: 6
  41133. };
  41134. exports.FIELDS = FIELDS;
  41135. function tokenize(input) {
  41136. var tokens = [];
  41137. var css = input.css.valueOf();
  41138. var _css = css,
  41139. length = _css.length;
  41140. var offset = -1;
  41141. var line = 1;
  41142. var start = 0;
  41143. var end = 0;
  41144. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  41145. function unclosed(what, fix) {
  41146. if (input.safe) {
  41147. // fyi: this is never set to true.
  41148. css += fix;
  41149. next = css.length - 1;
  41150. } else {
  41151. throw input.error('Unclosed ' + what, line, start - offset, start);
  41152. }
  41153. }
  41154. while (start < length) {
  41155. code = css.charCodeAt(start);
  41156. if (code === t.newline) {
  41157. offset = start;
  41158. line += 1;
  41159. }
  41160. switch (code) {
  41161. case t.space:
  41162. case t.tab:
  41163. case t.newline:
  41164. case t.cr:
  41165. case t.feed:
  41166. next = start;
  41167. do {
  41168. next += 1;
  41169. code = css.charCodeAt(next);
  41170. if (code === t.newline) {
  41171. offset = next;
  41172. line += 1;
  41173. }
  41174. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  41175. tokenType = t.space;
  41176. endLine = line;
  41177. endColumn = next - offset - 1;
  41178. end = next;
  41179. break;
  41180. case t.plus:
  41181. case t.greaterThan:
  41182. case t.tilde:
  41183. case t.pipe:
  41184. next = start;
  41185. do {
  41186. next += 1;
  41187. code = css.charCodeAt(next);
  41188. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  41189. tokenType = t.combinator;
  41190. endLine = line;
  41191. endColumn = start - offset;
  41192. end = next;
  41193. break;
  41194. // Consume these characters as single tokens.
  41195. case t.asterisk:
  41196. case t.ampersand:
  41197. case t.bang:
  41198. case t.comma:
  41199. case t.equals:
  41200. case t.dollar:
  41201. case t.caret:
  41202. case t.openSquare:
  41203. case t.closeSquare:
  41204. case t.colon:
  41205. case t.semicolon:
  41206. case t.openParenthesis:
  41207. case t.closeParenthesis:
  41208. next = start;
  41209. tokenType = code;
  41210. endLine = line;
  41211. endColumn = start - offset;
  41212. end = next + 1;
  41213. break;
  41214. case t.singleQuote:
  41215. case t.doubleQuote:
  41216. quote = code === t.singleQuote ? "'" : '"';
  41217. next = start;
  41218. do {
  41219. escaped = false;
  41220. next = css.indexOf(quote, next + 1);
  41221. if (next === -1) {
  41222. unclosed('quote', quote);
  41223. }
  41224. escapePos = next;
  41225. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  41226. escapePos -= 1;
  41227. escaped = !escaped;
  41228. }
  41229. } while (escaped);
  41230. tokenType = t.str;
  41231. endLine = line;
  41232. endColumn = start - offset;
  41233. end = next + 1;
  41234. break;
  41235. default:
  41236. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  41237. next = css.indexOf('*/', start + 2) + 1;
  41238. if (next === 0) {
  41239. unclosed('comment', '*/');
  41240. }
  41241. content = css.slice(start, next + 1);
  41242. lines = content.split('\n');
  41243. last = lines.length - 1;
  41244. if (last > 0) {
  41245. nextLine = line + last;
  41246. nextOffset = next - lines[last].length;
  41247. } else {
  41248. nextLine = line;
  41249. nextOffset = offset;
  41250. }
  41251. tokenType = t.comment;
  41252. line = nextLine;
  41253. endLine = nextLine;
  41254. endColumn = next - nextOffset;
  41255. } else if (code === t.slash) {
  41256. next = start;
  41257. tokenType = code;
  41258. endLine = line;
  41259. endColumn = start - offset;
  41260. end = next + 1;
  41261. } else {
  41262. next = consumeWord(css, start);
  41263. tokenType = t.word;
  41264. endLine = line;
  41265. endColumn = next - offset;
  41266. }
  41267. end = next + 1;
  41268. break;
  41269. } // Ensure that the token structure remains consistent
  41270. tokens.push([tokenType, // [0] Token type
  41271. line, // [1] Starting line
  41272. start - offset, // [2] Starting column
  41273. endLine, // [3] Ending line
  41274. endColumn, // [4] Ending column
  41275. start, // [5] Start position / Source index
  41276. end // [6] End position
  41277. ]); // Reset offset for the next token
  41278. if (nextOffset) {
  41279. offset = nextOffset;
  41280. nextOffset = null;
  41281. }
  41282. start = end;
  41283. }
  41284. return tokens;
  41285. }
  41286. });
  41287. var parser$1 = createCommonjsModule(function (module, exports) {
  41288. exports.__esModule = true;
  41289. exports["default"] = void 0;
  41290. var _root = _interopRequireDefault(root$1);
  41291. var _selector = _interopRequireDefault(selector);
  41292. var _className = _interopRequireDefault(className);
  41293. var _comment = _interopRequireDefault(comment$1);
  41294. var _id = _interopRequireDefault(id);
  41295. var _tag = _interopRequireDefault(tag);
  41296. var _string = _interopRequireDefault(string);
  41297. var _pseudo = _interopRequireDefault(pseudo);
  41298. var _attribute = _interopRequireWildcard(attribute);
  41299. var _universal = _interopRequireDefault(universal);
  41300. var _combinator = _interopRequireDefault(combinator);
  41301. var _nesting = _interopRequireDefault(nesting);
  41302. var _sortAscending = _interopRequireDefault(sortAscending_1);
  41303. var _tokenize = _interopRequireWildcard(tokenize_1);
  41304. var tokens = _interopRequireWildcard(tokenTypes$1);
  41305. var types = _interopRequireWildcard(types$1);
  41306. var _WHITESPACE_TOKENS, _Object$assign;
  41307. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  41308. 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; }
  41309. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41310. 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); } }
  41311. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  41312. 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);
  41313. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  41314. function tokenStart(token) {
  41315. return {
  41316. line: token[_tokenize.FIELDS.START_LINE],
  41317. column: token[_tokenize.FIELDS.START_COL]
  41318. };
  41319. }
  41320. function tokenEnd(token) {
  41321. return {
  41322. line: token[_tokenize.FIELDS.END_LINE],
  41323. column: token[_tokenize.FIELDS.END_COL]
  41324. };
  41325. }
  41326. function getSource(startLine, startColumn, endLine, endColumn) {
  41327. return {
  41328. start: {
  41329. line: startLine,
  41330. column: startColumn
  41331. },
  41332. end: {
  41333. line: endLine,
  41334. column: endColumn
  41335. }
  41336. };
  41337. }
  41338. function getTokenSource(token) {
  41339. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  41340. }
  41341. function getTokenSourceSpan(startToken, endToken) {
  41342. if (!startToken) {
  41343. return undefined;
  41344. }
  41345. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  41346. }
  41347. function unescapeProp(node, prop) {
  41348. var value = node[prop];
  41349. if (typeof value !== "string") {
  41350. return;
  41351. }
  41352. if (value.indexOf("\\") !== -1) {
  41353. (0, util$2.ensureObject)(node, 'raws');
  41354. node[prop] = (0, util$2.unesc)(value);
  41355. if (node.raws[prop] === undefined) {
  41356. node.raws[prop] = value;
  41357. }
  41358. }
  41359. return node;
  41360. }
  41361. function indexesOf(array, item) {
  41362. var i = -1;
  41363. var indexes = [];
  41364. while ((i = array.indexOf(item, i + 1)) !== -1) {
  41365. indexes.push(i);
  41366. }
  41367. return indexes;
  41368. }
  41369. function uniqs() {
  41370. var list = Array.prototype.concat.apply([], arguments);
  41371. return list.filter(function (item, i) {
  41372. return i === list.indexOf(item);
  41373. });
  41374. }
  41375. var Parser = /*#__PURE__*/function () {
  41376. function Parser(rule, options) {
  41377. if (options === void 0) {
  41378. options = {};
  41379. }
  41380. this.rule = rule;
  41381. this.options = Object.assign({
  41382. lossy: false,
  41383. safe: false
  41384. }, options);
  41385. this.position = 0;
  41386. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  41387. this.tokens = (0, _tokenize["default"])({
  41388. css: this.css,
  41389. error: this._errorGenerator(),
  41390. safe: this.options.safe
  41391. });
  41392. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  41393. this.root = new _root["default"]({
  41394. source: rootSource
  41395. });
  41396. this.root.errorGenerator = this._errorGenerator();
  41397. var selector = new _selector["default"]({
  41398. source: {
  41399. start: {
  41400. line: 1,
  41401. column: 1
  41402. }
  41403. }
  41404. });
  41405. this.root.append(selector);
  41406. this.current = selector;
  41407. this.loop();
  41408. }
  41409. var _proto = Parser.prototype;
  41410. _proto._errorGenerator = function _errorGenerator() {
  41411. var _this = this;
  41412. return function (message, errorOptions) {
  41413. if (typeof _this.rule === 'string') {
  41414. return new Error(message);
  41415. }
  41416. return _this.rule.error(message, errorOptions);
  41417. };
  41418. };
  41419. _proto.attribute = function attribute() {
  41420. var attr = [];
  41421. var startingToken = this.currToken;
  41422. this.position++;
  41423. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  41424. attr.push(this.currToken);
  41425. this.position++;
  41426. }
  41427. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  41428. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  41429. }
  41430. var len = attr.length;
  41431. var node = {
  41432. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  41433. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  41434. };
  41435. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  41436. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  41437. }
  41438. var pos = 0;
  41439. var spaceBefore = '';
  41440. var commentBefore = '';
  41441. var lastAdded = null;
  41442. var spaceAfterMeaningfulToken = false;
  41443. while (pos < len) {
  41444. var token = attr[pos];
  41445. var content = this.content(token);
  41446. var next = attr[pos + 1];
  41447. switch (token[_tokenize.FIELDS.TYPE]) {
  41448. case tokens.space:
  41449. // if (
  41450. // len === 1 ||
  41451. // pos === 0 && this.content(next) === '|'
  41452. // ) {
  41453. // return this.expected('attribute', token[TOKEN.START_POS], content);
  41454. // }
  41455. spaceAfterMeaningfulToken = true;
  41456. if (this.options.lossy) {
  41457. break;
  41458. }
  41459. if (lastAdded) {
  41460. (0, util$2.ensureObject)(node, 'spaces', lastAdded);
  41461. var prevContent = node.spaces[lastAdded].after || '';
  41462. node.spaces[lastAdded].after = prevContent + content;
  41463. var existingComment = (0, util$2.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  41464. if (existingComment) {
  41465. node.raws.spaces[lastAdded].after = existingComment + content;
  41466. }
  41467. } else {
  41468. spaceBefore = spaceBefore + content;
  41469. commentBefore = commentBefore + content;
  41470. }
  41471. break;
  41472. case tokens.asterisk:
  41473. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  41474. node.operator = content;
  41475. lastAdded = 'operator';
  41476. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  41477. if (spaceBefore) {
  41478. (0, util$2.ensureObject)(node, 'spaces', 'attribute');
  41479. node.spaces.attribute.before = spaceBefore;
  41480. spaceBefore = '';
  41481. }
  41482. if (commentBefore) {
  41483. (0, util$2.ensureObject)(node, 'raws', 'spaces', 'attribute');
  41484. node.raws.spaces.attribute.before = spaceBefore;
  41485. commentBefore = '';
  41486. }
  41487. node.namespace = (node.namespace || "") + content;
  41488. var rawValue = (0, util$2.getProp)(node, 'raws', 'namespace') || null;
  41489. if (rawValue) {
  41490. node.raws.namespace += content;
  41491. }
  41492. lastAdded = 'namespace';
  41493. }
  41494. spaceAfterMeaningfulToken = false;
  41495. break;
  41496. case tokens.dollar:
  41497. if (lastAdded === "value") {
  41498. var oldRawValue = (0, util$2.getProp)(node, 'raws', 'value');
  41499. node.value += "$";
  41500. if (oldRawValue) {
  41501. node.raws.value = oldRawValue + "$";
  41502. }
  41503. break;
  41504. }
  41505. // Falls through
  41506. case tokens.caret:
  41507. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  41508. node.operator = content;
  41509. lastAdded = 'operator';
  41510. }
  41511. spaceAfterMeaningfulToken = false;
  41512. break;
  41513. case tokens.combinator:
  41514. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  41515. node.operator = content;
  41516. lastAdded = 'operator';
  41517. }
  41518. if (content !== '|') {
  41519. spaceAfterMeaningfulToken = false;
  41520. break;
  41521. }
  41522. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  41523. node.operator = content;
  41524. lastAdded = 'operator';
  41525. } else if (!node.namespace && !node.attribute) {
  41526. node.namespace = true;
  41527. }
  41528. spaceAfterMeaningfulToken = false;
  41529. break;
  41530. case tokens.word:
  41531. 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.
  41532. !node.operator && !node.namespace) {
  41533. node.namespace = content;
  41534. lastAdded = 'namespace';
  41535. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  41536. if (spaceBefore) {
  41537. (0, util$2.ensureObject)(node, 'spaces', 'attribute');
  41538. node.spaces.attribute.before = spaceBefore;
  41539. spaceBefore = '';
  41540. }
  41541. if (commentBefore) {
  41542. (0, util$2.ensureObject)(node, 'raws', 'spaces', 'attribute');
  41543. node.raws.spaces.attribute.before = commentBefore;
  41544. commentBefore = '';
  41545. }
  41546. node.attribute = (node.attribute || "") + content;
  41547. var _rawValue = (0, util$2.getProp)(node, 'raws', 'attribute') || null;
  41548. if (_rawValue) {
  41549. node.raws.attribute += content;
  41550. }
  41551. lastAdded = 'attribute';
  41552. } else if (!node.value && node.value !== "" || lastAdded === "value" && !spaceAfterMeaningfulToken) {
  41553. var _unescaped = (0, util$2.unesc)(content);
  41554. var _oldRawValue = (0, util$2.getProp)(node, 'raws', 'value') || '';
  41555. var oldValue = node.value || '';
  41556. node.value = oldValue + _unescaped;
  41557. node.quoteMark = null;
  41558. if (_unescaped !== content || _oldRawValue) {
  41559. (0, util$2.ensureObject)(node, 'raws');
  41560. node.raws.value = (_oldRawValue || oldValue) + content;
  41561. }
  41562. lastAdded = 'value';
  41563. } else {
  41564. var insensitive = content === 'i' || content === "I";
  41565. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  41566. node.insensitive = insensitive;
  41567. if (!insensitive || content === "I") {
  41568. (0, util$2.ensureObject)(node, 'raws');
  41569. node.raws.insensitiveFlag = content;
  41570. }
  41571. lastAdded = 'insensitive';
  41572. if (spaceBefore) {
  41573. (0, util$2.ensureObject)(node, 'spaces', 'insensitive');
  41574. node.spaces.insensitive.before = spaceBefore;
  41575. spaceBefore = '';
  41576. }
  41577. if (commentBefore) {
  41578. (0, util$2.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  41579. node.raws.spaces.insensitive.before = commentBefore;
  41580. commentBefore = '';
  41581. }
  41582. } else if (node.value || node.value === '') {
  41583. lastAdded = 'value';
  41584. node.value += content;
  41585. if (node.raws.value) {
  41586. node.raws.value += content;
  41587. }
  41588. }
  41589. }
  41590. spaceAfterMeaningfulToken = false;
  41591. break;
  41592. case tokens.str:
  41593. if (!node.attribute || !node.operator) {
  41594. return this.error("Expected an attribute followed by an operator preceding the string.", {
  41595. index: token[_tokenize.FIELDS.START_POS]
  41596. });
  41597. }
  41598. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  41599. unescaped = _unescapeValue.unescaped,
  41600. quoteMark = _unescapeValue.quoteMark;
  41601. node.value = unescaped;
  41602. node.quoteMark = quoteMark;
  41603. lastAdded = 'value';
  41604. (0, util$2.ensureObject)(node, 'raws');
  41605. node.raws.value = content;
  41606. spaceAfterMeaningfulToken = false;
  41607. break;
  41608. case tokens.equals:
  41609. if (!node.attribute) {
  41610. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  41611. }
  41612. if (node.value) {
  41613. return this.error('Unexpected "=" found; an operator was already defined.', {
  41614. index: token[_tokenize.FIELDS.START_POS]
  41615. });
  41616. }
  41617. node.operator = node.operator ? node.operator + content : content;
  41618. lastAdded = 'operator';
  41619. spaceAfterMeaningfulToken = false;
  41620. break;
  41621. case tokens.comment:
  41622. if (lastAdded) {
  41623. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  41624. var lastComment = (0, util$2.getProp)(node, 'spaces', lastAdded, 'after') || '';
  41625. var rawLastComment = (0, util$2.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  41626. (0, util$2.ensureObject)(node, 'raws', 'spaces', lastAdded);
  41627. node.raws.spaces[lastAdded].after = rawLastComment + content;
  41628. } else {
  41629. var lastValue = node[lastAdded] || '';
  41630. var rawLastValue = (0, util$2.getProp)(node, 'raws', lastAdded) || lastValue;
  41631. (0, util$2.ensureObject)(node, 'raws');
  41632. node.raws[lastAdded] = rawLastValue + content;
  41633. }
  41634. } else {
  41635. commentBefore = commentBefore + content;
  41636. }
  41637. break;
  41638. default:
  41639. return this.error("Unexpected \"" + content + "\" found.", {
  41640. index: token[_tokenize.FIELDS.START_POS]
  41641. });
  41642. }
  41643. pos++;
  41644. }
  41645. unescapeProp(node, "attribute");
  41646. unescapeProp(node, "namespace");
  41647. this.newNode(new _attribute["default"](node));
  41648. this.position++;
  41649. }
  41650. /**
  41651. * return a node containing meaningless garbage up to (but not including) the specified token position.
  41652. * if the token position is negative, all remaining tokens are consumed.
  41653. *
  41654. * This returns an array containing a single string node if all whitespace,
  41655. * otherwise an array of comment nodes with space before and after.
  41656. *
  41657. * These tokens are not added to the current selector, the caller can add them or use them to amend
  41658. * a previous node's space metadata.
  41659. *
  41660. * In lossy mode, this returns only comments.
  41661. */
  41662. ;
  41663. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  41664. if (stopPosition < 0) {
  41665. stopPosition = this.tokens.length;
  41666. }
  41667. var startPosition = this.position;
  41668. var nodes = [];
  41669. var space = "";
  41670. var lastComment = undefined;
  41671. do {
  41672. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  41673. if (!this.options.lossy) {
  41674. space += this.content();
  41675. }
  41676. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  41677. var spaces = {};
  41678. if (space) {
  41679. spaces.before = space;
  41680. space = "";
  41681. }
  41682. lastComment = new _comment["default"]({
  41683. value: this.content(),
  41684. source: getTokenSource(this.currToken),
  41685. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  41686. spaces: spaces
  41687. });
  41688. nodes.push(lastComment);
  41689. }
  41690. } while (++this.position < stopPosition);
  41691. if (space) {
  41692. if (lastComment) {
  41693. lastComment.spaces.after = space;
  41694. } else if (!this.options.lossy) {
  41695. var firstToken = this.tokens[startPosition];
  41696. var lastToken = this.tokens[this.position - 1];
  41697. nodes.push(new _string["default"]({
  41698. value: '',
  41699. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  41700. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  41701. spaces: {
  41702. before: space,
  41703. after: ''
  41704. }
  41705. }));
  41706. }
  41707. }
  41708. return nodes;
  41709. }
  41710. /**
  41711. *
  41712. * @param {*} nodes
  41713. */
  41714. ;
  41715. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  41716. var _this2 = this;
  41717. if (requiredSpace === void 0) {
  41718. requiredSpace = false;
  41719. }
  41720. var space = "";
  41721. var rawSpace = "";
  41722. nodes.forEach(function (n) {
  41723. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  41724. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  41725. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  41726. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  41727. });
  41728. if (rawSpace === space) {
  41729. rawSpace = undefined;
  41730. }
  41731. var result = {
  41732. space: space,
  41733. rawSpace: rawSpace
  41734. };
  41735. return result;
  41736. };
  41737. _proto.isNamedCombinator = function isNamedCombinator(position) {
  41738. if (position === void 0) {
  41739. position = this.position;
  41740. }
  41741. 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;
  41742. };
  41743. _proto.namedCombinator = function namedCombinator() {
  41744. if (this.isNamedCombinator()) {
  41745. var nameRaw = this.content(this.tokens[this.position + 1]);
  41746. var name = (0, util$2.unesc)(nameRaw).toLowerCase();
  41747. var raws = {};
  41748. if (name !== nameRaw) {
  41749. raws.value = "/" + nameRaw + "/";
  41750. }
  41751. var node = new _combinator["default"]({
  41752. value: "/" + name + "/",
  41753. 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]),
  41754. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  41755. raws: raws
  41756. });
  41757. this.position = this.position + 3;
  41758. return node;
  41759. } else {
  41760. this.unexpected();
  41761. }
  41762. };
  41763. _proto.combinator = function combinator() {
  41764. var _this3 = this;
  41765. if (this.content() === '|') {
  41766. return this.namespace();
  41767. } // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  41768. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  41769. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma) {
  41770. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  41771. if (nodes.length > 0) {
  41772. var last = this.current.last;
  41773. if (last) {
  41774. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  41775. space = _this$convertWhitespa.space,
  41776. rawSpace = _this$convertWhitespa.rawSpace;
  41777. if (rawSpace !== undefined) {
  41778. last.rawSpaceAfter += rawSpace;
  41779. }
  41780. last.spaces.after += space;
  41781. } else {
  41782. nodes.forEach(function (n) {
  41783. return _this3.newNode(n);
  41784. });
  41785. }
  41786. }
  41787. return;
  41788. }
  41789. var firstToken = this.currToken;
  41790. var spaceOrDescendantSelectorNodes = undefined;
  41791. if (nextSigTokenPos > this.position) {
  41792. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  41793. }
  41794. var node;
  41795. if (this.isNamedCombinator()) {
  41796. node = this.namedCombinator();
  41797. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  41798. node = new _combinator["default"]({
  41799. value: this.content(),
  41800. source: getTokenSource(this.currToken),
  41801. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  41802. });
  41803. this.position++;
  41804. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  41805. this.unexpected();
  41806. }
  41807. if (node) {
  41808. if (spaceOrDescendantSelectorNodes) {
  41809. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  41810. _space = _this$convertWhitespa2.space,
  41811. _rawSpace = _this$convertWhitespa2.rawSpace;
  41812. node.spaces.before = _space;
  41813. node.rawSpaceBefore = _rawSpace;
  41814. }
  41815. } else {
  41816. // descendant combinator
  41817. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  41818. _space2 = _this$convertWhitespa3.space,
  41819. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  41820. if (!_rawSpace2) {
  41821. _rawSpace2 = _space2;
  41822. }
  41823. var spaces = {};
  41824. var raws = {
  41825. spaces: {}
  41826. };
  41827. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  41828. spaces.before = _space2.slice(0, _space2.length - 1);
  41829. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  41830. } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
  41831. spaces.after = _space2.slice(1);
  41832. raws.spaces.after = _rawSpace2.slice(1);
  41833. } else {
  41834. raws.value = _rawSpace2;
  41835. }
  41836. node = new _combinator["default"]({
  41837. value: ' ',
  41838. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  41839. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  41840. spaces: spaces,
  41841. raws: raws
  41842. });
  41843. }
  41844. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  41845. node.spaces.after = this.optionalSpace(this.content());
  41846. this.position++;
  41847. }
  41848. return this.newNode(node);
  41849. };
  41850. _proto.comma = function comma() {
  41851. if (this.position === this.tokens.length - 1) {
  41852. this.root.trailingComma = true;
  41853. this.position++;
  41854. return;
  41855. }
  41856. this.current._inferEndPosition();
  41857. var selector = new _selector["default"]({
  41858. source: {
  41859. start: tokenStart(this.tokens[this.position + 1])
  41860. }
  41861. });
  41862. this.current.parent.append(selector);
  41863. this.current = selector;
  41864. this.position++;
  41865. };
  41866. _proto.comment = function comment() {
  41867. var current = this.currToken;
  41868. this.newNode(new _comment["default"]({
  41869. value: this.content(),
  41870. source: getTokenSource(current),
  41871. sourceIndex: current[_tokenize.FIELDS.START_POS]
  41872. }));
  41873. this.position++;
  41874. };
  41875. _proto.error = function error(message, opts) {
  41876. throw this.root.error(message, opts);
  41877. };
  41878. _proto.missingBackslash = function missingBackslash() {
  41879. return this.error('Expected a backslash preceding the semicolon.', {
  41880. index: this.currToken[_tokenize.FIELDS.START_POS]
  41881. });
  41882. };
  41883. _proto.missingParenthesis = function missingParenthesis() {
  41884. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  41885. };
  41886. _proto.missingSquareBracket = function missingSquareBracket() {
  41887. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  41888. };
  41889. _proto.unexpected = function unexpected() {
  41890. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  41891. };
  41892. _proto.namespace = function namespace() {
  41893. var before = this.prevToken && this.content(this.prevToken) || true;
  41894. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  41895. this.position++;
  41896. return this.word(before);
  41897. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  41898. this.position++;
  41899. return this.universal(before);
  41900. }
  41901. };
  41902. _proto.nesting = function nesting() {
  41903. if (this.nextToken) {
  41904. var nextContent = this.content(this.nextToken);
  41905. if (nextContent === "|") {
  41906. this.position++;
  41907. return;
  41908. }
  41909. }
  41910. var current = this.currToken;
  41911. this.newNode(new _nesting["default"]({
  41912. value: this.content(),
  41913. source: getTokenSource(current),
  41914. sourceIndex: current[_tokenize.FIELDS.START_POS]
  41915. }));
  41916. this.position++;
  41917. };
  41918. _proto.parentheses = function parentheses() {
  41919. var last = this.current.last;
  41920. var unbalanced = 1;
  41921. this.position++;
  41922. if (last && last.type === types.PSEUDO) {
  41923. var selector = new _selector["default"]({
  41924. source: {
  41925. start: tokenStart(this.tokens[this.position - 1])
  41926. }
  41927. });
  41928. var cache = this.current;
  41929. last.append(selector);
  41930. this.current = selector;
  41931. while (this.position < this.tokens.length && unbalanced) {
  41932. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  41933. unbalanced++;
  41934. }
  41935. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  41936. unbalanced--;
  41937. }
  41938. if (unbalanced) {
  41939. this.parse();
  41940. } else {
  41941. this.current.source.end = tokenEnd(this.currToken);
  41942. this.current.parent.source.end = tokenEnd(this.currToken);
  41943. this.position++;
  41944. }
  41945. }
  41946. this.current = cache;
  41947. } else {
  41948. // I think this case should be an error. It's used to implement a basic parse of media queries
  41949. // but I don't think it's a good idea.
  41950. var parenStart = this.currToken;
  41951. var parenValue = "(";
  41952. var parenEnd;
  41953. while (this.position < this.tokens.length && unbalanced) {
  41954. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  41955. unbalanced++;
  41956. }
  41957. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  41958. unbalanced--;
  41959. }
  41960. parenEnd = this.currToken;
  41961. parenValue += this.parseParenthesisToken(this.currToken);
  41962. this.position++;
  41963. }
  41964. if (last) {
  41965. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  41966. } else {
  41967. this.newNode(new _string["default"]({
  41968. value: parenValue,
  41969. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  41970. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  41971. }));
  41972. }
  41973. }
  41974. if (unbalanced) {
  41975. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  41976. }
  41977. };
  41978. _proto.pseudo = function pseudo() {
  41979. var _this4 = this;
  41980. var pseudoStr = '';
  41981. var startingToken = this.currToken;
  41982. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  41983. pseudoStr += this.content();
  41984. this.position++;
  41985. }
  41986. if (!this.currToken) {
  41987. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  41988. }
  41989. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  41990. this.splitWord(false, function (first, length) {
  41991. pseudoStr += first;
  41992. _this4.newNode(new _pseudo["default"]({
  41993. value: pseudoStr,
  41994. source: getTokenSourceSpan(startingToken, _this4.currToken),
  41995. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  41996. }));
  41997. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  41998. _this4.error('Misplaced parenthesis.', {
  41999. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  42000. });
  42001. }
  42002. });
  42003. } else {
  42004. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  42005. }
  42006. };
  42007. _proto.space = function space() {
  42008. var content = this.content(); // Handle space before and after the selector
  42009. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  42010. return node.type === 'comment';
  42011. })) {
  42012. this.spaces = this.optionalSpace(content);
  42013. this.position++;
  42014. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  42015. this.current.last.spaces.after = this.optionalSpace(content);
  42016. this.position++;
  42017. } else {
  42018. this.combinator();
  42019. }
  42020. };
  42021. _proto.string = function string() {
  42022. var current = this.currToken;
  42023. this.newNode(new _string["default"]({
  42024. value: this.content(),
  42025. source: getTokenSource(current),
  42026. sourceIndex: current[_tokenize.FIELDS.START_POS]
  42027. }));
  42028. this.position++;
  42029. };
  42030. _proto.universal = function universal(namespace) {
  42031. var nextToken = this.nextToken;
  42032. if (nextToken && this.content(nextToken) === '|') {
  42033. this.position++;
  42034. return this.namespace();
  42035. }
  42036. var current = this.currToken;
  42037. this.newNode(new _universal["default"]({
  42038. value: this.content(),
  42039. source: getTokenSource(current),
  42040. sourceIndex: current[_tokenize.FIELDS.START_POS]
  42041. }), namespace);
  42042. this.position++;
  42043. };
  42044. _proto.splitWord = function splitWord(namespace, firstCallback) {
  42045. var _this5 = this;
  42046. var nextToken = this.nextToken;
  42047. var word = this.content();
  42048. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  42049. this.position++;
  42050. var current = this.content();
  42051. word += current;
  42052. if (current.lastIndexOf('\\') === current.length - 1) {
  42053. var next = this.nextToken;
  42054. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  42055. word += this.requiredSpace(this.content(next));
  42056. this.position++;
  42057. }
  42058. }
  42059. nextToken = this.nextToken;
  42060. }
  42061. var hasClass = indexesOf(word, '.').filter(function (i) {
  42062. // Allow escaped dot within class name
  42063. var escapedDot = word[i - 1] === '\\'; // Allow decimal numbers percent in @keyframes
  42064. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  42065. return !escapedDot && !isKeyframesPercent;
  42066. });
  42067. var hasId = indexesOf(word, '#').filter(function (i) {
  42068. return word[i - 1] !== '\\';
  42069. }); // Eliminate Sass interpolations from the list of id indexes
  42070. var interpolations = indexesOf(word, '#{');
  42071. if (interpolations.length) {
  42072. hasId = hasId.filter(function (hashIndex) {
  42073. return !~interpolations.indexOf(hashIndex);
  42074. });
  42075. }
  42076. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  42077. indices.forEach(function (ind, i) {
  42078. var index = indices[i + 1] || word.length;
  42079. var value = word.slice(ind, index);
  42080. if (i === 0 && firstCallback) {
  42081. return firstCallback.call(_this5, value, indices.length);
  42082. }
  42083. var node;
  42084. var current = _this5.currToken;
  42085. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  42086. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  42087. if (~hasClass.indexOf(ind)) {
  42088. var classNameOpts = {
  42089. value: value.slice(1),
  42090. source: source,
  42091. sourceIndex: sourceIndex
  42092. };
  42093. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  42094. } else if (~hasId.indexOf(ind)) {
  42095. var idOpts = {
  42096. value: value.slice(1),
  42097. source: source,
  42098. sourceIndex: sourceIndex
  42099. };
  42100. node = new _id["default"](unescapeProp(idOpts, "value"));
  42101. } else {
  42102. var tagOpts = {
  42103. value: value,
  42104. source: source,
  42105. sourceIndex: sourceIndex
  42106. };
  42107. unescapeProp(tagOpts, "value");
  42108. node = new _tag["default"](tagOpts);
  42109. }
  42110. _this5.newNode(node, namespace); // Ensure that the namespace is used only once
  42111. namespace = null;
  42112. });
  42113. this.position++;
  42114. };
  42115. _proto.word = function word(namespace) {
  42116. var nextToken = this.nextToken;
  42117. if (nextToken && this.content(nextToken) === '|') {
  42118. this.position++;
  42119. return this.namespace();
  42120. }
  42121. return this.splitWord(namespace);
  42122. };
  42123. _proto.loop = function loop() {
  42124. while (this.position < this.tokens.length) {
  42125. this.parse(true);
  42126. }
  42127. this.current._inferEndPosition();
  42128. return this.root;
  42129. };
  42130. _proto.parse = function parse(throwOnParenthesis) {
  42131. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  42132. case tokens.space:
  42133. this.space();
  42134. break;
  42135. case tokens.comment:
  42136. this.comment();
  42137. break;
  42138. case tokens.openParenthesis:
  42139. this.parentheses();
  42140. break;
  42141. case tokens.closeParenthesis:
  42142. if (throwOnParenthesis) {
  42143. this.missingParenthesis();
  42144. }
  42145. break;
  42146. case tokens.openSquare:
  42147. this.attribute();
  42148. break;
  42149. case tokens.dollar:
  42150. case tokens.caret:
  42151. case tokens.equals:
  42152. case tokens.word:
  42153. this.word();
  42154. break;
  42155. case tokens.colon:
  42156. this.pseudo();
  42157. break;
  42158. case tokens.comma:
  42159. this.comma();
  42160. break;
  42161. case tokens.asterisk:
  42162. this.universal();
  42163. break;
  42164. case tokens.ampersand:
  42165. this.nesting();
  42166. break;
  42167. case tokens.slash:
  42168. case tokens.combinator:
  42169. this.combinator();
  42170. break;
  42171. case tokens.str:
  42172. this.string();
  42173. break;
  42174. // These cases throw; no break needed.
  42175. case tokens.closeSquare:
  42176. this.missingSquareBracket();
  42177. case tokens.semicolon:
  42178. this.missingBackslash();
  42179. default:
  42180. this.unexpected();
  42181. }
  42182. }
  42183. /**
  42184. * Helpers
  42185. */
  42186. ;
  42187. _proto.expected = function expected(description, index, found) {
  42188. if (Array.isArray(description)) {
  42189. var last = description.pop();
  42190. description = description.join(', ') + " or " + last;
  42191. }
  42192. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  42193. if (!found) {
  42194. return this.error("Expected " + an + " " + description + ".", {
  42195. index: index
  42196. });
  42197. }
  42198. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  42199. index: index
  42200. });
  42201. };
  42202. _proto.requiredSpace = function requiredSpace(space) {
  42203. return this.options.lossy ? ' ' : space;
  42204. };
  42205. _proto.optionalSpace = function optionalSpace(space) {
  42206. return this.options.lossy ? '' : space;
  42207. };
  42208. _proto.lossySpace = function lossySpace(space, required) {
  42209. if (this.options.lossy) {
  42210. return required ? ' ' : '';
  42211. } else {
  42212. return space;
  42213. }
  42214. };
  42215. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  42216. var content = this.content(token);
  42217. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  42218. return this.requiredSpace(content);
  42219. } else {
  42220. return content;
  42221. }
  42222. };
  42223. _proto.newNode = function newNode(node, namespace) {
  42224. if (namespace) {
  42225. if (/^ +$/.test(namespace)) {
  42226. if (!this.options.lossy) {
  42227. this.spaces = (this.spaces || '') + namespace;
  42228. }
  42229. namespace = true;
  42230. }
  42231. node.namespace = namespace;
  42232. unescapeProp(node, "namespace");
  42233. }
  42234. if (this.spaces) {
  42235. node.spaces.before = this.spaces;
  42236. this.spaces = '';
  42237. }
  42238. return this.current.append(node);
  42239. };
  42240. _proto.content = function content(token) {
  42241. if (token === void 0) {
  42242. token = this.currToken;
  42243. }
  42244. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  42245. };
  42246. /**
  42247. * returns the index of the next non-whitespace, non-comment token.
  42248. * returns -1 if no meaningful token is found.
  42249. */
  42250. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  42251. if (startPosition === void 0) {
  42252. startPosition = this.position + 1;
  42253. }
  42254. var searchPosition = startPosition;
  42255. while (searchPosition < this.tokens.length) {
  42256. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  42257. searchPosition++;
  42258. continue;
  42259. } else {
  42260. return searchPosition;
  42261. }
  42262. }
  42263. return -1;
  42264. };
  42265. _createClass(Parser, [{
  42266. key: "currToken",
  42267. get: function get() {
  42268. return this.tokens[this.position];
  42269. }
  42270. }, {
  42271. key: "nextToken",
  42272. get: function get() {
  42273. return this.tokens[this.position + 1];
  42274. }
  42275. }, {
  42276. key: "prevToken",
  42277. get: function get() {
  42278. return this.tokens[this.position - 1];
  42279. }
  42280. }]);
  42281. return Parser;
  42282. }();
  42283. exports["default"] = Parser;
  42284. module.exports = exports.default;
  42285. });
  42286. var processor$1 = createCommonjsModule(function (module, exports) {
  42287. exports.__esModule = true;
  42288. exports["default"] = void 0;
  42289. var _parser = _interopRequireDefault(parser$1);
  42290. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  42291. var Processor = /*#__PURE__*/function () {
  42292. function Processor(func, options) {
  42293. this.func = func || function noop() {};
  42294. this.funcRes = null;
  42295. this.options = options;
  42296. }
  42297. var _proto = Processor.prototype;
  42298. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  42299. if (options === void 0) {
  42300. options = {};
  42301. }
  42302. var merged = Object.assign({}, this.options, options);
  42303. if (merged.updateSelector === false) {
  42304. return false;
  42305. } else {
  42306. return typeof rule !== "string";
  42307. }
  42308. };
  42309. _proto._isLossy = function _isLossy(options) {
  42310. if (options === void 0) {
  42311. options = {};
  42312. }
  42313. var merged = Object.assign({}, this.options, options);
  42314. if (merged.lossless === false) {
  42315. return true;
  42316. } else {
  42317. return false;
  42318. }
  42319. };
  42320. _proto._root = function _root(rule, options) {
  42321. if (options === void 0) {
  42322. options = {};
  42323. }
  42324. var parser = new _parser["default"](rule, this._parseOptions(options));
  42325. return parser.root;
  42326. };
  42327. _proto._parseOptions = function _parseOptions(options) {
  42328. return {
  42329. lossy: this._isLossy(options)
  42330. };
  42331. };
  42332. _proto._run = function _run(rule, options) {
  42333. var _this = this;
  42334. if (options === void 0) {
  42335. options = {};
  42336. }
  42337. return new Promise(function (resolve, reject) {
  42338. try {
  42339. var root = _this._root(rule, options);
  42340. Promise.resolve(_this.func(root)).then(function (transform) {
  42341. var string = undefined;
  42342. if (_this._shouldUpdateSelector(rule, options)) {
  42343. string = root.toString();
  42344. rule.selector = string;
  42345. }
  42346. return {
  42347. transform: transform,
  42348. root: root,
  42349. string: string
  42350. };
  42351. }).then(resolve, reject);
  42352. } catch (e) {
  42353. reject(e);
  42354. return;
  42355. }
  42356. });
  42357. };
  42358. _proto._runSync = function _runSync(rule, options) {
  42359. if (options === void 0) {
  42360. options = {};
  42361. }
  42362. var root = this._root(rule, options);
  42363. var transform = this.func(root);
  42364. if (transform && typeof transform.then === "function") {
  42365. throw new Error("Selector processor returned a promise to a synchronous call.");
  42366. }
  42367. var string = undefined;
  42368. if (options.updateSelector && typeof rule !== "string") {
  42369. string = root.toString();
  42370. rule.selector = string;
  42371. }
  42372. return {
  42373. transform: transform,
  42374. root: root,
  42375. string: string
  42376. };
  42377. }
  42378. /**
  42379. * Process rule into a selector AST.
  42380. *
  42381. * @param rule {postcss.Rule | string} The css selector to be processed
  42382. * @param options The options for processing
  42383. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  42384. */
  42385. ;
  42386. _proto.ast = function ast(rule, options) {
  42387. return this._run(rule, options).then(function (result) {
  42388. return result.root;
  42389. });
  42390. }
  42391. /**
  42392. * Process rule into a selector AST synchronously.
  42393. *
  42394. * @param rule {postcss.Rule | string} The css selector to be processed
  42395. * @param options The options for processing
  42396. * @returns {parser.Root} The AST of the selector after processing it.
  42397. */
  42398. ;
  42399. _proto.astSync = function astSync(rule, options) {
  42400. return this._runSync(rule, options).root;
  42401. }
  42402. /**
  42403. * Process a selector into a transformed value asynchronously
  42404. *
  42405. * @param rule {postcss.Rule | string} The css selector to be processed
  42406. * @param options The options for processing
  42407. * @returns {Promise<any>} The value returned by the processor.
  42408. */
  42409. ;
  42410. _proto.transform = function transform(rule, options) {
  42411. return this._run(rule, options).then(function (result) {
  42412. return result.transform;
  42413. });
  42414. }
  42415. /**
  42416. * Process a selector into a transformed value synchronously.
  42417. *
  42418. * @param rule {postcss.Rule | string} The css selector to be processed
  42419. * @param options The options for processing
  42420. * @returns {any} The value returned by the processor.
  42421. */
  42422. ;
  42423. _proto.transformSync = function transformSync(rule, options) {
  42424. return this._runSync(rule, options).transform;
  42425. }
  42426. /**
  42427. * Process a selector into a new selector string asynchronously.
  42428. *
  42429. * @param rule {postcss.Rule | string} The css selector to be processed
  42430. * @param options The options for processing
  42431. * @returns {string} the selector after processing.
  42432. */
  42433. ;
  42434. _proto.process = function process(rule, options) {
  42435. return this._run(rule, options).then(function (result) {
  42436. return result.string || result.root.toString();
  42437. });
  42438. }
  42439. /**
  42440. * Process a selector into a new selector string synchronously.
  42441. *
  42442. * @param rule {postcss.Rule | string} The css selector to be processed
  42443. * @param options The options for processing
  42444. * @returns {string} the selector after processing.
  42445. */
  42446. ;
  42447. _proto.processSync = function processSync(rule, options) {
  42448. var result = this._runSync(rule, options);
  42449. return result.string || result.root.toString();
  42450. };
  42451. return Processor;
  42452. }();
  42453. exports["default"] = Processor;
  42454. module.exports = exports.default;
  42455. });
  42456. /*@__PURE__*/getDefaultExportFromCjs(processor$1);
  42457. var constructors = createCommonjsModule(function (module, exports) {
  42458. exports.__esModule = true;
  42459. 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;
  42460. var _attribute = _interopRequireDefault(attribute);
  42461. var _className = _interopRequireDefault(className);
  42462. var _combinator = _interopRequireDefault(combinator);
  42463. var _comment = _interopRequireDefault(comment$1);
  42464. var _id = _interopRequireDefault(id);
  42465. var _nesting = _interopRequireDefault(nesting);
  42466. var _pseudo = _interopRequireDefault(pseudo);
  42467. var _root = _interopRequireDefault(root$1);
  42468. var _selector = _interopRequireDefault(selector);
  42469. var _string = _interopRequireDefault(string);
  42470. var _tag = _interopRequireDefault(tag);
  42471. var _universal = _interopRequireDefault(universal);
  42472. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  42473. var attribute$1 = function attribute(opts) {
  42474. return new _attribute["default"](opts);
  42475. };
  42476. exports.attribute = attribute$1;
  42477. var className$1 = function className(opts) {
  42478. return new _className["default"](opts);
  42479. };
  42480. exports.className = className$1;
  42481. var combinator$1 = function combinator(opts) {
  42482. return new _combinator["default"](opts);
  42483. };
  42484. exports.combinator = combinator$1;
  42485. var comment = function comment(opts) {
  42486. return new _comment["default"](opts);
  42487. };
  42488. exports.comment = comment;
  42489. var id$1 = function id(opts) {
  42490. return new _id["default"](opts);
  42491. };
  42492. exports.id = id$1;
  42493. var nesting$1 = function nesting(opts) {
  42494. return new _nesting["default"](opts);
  42495. };
  42496. exports.nesting = nesting$1;
  42497. var pseudo$1 = function pseudo(opts) {
  42498. return new _pseudo["default"](opts);
  42499. };
  42500. exports.pseudo = pseudo$1;
  42501. var root = function root(opts) {
  42502. return new _root["default"](opts);
  42503. };
  42504. exports.root = root;
  42505. var selector$1 = function selector(opts) {
  42506. return new _selector["default"](opts);
  42507. };
  42508. exports.selector = selector$1;
  42509. var string$1 = function string(opts) {
  42510. return new _string["default"](opts);
  42511. };
  42512. exports.string = string$1;
  42513. var tag$1 = function tag(opts) {
  42514. return new _tag["default"](opts);
  42515. };
  42516. exports.tag = tag$1;
  42517. var universal$1 = function universal(opts) {
  42518. return new _universal["default"](opts);
  42519. };
  42520. exports.universal = universal$1;
  42521. });
  42522. var guards = createCommonjsModule(function (module, exports) {
  42523. exports.__esModule = true;
  42524. exports.isNode = isNode;
  42525. exports.isPseudoElement = isPseudoElement;
  42526. exports.isPseudoClass = isPseudoClass;
  42527. exports.isContainer = isContainer;
  42528. exports.isNamespace = isNamespace;
  42529. 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;
  42530. var _IS_TYPE;
  42531. 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);
  42532. function isNode(node) {
  42533. return typeof node === "object" && IS_TYPE[node.type];
  42534. }
  42535. function isNodeType(type, node) {
  42536. return isNode(node) && node.type === type;
  42537. }
  42538. var isAttribute = isNodeType.bind(null, types$1.ATTRIBUTE);
  42539. exports.isAttribute = isAttribute;
  42540. var isClassName = isNodeType.bind(null, types$1.CLASS);
  42541. exports.isClassName = isClassName;
  42542. var isCombinator = isNodeType.bind(null, types$1.COMBINATOR);
  42543. exports.isCombinator = isCombinator;
  42544. var isComment = isNodeType.bind(null, types$1.COMMENT);
  42545. exports.isComment = isComment;
  42546. var isIdentifier = isNodeType.bind(null, types$1.ID);
  42547. exports.isIdentifier = isIdentifier;
  42548. var isNesting = isNodeType.bind(null, types$1.NESTING);
  42549. exports.isNesting = isNesting;
  42550. var isPseudo = isNodeType.bind(null, types$1.PSEUDO);
  42551. exports.isPseudo = isPseudo;
  42552. var isRoot = isNodeType.bind(null, types$1.ROOT);
  42553. exports.isRoot = isRoot;
  42554. var isSelector = isNodeType.bind(null, types$1.SELECTOR);
  42555. exports.isSelector = isSelector;
  42556. var isString = isNodeType.bind(null, types$1.STRING);
  42557. exports.isString = isString;
  42558. var isTag = isNodeType.bind(null, types$1.TAG);
  42559. exports.isTag = isTag;
  42560. var isUniversal = isNodeType.bind(null, types$1.UNIVERSAL);
  42561. exports.isUniversal = isUniversal;
  42562. function isPseudoElement(node) {
  42563. return isPseudo(node) && node.value && (node.value.startsWith("::") || node.value.toLowerCase() === ":before" || node.value.toLowerCase() === ":after");
  42564. }
  42565. function isPseudoClass(node) {
  42566. return isPseudo(node) && !isPseudoElement(node);
  42567. }
  42568. function isContainer(node) {
  42569. return !!(isNode(node) && node.walk);
  42570. }
  42571. function isNamespace(node) {
  42572. return isAttribute(node) || isTag(node);
  42573. }
  42574. });
  42575. var selectors = createCommonjsModule(function (module, exports) {
  42576. exports.__esModule = true;
  42577. Object.keys(types$1).forEach(function (key) {
  42578. if (key === "default" || key === "__esModule") return;
  42579. if (key in exports && exports[key] === types$1[key]) return;
  42580. exports[key] = types$1[key];
  42581. });
  42582. Object.keys(constructors).forEach(function (key) {
  42583. if (key === "default" || key === "__esModule") return;
  42584. if (key in exports && exports[key] === constructors[key]) return;
  42585. exports[key] = constructors[key];
  42586. });
  42587. Object.keys(guards).forEach(function (key) {
  42588. if (key === "default" || key === "__esModule") return;
  42589. if (key in exports && exports[key] === guards[key]) return;
  42590. exports[key] = guards[key];
  42591. });
  42592. });
  42593. var dist = createCommonjsModule(function (module, exports) {
  42594. exports.__esModule = true;
  42595. exports["default"] = void 0;
  42596. var _processor = _interopRequireDefault(processor$1);
  42597. var selectors$1 = _interopRequireWildcard(selectors);
  42598. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
  42599. 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; }
  42600. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  42601. var parser = function parser(processor) {
  42602. return new _processor["default"](processor);
  42603. };
  42604. Object.assign(parser, selectors$1);
  42605. delete parser.__esModule;
  42606. var _default = parser;
  42607. exports["default"] = _default;
  42608. module.exports = exports.default;
  42609. });
  42610. var selectorParser = /*@__PURE__*/getDefaultExportFromCjs(dist);
  42611. const animationNameRE = /^(-\w+-)?animation-name$/;
  42612. const animationRE = /^(-\w+-)?animation$/;
  42613. const scopedPlugin = (id = '') => {
  42614. const keyframes = Object.create(null);
  42615. const shortId = id.replace(/^data-v-/, '');
  42616. return {
  42617. postcssPlugin: 'vue-sfc-scoped',
  42618. Rule(rule) {
  42619. processRule(id, rule);
  42620. },
  42621. AtRule(node) {
  42622. if (/-?keyframes$/.test(node.name) &&
  42623. !node.params.endsWith(`-${shortId}`)) {
  42624. // register keyframes
  42625. keyframes[node.params] = node.params = node.params + '-' + shortId;
  42626. }
  42627. },
  42628. OnceExit(root) {
  42629. if (Object.keys(keyframes).length) {
  42630. // If keyframes are found in this <style>, find and rewrite animation names
  42631. // in declarations.
  42632. // Caveat: this only works for keyframes and animation rules in the same
  42633. // <style> element.
  42634. // individual animation-name declaration
  42635. root.walkDecls(decl => {
  42636. if (animationNameRE.test(decl.prop)) {
  42637. decl.value = decl.value
  42638. .split(',')
  42639. .map(v => keyframes[v.trim()] || v.trim())
  42640. .join(',');
  42641. }
  42642. // shorthand
  42643. if (animationRE.test(decl.prop)) {
  42644. decl.value = decl.value
  42645. .split(',')
  42646. .map(v => {
  42647. const vals = v.trim().split(/\s+/);
  42648. const i = vals.findIndex(val => keyframes[val]);
  42649. if (i !== -1) {
  42650. vals.splice(i, 1, keyframes[vals[i]]);
  42651. return vals.join(' ');
  42652. }
  42653. else {
  42654. return v;
  42655. }
  42656. })
  42657. .join(',');
  42658. }
  42659. });
  42660. }
  42661. }
  42662. };
  42663. };
  42664. const processedRules = new WeakSet();
  42665. function processRule(id, rule) {
  42666. if (processedRules.has(rule) ||
  42667. (rule.parent &&
  42668. rule.parent.type === 'atrule' &&
  42669. /-?keyframes$/.test(rule.parent.name))) {
  42670. return;
  42671. }
  42672. processedRules.add(rule);
  42673. rule.selector = selectorParser(selectorRoot => {
  42674. selectorRoot.each(selector => {
  42675. rewriteSelector(id, selector, selectorRoot);
  42676. });
  42677. }).processSync(rule.selector);
  42678. }
  42679. function rewriteSelector(id, selector, selectorRoot, slotted = false) {
  42680. let node = null;
  42681. let shouldInject = true;
  42682. // find the last child node to insert attribute selector
  42683. selector.each(n => {
  42684. // DEPRECATED ">>>" and "/deep/" combinator
  42685. if (n.type === 'combinator' &&
  42686. (n.value === '>>>' || n.value === '/deep/')) {
  42687. n.value = ' ';
  42688. n.spaces.before = n.spaces.after = '';
  42689. warn(`the >>> and /deep/ combinators have been deprecated. ` +
  42690. `Use :deep() instead.`);
  42691. return false;
  42692. }
  42693. if (n.type === 'pseudo') {
  42694. const { value } = n;
  42695. // deep: inject [id] attribute at the node before the ::v-deep
  42696. // combinator.
  42697. if (value === ':deep' || value === '::v-deep') {
  42698. if (n.nodes.length) {
  42699. // .foo ::v-deep(.bar) -> .foo[xxxxxxx] .bar
  42700. // replace the current node with ::v-deep's inner selector
  42701. let last = n;
  42702. n.nodes[0].each(ss => {
  42703. selector.insertAfter(last, ss);
  42704. last = ss;
  42705. });
  42706. // insert a space combinator before if it doesn't already have one
  42707. const prev = selector.at(selector.index(n) - 1);
  42708. if (!prev || !isSpaceCombinator(prev)) {
  42709. selector.insertAfter(n, selectorParser.combinator({
  42710. value: ' '
  42711. }));
  42712. }
  42713. selector.removeChild(n);
  42714. }
  42715. else {
  42716. // DEPRECATED usage
  42717. // .foo ::v-deep .bar -> .foo[xxxxxxx] .bar
  42718. warn(`::v-deep usage as a combinator has ` +
  42719. `been deprecated. Use :deep(<inner-selector>) instead.`);
  42720. const prev = selector.at(selector.index(n) - 1);
  42721. if (prev && isSpaceCombinator(prev)) {
  42722. selector.removeChild(prev);
  42723. }
  42724. selector.removeChild(n);
  42725. }
  42726. return false;
  42727. }
  42728. // slot: use selector inside `::v-slotted` and inject [id + '-s']
  42729. // instead.
  42730. // ::v-slotted(.foo) -> .foo[xxxxxxx-s]
  42731. if (value === ':slotted' || value === '::v-slotted') {
  42732. rewriteSelector(id, n.nodes[0], selectorRoot, true /* slotted */);
  42733. let last = n;
  42734. n.nodes[0].each(ss => {
  42735. selector.insertAfter(last, ss);
  42736. last = ss;
  42737. });
  42738. // selector.insertAfter(n, n.nodes[0])
  42739. selector.removeChild(n);
  42740. // since slotted attribute already scopes the selector there's no
  42741. // need for the non-slot attribute.
  42742. shouldInject = false;
  42743. return false;
  42744. }
  42745. // global: replace with inner selector and do not inject [id].
  42746. // ::v-global(.foo) -> .foo
  42747. if (value === ':global' || value === '::v-global') {
  42748. selectorRoot.insertAfter(selector, n.nodes[0]);
  42749. selectorRoot.removeChild(selector);
  42750. return false;
  42751. }
  42752. }
  42753. if (n.type !== 'pseudo' && n.type !== 'combinator') {
  42754. node = n;
  42755. }
  42756. });
  42757. if (node) {
  42758. node.spaces.after = '';
  42759. }
  42760. else {
  42761. // For deep selectors & standalone pseudo selectors,
  42762. // the attribute selectors are prepended rather than appended.
  42763. // So all leading spaces must be eliminated to avoid problems.
  42764. selector.first.spaces.before = '';
  42765. }
  42766. if (shouldInject) {
  42767. const idToAdd = slotted ? id + '-s' : id;
  42768. selector.insertAfter(
  42769. // If node is null it means we need to inject [id] at the start
  42770. // insertAfter can handle `null` here
  42771. node, selectorParser.attribute({
  42772. attribute: idToAdd,
  42773. value: idToAdd,
  42774. raws: {},
  42775. quoteMark: `"`
  42776. }));
  42777. }
  42778. }
  42779. function isSpaceCombinator(node) {
  42780. return node.type === 'combinator' && /^\s+$/.test(node.value);
  42781. }
  42782. scopedPlugin.postcss = true;
  42783. var SourceMapConsumer$7 = sourceMap.SourceMapConsumer;
  42784. var SourceMapGenerator$9 = sourceMap.SourceMapGenerator;
  42785. var mergeSourceMap = merge$1;
  42786. /**
  42787. * Merge old source map and new source map and return merged.
  42788. * If old or new source map value is falsy, return another one as it is.
  42789. *
  42790. * @param {object|string} [oldMap] old source map object
  42791. * @param {object|string} [newmap] new source map object
  42792. * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
  42793. */
  42794. function merge$1(oldMap, newMap) {
  42795. if (!oldMap) return newMap
  42796. if (!newMap) return oldMap
  42797. var oldMapConsumer = new SourceMapConsumer$7(oldMap);
  42798. var newMapConsumer = new SourceMapConsumer$7(newMap);
  42799. var mergedMapGenerator = new SourceMapGenerator$9();
  42800. // iterate on new map and overwrite original position of new map with one of old map
  42801. newMapConsumer.eachMapping(function(m) {
  42802. // pass when `originalLine` is null.
  42803. // It occurs in case that the node does not have origin in original code.
  42804. if (m.originalLine == null) return
  42805. var origPosInOldMap = oldMapConsumer.originalPositionFor({
  42806. line: m.originalLine,
  42807. column: m.originalColumn
  42808. });
  42809. if (origPosInOldMap.source == null) return
  42810. mergedMapGenerator.addMapping({
  42811. original: {
  42812. line: origPosInOldMap.line,
  42813. column: origPosInOldMap.column
  42814. },
  42815. generated: {
  42816. line: m.generatedLine,
  42817. column: m.generatedColumn
  42818. },
  42819. source: origPosInOldMap.source,
  42820. name: origPosInOldMap.name
  42821. });
  42822. });
  42823. var consumers = [oldMapConsumer, newMapConsumer];
  42824. consumers.forEach(function(consumer) {
  42825. consumer.sources.forEach(function(sourceFile) {
  42826. mergedMapGenerator._sources.add(sourceFile);
  42827. var sourceContent = consumer.sourceContentFor(sourceFile);
  42828. if (sourceContent != null) {
  42829. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  42830. }
  42831. });
  42832. });
  42833. mergedMapGenerator._sourceRoot = oldMap.sourceRoot;
  42834. mergedMapGenerator._file = oldMap.file;
  42835. return JSON.parse(mergedMapGenerator.toString())
  42836. }
  42837. // .scss/.sass processor
  42838. const scss = (source, map, options, load = require) => {
  42839. const nodeSass = load('sass');
  42840. const finalOptions = Object.assign(Object.assign({}, options), { data: getSource(source, options.filename, options.additionalData), file: options.filename, outFile: options.filename, sourceMap: !!map });
  42841. try {
  42842. const result = nodeSass.renderSync(finalOptions);
  42843. const dependencies = result.stats.includedFiles;
  42844. if (map) {
  42845. return {
  42846. code: result.css.toString(),
  42847. map: mergeSourceMap(map, JSON.parse(result.map.toString())),
  42848. errors: [],
  42849. dependencies
  42850. };
  42851. }
  42852. return { code: result.css.toString(), errors: [], dependencies };
  42853. }
  42854. catch (e) {
  42855. return { code: '', errors: [e], dependencies: [] };
  42856. }
  42857. };
  42858. const sass = (source, map, options, load) => scss(source, map, Object.assign(Object.assign({}, options), { indentedSyntax: true }), load);
  42859. // .less
  42860. const less = (source, map, options, load = require) => {
  42861. const nodeLess = load('less');
  42862. let result;
  42863. let error = null;
  42864. nodeLess.render(getSource(source, options.filename, options.additionalData), Object.assign(Object.assign({}, options), { syncImport: true }), (err, output) => {
  42865. error = err;
  42866. result = output;
  42867. });
  42868. if (error)
  42869. return { code: '', errors: [error], dependencies: [] };
  42870. const dependencies = result.imports;
  42871. if (map) {
  42872. return {
  42873. code: result.css.toString(),
  42874. map: mergeSourceMap(map, result.map),
  42875. errors: [],
  42876. dependencies: dependencies
  42877. };
  42878. }
  42879. return {
  42880. code: result.css.toString(),
  42881. errors: [],
  42882. dependencies: dependencies
  42883. };
  42884. };
  42885. // .styl
  42886. const styl = (source, map, options, load = require) => {
  42887. const nodeStylus = load('stylus');
  42888. try {
  42889. const ref = nodeStylus(source);
  42890. Object.keys(options).forEach(key => ref.set(key, options[key]));
  42891. if (map)
  42892. ref.set('sourcemap', { inline: false, comment: false });
  42893. const result = ref.render();
  42894. const dependencies = ref.deps();
  42895. if (map) {
  42896. return {
  42897. code: result,
  42898. map: mergeSourceMap(map, ref.sourcemap),
  42899. errors: [],
  42900. dependencies
  42901. };
  42902. }
  42903. return { code: result, errors: [], dependencies };
  42904. }
  42905. catch (e) {
  42906. return { code: '', errors: [e], dependencies: [] };
  42907. }
  42908. };
  42909. function getSource(source, filename, additionalData) {
  42910. if (!additionalData)
  42911. return source;
  42912. if (isFunction(additionalData)) {
  42913. return additionalData(source, filename);
  42914. }
  42915. return additionalData + source;
  42916. }
  42917. const processors = {
  42918. less,
  42919. sass,
  42920. scss,
  42921. styl,
  42922. stylus: styl
  42923. };
  42924. function compileStyle(options) {
  42925. return doCompileStyle(Object.assign(Object.assign({}, options), { isAsync: false }));
  42926. }
  42927. function compileStyleAsync(options) {
  42928. return doCompileStyle(Object.assign(Object.assign({}, options), { isAsync: true }));
  42929. }
  42930. function doCompileStyle(options) {
  42931. const { filename, id, scoped = false, trim = true, isProd = false, modules = false, modulesOptions = {}, preprocessLang, postcssOptions, postcssPlugins } = options;
  42932. const preprocessor = preprocessLang && processors[preprocessLang];
  42933. const preProcessedSource = preprocessor && preprocess$1(options, preprocessor);
  42934. const map = preProcessedSource
  42935. ? preProcessedSource.map
  42936. : options.inMap || options.map;
  42937. const source = preProcessedSource ? preProcessedSource.code : options.source;
  42938. const shortId = id.replace(/^data-v-/, '');
  42939. const longId = `data-v-${shortId}`;
  42940. const plugins = (postcssPlugins || []).slice();
  42941. plugins.unshift(cssVarsPlugin({ id: shortId, isProd }));
  42942. if (trim) {
  42943. plugins.push(trimPlugin());
  42944. }
  42945. if (scoped) {
  42946. plugins.push(scopedPlugin(longId));
  42947. }
  42948. let cssModules;
  42949. if (modules) {
  42950. {
  42951. throw new Error('[@vue/compiler-sfc] `modules` option is not supported in the browser build.');
  42952. }
  42953. }
  42954. const postCSSOptions = Object.assign(Object.assign({}, postcssOptions), { to: filename, from: filename });
  42955. if (map) {
  42956. postCSSOptions.map = {
  42957. inline: false,
  42958. annotation: false,
  42959. prev: map
  42960. };
  42961. }
  42962. let result;
  42963. let code;
  42964. let outMap;
  42965. // stylus output include plain css. so need remove the repeat item
  42966. const dependencies = new Set(preProcessedSource ? preProcessedSource.dependencies : []);
  42967. // sass has filename self when provided filename option
  42968. dependencies.delete(filename);
  42969. const errors = [];
  42970. if (preProcessedSource && preProcessedSource.errors.length) {
  42971. errors.push(...preProcessedSource.errors);
  42972. }
  42973. const recordPlainCssDependencies = (messages) => {
  42974. messages.forEach(msg => {
  42975. if (msg.type === 'dependency') {
  42976. // postcss output path is absolute position path
  42977. dependencies.add(msg.file);
  42978. }
  42979. });
  42980. return dependencies;
  42981. };
  42982. try {
  42983. result = postcss_1(plugins).process(source, postCSSOptions);
  42984. // In async mode, return a promise.
  42985. if (options.isAsync) {
  42986. return result
  42987. .then(result => ({
  42988. code: result.css || '',
  42989. map: result.map && result.map.toJSON(),
  42990. errors,
  42991. modules: cssModules,
  42992. rawResult: result,
  42993. dependencies: recordPlainCssDependencies(result.messages)
  42994. }))
  42995. .catch(error => ({
  42996. code: '',
  42997. map: undefined,
  42998. errors: [...errors, error],
  42999. rawResult: undefined,
  43000. dependencies
  43001. }));
  43002. }
  43003. recordPlainCssDependencies(result.messages);
  43004. // force synchronous transform (we know we only have sync plugins)
  43005. code = result.css;
  43006. outMap = result.map;
  43007. }
  43008. catch (e) {
  43009. errors.push(e);
  43010. }
  43011. return {
  43012. code: code || ``,
  43013. map: outMap && outMap.toJSON(),
  43014. errors,
  43015. rawResult: result,
  43016. dependencies
  43017. };
  43018. }
  43019. function preprocess$1(options, preprocessor) {
  43020. if (!options.preprocessCustomRequire) {
  43021. throw new Error(`[@vue/compiler-sfc] Style preprocessing in the browser build must ` +
  43022. `provide the \`preprocessCustomRequire\` option to return the in-browser ` +
  43023. `version of the preprocessor.`);
  43024. }
  43025. return preprocessor(options.source, options.inMap || options.map, Object.assign({ filename: options.filename }, options.preprocessOptions), options.preprocessCustomRequire);
  43026. }
  43027. // API
  43028. const walk$2 = walk$1;
  43029. 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 };