compiler-dom.esm-browser.js 216 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552
  1. /**
  2. * Make a map and return a function for checking if a key
  3. * is in that map.
  4. * IMPORTANT: all calls of this function must be prefixed with
  5. * \/\*#\_\_PURE\_\_\*\/
  6. * So that rollup can tree-shake them if necessary.
  7. */
  8. function makeMap(str, expectsLowerCase) {
  9. const map = Object.create(null);
  10. const list = str.split(',');
  11. for (let i = 0; i < list.length; i++) {
  12. map[list[i]] = true;
  13. }
  14. return expectsLowerCase ? val => !!map[val.toLowerCase()] : val => !!map[val];
  15. }
  16. /**
  17. * dev only flag -> name mapping
  18. */
  19. const PatchFlagNames = {
  20. [1 /* PatchFlags.TEXT */]: `TEXT`,
  21. [2 /* PatchFlags.CLASS */]: `CLASS`,
  22. [4 /* PatchFlags.STYLE */]: `STYLE`,
  23. [8 /* PatchFlags.PROPS */]: `PROPS`,
  24. [16 /* PatchFlags.FULL_PROPS */]: `FULL_PROPS`,
  25. [32 /* PatchFlags.HYDRATE_EVENTS */]: `HYDRATE_EVENTS`,
  26. [64 /* PatchFlags.STABLE_FRAGMENT */]: `STABLE_FRAGMENT`,
  27. [128 /* PatchFlags.KEYED_FRAGMENT */]: `KEYED_FRAGMENT`,
  28. [256 /* PatchFlags.UNKEYED_FRAGMENT */]: `UNKEYED_FRAGMENT`,
  29. [512 /* PatchFlags.NEED_PATCH */]: `NEED_PATCH`,
  30. [1024 /* PatchFlags.DYNAMIC_SLOTS */]: `DYNAMIC_SLOTS`,
  31. [2048 /* PatchFlags.DEV_ROOT_FRAGMENT */]: `DEV_ROOT_FRAGMENT`,
  32. [-1 /* PatchFlags.HOISTED */]: `HOISTED`,
  33. [-2 /* PatchFlags.BAIL */]: `BAIL`
  34. };
  35. /**
  36. * Dev only
  37. */
  38. const slotFlagsText = {
  39. [1 /* SlotFlags.STABLE */]: 'STABLE',
  40. [2 /* SlotFlags.DYNAMIC */]: 'DYNAMIC',
  41. [3 /* SlotFlags.FORWARDED */]: 'FORWARDED'
  42. };
  43. const range = 2;
  44. function generateCodeFrame(source, start = 0, end = source.length) {
  45. // Split the content into individual lines but capture the newline sequence
  46. // that separated each line. This is important because the actual sequence is
  47. // needed to properly take into account the full line length for offset
  48. // comparison
  49. let lines = source.split(/(\r?\n)/);
  50. // Separate the lines and newline sequences into separate arrays for easier referencing
  51. const newlineSequences = lines.filter((_, idx) => idx % 2 === 1);
  52. lines = lines.filter((_, idx) => idx % 2 === 0);
  53. let count = 0;
  54. const res = [];
  55. for (let i = 0; i < lines.length; i++) {
  56. count +=
  57. lines[i].length +
  58. ((newlineSequences[i] && newlineSequences[i].length) || 0);
  59. if (count >= start) {
  60. for (let j = i - range; j <= i + range || end > count; j++) {
  61. if (j < 0 || j >= lines.length)
  62. continue;
  63. const line = j + 1;
  64. res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
  65. const lineLength = lines[j].length;
  66. const newLineSeqLength = (newlineSequences[j] && newlineSequences[j].length) || 0;
  67. if (j === i) {
  68. // push underline
  69. const pad = start - (count - (lineLength + newLineSeqLength));
  70. const length = Math.max(1, end > count ? lineLength - pad : end - start);
  71. res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
  72. }
  73. else if (j > i) {
  74. if (end > count) {
  75. const length = Math.max(Math.min(end - count, lineLength), 1);
  76. res.push(` | ` + '^'.repeat(length));
  77. }
  78. count += lineLength + newLineSeqLength;
  79. }
  80. }
  81. break;
  82. }
  83. }
  84. return res.join('\n');
  85. }
  86. const listDelimiterRE = /;(?![^(]*\))/g;
  87. const propertyDelimiterRE = /:([^]+)/;
  88. const styleCommentRE = /\/\*.*?\*\//gs;
  89. function parseStringStyle(cssText) {
  90. const ret = {};
  91. cssText
  92. .replace(styleCommentRE, '')
  93. .split(listDelimiterRE)
  94. .forEach(item => {
  95. if (item) {
  96. const tmp = item.split(propertyDelimiterRE);
  97. tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
  98. }
  99. });
  100. return ret;
  101. }
  102. // These tag configs are shared between compiler-dom and runtime-dom, so they
  103. // https://developer.mozilla.org/en-US/docs/Web/HTML/Element
  104. const HTML_TAGS = 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +
  105. 'header,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,' +
  106. 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +
  107. 'data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,' +
  108. 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +
  109. 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +
  110. 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +
  111. 'option,output,progress,select,textarea,details,dialog,menu,' +
  112. 'summary,template,blockquote,iframe,tfoot';
  113. // https://developer.mozilla.org/en-US/docs/Web/SVG/Element
  114. const SVG_TAGS = 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +
  115. 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +
  116. 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +
  117. 'feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +
  118. 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +
  119. 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +
  120. 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +
  121. 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +
  122. 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +
  123. 'text,textPath,title,tspan,unknown,use,view';
  124. const VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';
  125. /**
  126. * Compiler only.
  127. * Do NOT use in runtime code paths unless behind `true` flag.
  128. */
  129. const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
  130. /**
  131. * Compiler only.
  132. * Do NOT use in runtime code paths unless behind `true` flag.
  133. */
  134. const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
  135. /**
  136. * Compiler only.
  137. * Do NOT use in runtime code paths unless behind `true` flag.
  138. */
  139. const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
  140. const EMPTY_OBJ = Object.freeze({})
  141. ;
  142. Object.freeze([]) ;
  143. const NOOP = () => { };
  144. /**
  145. * Always return false.
  146. */
  147. const NO = () => false;
  148. const onRE = /^on[^a-z]/;
  149. const isOn = (key) => onRE.test(key);
  150. const extend = Object.assign;
  151. const isArray = Array.isArray;
  152. const isString = (val) => typeof val === 'string';
  153. const isSymbol = (val) => typeof val === 'symbol';
  154. const isObject = (val) => val !== null && typeof val === 'object';
  155. const isReservedProp = /*#__PURE__*/ makeMap(
  156. // the leading comma is intentional so empty string "" is also included
  157. ',key,ref,ref_for,ref_key,' +
  158. 'onVnodeBeforeMount,onVnodeMounted,' +
  159. 'onVnodeBeforeUpdate,onVnodeUpdated,' +
  160. 'onVnodeBeforeUnmount,onVnodeUnmounted');
  161. const isBuiltInDirective = /*#__PURE__*/ makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo');
  162. const cacheStringFunction = (fn) => {
  163. const cache = Object.create(null);
  164. return ((str) => {
  165. const hit = cache[str];
  166. return hit || (cache[str] = fn(str));
  167. });
  168. };
  169. const camelizeRE = /-(\w)/g;
  170. /**
  171. * @private
  172. */
  173. const camelize = cacheStringFunction((str) => {
  174. return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
  175. });
  176. const hyphenateRE = /\B([A-Z])/g;
  177. /**
  178. * @private
  179. */
  180. const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
  181. /**
  182. * @private
  183. */
  184. const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
  185. /**
  186. * @private
  187. */
  188. const toHandlerKey = cacheStringFunction((str) => str ? `on${capitalize(str)}` : ``);
  189. function defaultOnError(error) {
  190. throw error;
  191. }
  192. function defaultOnWarn(msg) {
  193. console.warn(`[Vue warn] ${msg.message}`);
  194. }
  195. function createCompilerError(code, loc, messages, additionalMessage) {
  196. const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
  197. ;
  198. const error = new SyntaxError(String(msg));
  199. error.code = code;
  200. error.loc = loc;
  201. return error;
  202. }
  203. const errorMessages = {
  204. // parse errors
  205. [0 /* ErrorCodes.ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
  206. [1 /* ErrorCodes.CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
  207. [2 /* ErrorCodes.DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
  208. [3 /* ErrorCodes.END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
  209. [4 /* ErrorCodes.END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
  210. [5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
  211. [6 /* ErrorCodes.EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
  212. [7 /* ErrorCodes.EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
  213. [8 /* ErrorCodes.EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
  214. [9 /* ErrorCodes.EOF_IN_TAG */]: 'Unexpected EOF in tag.',
  215. [10 /* ErrorCodes.INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
  216. [11 /* ErrorCodes.INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
  217. [12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
  218. [13 /* ErrorCodes.MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
  219. [14 /* ErrorCodes.MISSING_END_TAG_NAME */]: 'End tag name was expected.',
  220. [15 /* ErrorCodes.MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
  221. [16 /* ErrorCodes.NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
  222. [17 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
  223. [18 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
  224. [19 /* ErrorCodes.UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
  225. [21 /* ErrorCodes.UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
  226. [20 /* ErrorCodes.UNEXPECTED_NULL_CHARACTER */]: `Unexpected null character.`,
  227. [22 /* ErrorCodes.UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
  228. // Vue-specific parse errors
  229. [23 /* ErrorCodes.X_INVALID_END_TAG */]: 'Invalid end tag.',
  230. [24 /* ErrorCodes.X_MISSING_END_TAG */]: 'Element is missing end tag.',
  231. [25 /* ErrorCodes.X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
  232. [27 /* ErrorCodes.X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
  233. 'Note that dynamic directive argument cannot contain spaces.',
  234. [26 /* ErrorCodes.X_MISSING_DIRECTIVE_NAME */]: 'Legal directive name was expected.',
  235. // transform errors
  236. [28 /* ErrorCodes.X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
  237. [29 /* ErrorCodes.X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
  238. [30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if or v-else-if.`,
  239. [31 /* ErrorCodes.X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
  240. [32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
  241. [33 /* ErrorCodes.X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
  242. [34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
  243. [35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
  244. [36 /* ErrorCodes.X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
  245. [37 /* ErrorCodes.X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
  246. `When there are multiple named slots, all slots should use <template> ` +
  247. `syntax to avoid scope ambiguity.`,
  248. [38 /* ErrorCodes.X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
  249. [39 /* ErrorCodes.X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
  250. `default slot. These children will be ignored.`,
  251. [40 /* ErrorCodes.X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
  252. [41 /* ErrorCodes.X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
  253. [42 /* ErrorCodes.X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
  254. [43 /* ErrorCodes.X_V_MODEL_ON_SCOPE_VARIABLE */]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,
  255. [44 /* ErrorCodes.X_V_MODEL_ON_PROPS */]: `v-model cannot be used on a prop, because local prop bindings are not writable.\nUse a v-bind binding combined with a v-on listener that emits update:x event instead.`,
  256. [45 /* ErrorCodes.X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
  257. [46 /* ErrorCodes.X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
  258. // generic errors
  259. [47 /* ErrorCodes.X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
  260. [48 /* ErrorCodes.X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
  261. [49 /* ErrorCodes.X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
  262. [50 /* ErrorCodes.X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`,
  263. // just to fulfill types
  264. [51 /* ErrorCodes.__EXTEND_POINT__ */]: ``
  265. };
  266. const FRAGMENT = Symbol(`Fragment` );
  267. const TELEPORT = Symbol(`Teleport` );
  268. const SUSPENSE = Symbol(`Suspense` );
  269. const KEEP_ALIVE = Symbol(`KeepAlive` );
  270. const BASE_TRANSITION = Symbol(`BaseTransition` );
  271. const OPEN_BLOCK = Symbol(`openBlock` );
  272. const CREATE_BLOCK = Symbol(`createBlock` );
  273. const CREATE_ELEMENT_BLOCK = Symbol(`createElementBlock` );
  274. const CREATE_VNODE = Symbol(`createVNode` );
  275. const CREATE_ELEMENT_VNODE = Symbol(`createElementVNode` );
  276. const CREATE_COMMENT = Symbol(`createCommentVNode` );
  277. const CREATE_TEXT = Symbol(`createTextVNode` );
  278. const CREATE_STATIC = Symbol(`createStaticVNode` );
  279. const RESOLVE_COMPONENT = Symbol(`resolveComponent` );
  280. const RESOLVE_DYNAMIC_COMPONENT = Symbol(`resolveDynamicComponent` );
  281. const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` );
  282. const RESOLVE_FILTER = Symbol(`resolveFilter` );
  283. const WITH_DIRECTIVES = Symbol(`withDirectives` );
  284. const RENDER_LIST = Symbol(`renderList` );
  285. const RENDER_SLOT = Symbol(`renderSlot` );
  286. const CREATE_SLOTS = Symbol(`createSlots` );
  287. const TO_DISPLAY_STRING = Symbol(`toDisplayString` );
  288. const MERGE_PROPS = Symbol(`mergeProps` );
  289. const NORMALIZE_CLASS = Symbol(`normalizeClass` );
  290. const NORMALIZE_STYLE = Symbol(`normalizeStyle` );
  291. const NORMALIZE_PROPS = Symbol(`normalizeProps` );
  292. const GUARD_REACTIVE_PROPS = Symbol(`guardReactiveProps` );
  293. const TO_HANDLERS = Symbol(`toHandlers` );
  294. const CAMELIZE = Symbol(`camelize` );
  295. const CAPITALIZE = Symbol(`capitalize` );
  296. const TO_HANDLER_KEY = Symbol(`toHandlerKey` );
  297. const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` );
  298. const PUSH_SCOPE_ID = Symbol(`pushScopeId` );
  299. const POP_SCOPE_ID = Symbol(`popScopeId` );
  300. const WITH_CTX = Symbol(`withCtx` );
  301. const UNREF = Symbol(`unref` );
  302. const IS_REF = Symbol(`isRef` );
  303. const WITH_MEMO = Symbol(`withMemo` );
  304. const IS_MEMO_SAME = Symbol(`isMemoSame` );
  305. // Name mapping for runtime helpers that need to be imported from 'vue' in
  306. // generated code. Make sure these are correctly exported in the runtime!
  307. const helperNameMap = {
  308. [FRAGMENT]: `Fragment`,
  309. [TELEPORT]: `Teleport`,
  310. [SUSPENSE]: `Suspense`,
  311. [KEEP_ALIVE]: `KeepAlive`,
  312. [BASE_TRANSITION]: `BaseTransition`,
  313. [OPEN_BLOCK]: `openBlock`,
  314. [CREATE_BLOCK]: `createBlock`,
  315. [CREATE_ELEMENT_BLOCK]: `createElementBlock`,
  316. [CREATE_VNODE]: `createVNode`,
  317. [CREATE_ELEMENT_VNODE]: `createElementVNode`,
  318. [CREATE_COMMENT]: `createCommentVNode`,
  319. [CREATE_TEXT]: `createTextVNode`,
  320. [CREATE_STATIC]: `createStaticVNode`,
  321. [RESOLVE_COMPONENT]: `resolveComponent`,
  322. [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
  323. [RESOLVE_DIRECTIVE]: `resolveDirective`,
  324. [RESOLVE_FILTER]: `resolveFilter`,
  325. [WITH_DIRECTIVES]: `withDirectives`,
  326. [RENDER_LIST]: `renderList`,
  327. [RENDER_SLOT]: `renderSlot`,
  328. [CREATE_SLOTS]: `createSlots`,
  329. [TO_DISPLAY_STRING]: `toDisplayString`,
  330. [MERGE_PROPS]: `mergeProps`,
  331. [NORMALIZE_CLASS]: `normalizeClass`,
  332. [NORMALIZE_STYLE]: `normalizeStyle`,
  333. [NORMALIZE_PROPS]: `normalizeProps`,
  334. [GUARD_REACTIVE_PROPS]: `guardReactiveProps`,
  335. [TO_HANDLERS]: `toHandlers`,
  336. [CAMELIZE]: `camelize`,
  337. [CAPITALIZE]: `capitalize`,
  338. [TO_HANDLER_KEY]: `toHandlerKey`,
  339. [SET_BLOCK_TRACKING]: `setBlockTracking`,
  340. [PUSH_SCOPE_ID]: `pushScopeId`,
  341. [POP_SCOPE_ID]: `popScopeId`,
  342. [WITH_CTX]: `withCtx`,
  343. [UNREF]: `unref`,
  344. [IS_REF]: `isRef`,
  345. [WITH_MEMO]: `withMemo`,
  346. [IS_MEMO_SAME]: `isMemoSame`
  347. };
  348. function registerRuntimeHelpers(helpers) {
  349. Object.getOwnPropertySymbols(helpers).forEach(s => {
  350. helperNameMap[s] = helpers[s];
  351. });
  352. }
  353. // AST Utilities ---------------------------------------------------------------
  354. // Some expressions, e.g. sequence and conditional expressions, are never
  355. // associated with template nodes, so their source locations are just a stub.
  356. // Container types like CompoundExpression also don't need a real location.
  357. const locStub = {
  358. source: '',
  359. start: { line: 1, column: 1, offset: 0 },
  360. end: { line: 1, column: 1, offset: 0 }
  361. };
  362. function createRoot(children, loc = locStub) {
  363. return {
  364. type: 0 /* NodeTypes.ROOT */,
  365. children,
  366. helpers: [],
  367. components: [],
  368. directives: [],
  369. hoists: [],
  370. imports: [],
  371. cached: 0,
  372. temps: 0,
  373. codegenNode: undefined,
  374. loc
  375. };
  376. }
  377. function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent = false, loc = locStub) {
  378. if (context) {
  379. if (isBlock) {
  380. context.helper(OPEN_BLOCK);
  381. context.helper(getVNodeBlockHelper(context.inSSR, isComponent));
  382. }
  383. else {
  384. context.helper(getVNodeHelper(context.inSSR, isComponent));
  385. }
  386. if (directives) {
  387. context.helper(WITH_DIRECTIVES);
  388. }
  389. }
  390. return {
  391. type: 13 /* NodeTypes.VNODE_CALL */,
  392. tag,
  393. props,
  394. children,
  395. patchFlag,
  396. dynamicProps,
  397. directives,
  398. isBlock,
  399. disableTracking,
  400. isComponent,
  401. loc
  402. };
  403. }
  404. function createArrayExpression(elements, loc = locStub) {
  405. return {
  406. type: 17 /* NodeTypes.JS_ARRAY_EXPRESSION */,
  407. loc,
  408. elements
  409. };
  410. }
  411. function createObjectExpression(properties, loc = locStub) {
  412. return {
  413. type: 15 /* NodeTypes.JS_OBJECT_EXPRESSION */,
  414. loc,
  415. properties
  416. };
  417. }
  418. function createObjectProperty(key, value) {
  419. return {
  420. type: 16 /* NodeTypes.JS_PROPERTY */,
  421. loc: locStub,
  422. key: isString(key) ? createSimpleExpression(key, true) : key,
  423. value
  424. };
  425. }
  426. function createSimpleExpression(content, isStatic = false, loc = locStub, constType = 0 /* ConstantTypes.NOT_CONSTANT */) {
  427. return {
  428. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  429. loc,
  430. content,
  431. isStatic,
  432. constType: isStatic ? 3 /* ConstantTypes.CAN_STRINGIFY */ : constType
  433. };
  434. }
  435. function createInterpolation(content, loc) {
  436. return {
  437. type: 5 /* NodeTypes.INTERPOLATION */,
  438. loc,
  439. content: isString(content)
  440. ? createSimpleExpression(content, false, loc)
  441. : content
  442. };
  443. }
  444. function createCompoundExpression(children, loc = locStub) {
  445. return {
  446. type: 8 /* NodeTypes.COMPOUND_EXPRESSION */,
  447. loc,
  448. children
  449. };
  450. }
  451. function createCallExpression(callee, args = [], loc = locStub) {
  452. return {
  453. type: 14 /* NodeTypes.JS_CALL_EXPRESSION */,
  454. loc,
  455. callee,
  456. arguments: args
  457. };
  458. }
  459. function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
  460. return {
  461. type: 18 /* NodeTypes.JS_FUNCTION_EXPRESSION */,
  462. params,
  463. returns,
  464. newline,
  465. isSlot,
  466. loc
  467. };
  468. }
  469. function createConditionalExpression(test, consequent, alternate, newline = true) {
  470. return {
  471. type: 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */,
  472. test,
  473. consequent,
  474. alternate,
  475. newline,
  476. loc: locStub
  477. };
  478. }
  479. function createCacheExpression(index, value, isVNode = false) {
  480. return {
  481. type: 20 /* NodeTypes.JS_CACHE_EXPRESSION */,
  482. index,
  483. value,
  484. isVNode,
  485. loc: locStub
  486. };
  487. }
  488. function createBlockStatement(body) {
  489. return {
  490. type: 21 /* NodeTypes.JS_BLOCK_STATEMENT */,
  491. body,
  492. loc: locStub
  493. };
  494. }
  495. function createTemplateLiteral(elements) {
  496. return {
  497. type: 22 /* NodeTypes.JS_TEMPLATE_LITERAL */,
  498. elements,
  499. loc: locStub
  500. };
  501. }
  502. function createIfStatement(test, consequent, alternate) {
  503. return {
  504. type: 23 /* NodeTypes.JS_IF_STATEMENT */,
  505. test,
  506. consequent,
  507. alternate,
  508. loc: locStub
  509. };
  510. }
  511. function createAssignmentExpression(left, right) {
  512. return {
  513. type: 24 /* NodeTypes.JS_ASSIGNMENT_EXPRESSION */,
  514. left,
  515. right,
  516. loc: locStub
  517. };
  518. }
  519. function createSequenceExpression(expressions) {
  520. return {
  521. type: 25 /* NodeTypes.JS_SEQUENCE_EXPRESSION */,
  522. expressions,
  523. loc: locStub
  524. };
  525. }
  526. function createReturnStatement(returns) {
  527. return {
  528. type: 26 /* NodeTypes.JS_RETURN_STATEMENT */,
  529. returns,
  530. loc: locStub
  531. };
  532. }
  533. const isStaticExp = (p) => p.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && p.isStatic;
  534. const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
  535. function isCoreComponent(tag) {
  536. if (isBuiltInType(tag, 'Teleport')) {
  537. return TELEPORT;
  538. }
  539. else if (isBuiltInType(tag, 'Suspense')) {
  540. return SUSPENSE;
  541. }
  542. else if (isBuiltInType(tag, 'KeepAlive')) {
  543. return KEEP_ALIVE;
  544. }
  545. else if (isBuiltInType(tag, 'BaseTransition')) {
  546. return BASE_TRANSITION;
  547. }
  548. }
  549. const nonIdentifierRE = /^\d|[^\$\w]/;
  550. const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
  551. const validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/;
  552. const validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/;
  553. const whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g;
  554. /**
  555. * Simple lexer to check if an expression is a member expression. This is
  556. * lax and only checks validity at the root level (i.e. does not validate exps
  557. * inside square brackets), but it's ok since these are only used on template
  558. * expressions and false positives are invalid expressions in the first place.
  559. */
  560. const isMemberExpressionBrowser = (path) => {
  561. // remove whitespaces around . or [ first
  562. path = path.trim().replace(whitespaceRE, s => s.trim());
  563. let state = 0 /* MemberExpLexState.inMemberExp */;
  564. let stateStack = [];
  565. let currentOpenBracketCount = 0;
  566. let currentOpenParensCount = 0;
  567. let currentStringType = null;
  568. for (let i = 0; i < path.length; i++) {
  569. const char = path.charAt(i);
  570. switch (state) {
  571. case 0 /* MemberExpLexState.inMemberExp */:
  572. if (char === '[') {
  573. stateStack.push(state);
  574. state = 1 /* MemberExpLexState.inBrackets */;
  575. currentOpenBracketCount++;
  576. }
  577. else if (char === '(') {
  578. stateStack.push(state);
  579. state = 2 /* MemberExpLexState.inParens */;
  580. currentOpenParensCount++;
  581. }
  582. else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) {
  583. return false;
  584. }
  585. break;
  586. case 1 /* MemberExpLexState.inBrackets */:
  587. if (char === `'` || char === `"` || char === '`') {
  588. stateStack.push(state);
  589. state = 3 /* MemberExpLexState.inString */;
  590. currentStringType = char;
  591. }
  592. else if (char === `[`) {
  593. currentOpenBracketCount++;
  594. }
  595. else if (char === `]`) {
  596. if (!--currentOpenBracketCount) {
  597. state = stateStack.pop();
  598. }
  599. }
  600. break;
  601. case 2 /* MemberExpLexState.inParens */:
  602. if (char === `'` || char === `"` || char === '`') {
  603. stateStack.push(state);
  604. state = 3 /* MemberExpLexState.inString */;
  605. currentStringType = char;
  606. }
  607. else if (char === `(`) {
  608. currentOpenParensCount++;
  609. }
  610. else if (char === `)`) {
  611. // if the exp ends as a call then it should not be considered valid
  612. if (i === path.length - 1) {
  613. return false;
  614. }
  615. if (!--currentOpenParensCount) {
  616. state = stateStack.pop();
  617. }
  618. }
  619. break;
  620. case 3 /* MemberExpLexState.inString */:
  621. if (char === currentStringType) {
  622. state = stateStack.pop();
  623. currentStringType = null;
  624. }
  625. break;
  626. }
  627. }
  628. return !currentOpenBracketCount && !currentOpenParensCount;
  629. };
  630. const isMemberExpressionNode = NOOP
  631. ;
  632. const isMemberExpression = isMemberExpressionBrowser
  633. ;
  634. function getInnerRange(loc, offset, length) {
  635. const source = loc.source.slice(offset, offset + length);
  636. const newLoc = {
  637. source,
  638. start: advancePositionWithClone(loc.start, loc.source, offset),
  639. end: loc.end
  640. };
  641. if (length != null) {
  642. newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
  643. }
  644. return newLoc;
  645. }
  646. function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
  647. return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
  648. }
  649. // advance by mutation without cloning (for performance reasons), since this
  650. // gets called a lot in the parser
  651. function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
  652. let linesCount = 0;
  653. let lastNewLinePos = -1;
  654. for (let i = 0; i < numberOfCharacters; i++) {
  655. if (source.charCodeAt(i) === 10 /* newline char code */) {
  656. linesCount++;
  657. lastNewLinePos = i;
  658. }
  659. }
  660. pos.offset += numberOfCharacters;
  661. pos.line += linesCount;
  662. pos.column =
  663. lastNewLinePos === -1
  664. ? pos.column + numberOfCharacters
  665. : numberOfCharacters - lastNewLinePos;
  666. return pos;
  667. }
  668. function assert(condition, msg) {
  669. /* istanbul ignore if */
  670. if (!condition) {
  671. throw new Error(msg || `unexpected compiler condition`);
  672. }
  673. }
  674. function findDir(node, name, allowEmpty = false) {
  675. for (let i = 0; i < node.props.length; i++) {
  676. const p = node.props[i];
  677. if (p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  678. (allowEmpty || p.exp) &&
  679. (isString(name) ? p.name === name : name.test(p.name))) {
  680. return p;
  681. }
  682. }
  683. }
  684. function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
  685. for (let i = 0; i < node.props.length; i++) {
  686. const p = node.props[i];
  687. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  688. if (dynamicOnly)
  689. continue;
  690. if (p.name === name && (p.value || allowEmpty)) {
  691. return p;
  692. }
  693. }
  694. else if (p.name === 'bind' &&
  695. (p.exp || allowEmpty) &&
  696. isStaticArgOf(p.arg, name)) {
  697. return p;
  698. }
  699. }
  700. }
  701. function isStaticArgOf(arg, name) {
  702. return !!(arg && isStaticExp(arg) && arg.content === name);
  703. }
  704. function hasDynamicKeyVBind(node) {
  705. return node.props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  706. p.name === 'bind' &&
  707. (!p.arg || // v-bind="obj"
  708. p.arg.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
  709. !p.arg.isStatic) // v-bind:[foo]
  710. );
  711. }
  712. function isText(node) {
  713. return node.type === 5 /* NodeTypes.INTERPOLATION */ || node.type === 2 /* NodeTypes.TEXT */;
  714. }
  715. function isVSlot(p) {
  716. return p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'slot';
  717. }
  718. function isTemplateNode(node) {
  719. return (node.type === 1 /* NodeTypes.ELEMENT */ && node.tagType === 3 /* ElementTypes.TEMPLATE */);
  720. }
  721. function isSlotOutlet(node) {
  722. return node.type === 1 /* NodeTypes.ELEMENT */ && node.tagType === 2 /* ElementTypes.SLOT */;
  723. }
  724. function getVNodeHelper(ssr, isComponent) {
  725. return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE;
  726. }
  727. function getVNodeBlockHelper(ssr, isComponent) {
  728. return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK;
  729. }
  730. const propsHelperSet = new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]);
  731. function getUnnormalizedProps(props, callPath = []) {
  732. if (props &&
  733. !isString(props) &&
  734. props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  735. const callee = props.callee;
  736. if (!isString(callee) && propsHelperSet.has(callee)) {
  737. return getUnnormalizedProps(props.arguments[0], callPath.concat(props));
  738. }
  739. }
  740. return [props, callPath];
  741. }
  742. function injectProp(node, prop, context) {
  743. let propsWithInjection;
  744. /**
  745. * 1. mergeProps(...)
  746. * 2. toHandlers(...)
  747. * 3. normalizeProps(...)
  748. * 4. normalizeProps(guardReactiveProps(...))
  749. *
  750. * we need to get the real props before normalization
  751. */
  752. let props = node.type === 13 /* NodeTypes.VNODE_CALL */ ? node.props : node.arguments[2];
  753. let callPath = [];
  754. let parentCall;
  755. if (props &&
  756. !isString(props) &&
  757. props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  758. const ret = getUnnormalizedProps(props);
  759. props = ret[0];
  760. callPath = ret[1];
  761. parentCall = callPath[callPath.length - 1];
  762. }
  763. if (props == null || isString(props)) {
  764. propsWithInjection = createObjectExpression([prop]);
  765. }
  766. else if (props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  767. // merged props... add ours
  768. // only inject key to object literal if it's the first argument so that
  769. // if doesn't override user provided keys
  770. const first = props.arguments[0];
  771. if (!isString(first) && first.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
  772. // #6631
  773. if (!hasProp(prop, first)) {
  774. first.properties.unshift(prop);
  775. }
  776. }
  777. else {
  778. if (props.callee === TO_HANDLERS) {
  779. // #2366
  780. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  781. createObjectExpression([prop]),
  782. props
  783. ]);
  784. }
  785. else {
  786. props.arguments.unshift(createObjectExpression([prop]));
  787. }
  788. }
  789. !propsWithInjection && (propsWithInjection = props);
  790. }
  791. else if (props.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
  792. if (!hasProp(prop, props)) {
  793. props.properties.unshift(prop);
  794. }
  795. propsWithInjection = props;
  796. }
  797. else {
  798. // single v-bind with expression, return a merged replacement
  799. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  800. createObjectExpression([prop]),
  801. props
  802. ]);
  803. // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(props))`,
  804. // it will be rewritten as `normalizeProps(mergeProps({ key: 0 }, props))`,
  805. // the `guardReactiveProps` will no longer be needed
  806. if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) {
  807. parentCall = callPath[callPath.length - 2];
  808. }
  809. }
  810. if (node.type === 13 /* NodeTypes.VNODE_CALL */) {
  811. if (parentCall) {
  812. parentCall.arguments[0] = propsWithInjection;
  813. }
  814. else {
  815. node.props = propsWithInjection;
  816. }
  817. }
  818. else {
  819. if (parentCall) {
  820. parentCall.arguments[0] = propsWithInjection;
  821. }
  822. else {
  823. node.arguments[2] = propsWithInjection;
  824. }
  825. }
  826. }
  827. // check existing key to avoid overriding user provided keys
  828. function hasProp(prop, props) {
  829. let result = false;
  830. if (prop.key.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  831. const propKeyName = prop.key.content;
  832. result = props.properties.some(p => p.key.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  833. p.key.content === propKeyName);
  834. }
  835. return result;
  836. }
  837. function toValidAssetId(name, type) {
  838. // see issue#4422, we need adding identifier on validAssetId if variable `name` has specific character
  839. return `_${type}_${name.replace(/[^\w]/g, (searchValue, replaceValue) => {
  840. return searchValue === '-' ? '_' : name.charCodeAt(replaceValue).toString();
  841. })}`;
  842. }
  843. // Check if a node contains expressions that reference current context scope ids
  844. function hasScopeRef(node, ids) {
  845. if (!node || Object.keys(ids).length === 0) {
  846. return false;
  847. }
  848. switch (node.type) {
  849. case 1 /* NodeTypes.ELEMENT */:
  850. for (let i = 0; i < node.props.length; i++) {
  851. const p = node.props[i];
  852. if (p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  853. (hasScopeRef(p.arg, ids) || hasScopeRef(p.exp, ids))) {
  854. return true;
  855. }
  856. }
  857. return node.children.some(c => hasScopeRef(c, ids));
  858. case 11 /* NodeTypes.FOR */:
  859. if (hasScopeRef(node.source, ids)) {
  860. return true;
  861. }
  862. return node.children.some(c => hasScopeRef(c, ids));
  863. case 9 /* NodeTypes.IF */:
  864. return node.branches.some(b => hasScopeRef(b, ids));
  865. case 10 /* NodeTypes.IF_BRANCH */:
  866. if (hasScopeRef(node.condition, ids)) {
  867. return true;
  868. }
  869. return node.children.some(c => hasScopeRef(c, ids));
  870. case 4 /* NodeTypes.SIMPLE_EXPRESSION */:
  871. return (!node.isStatic &&
  872. isSimpleIdentifier(node.content) &&
  873. !!ids[node.content]);
  874. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  875. return node.children.some(c => isObject(c) && hasScopeRef(c, ids));
  876. case 5 /* NodeTypes.INTERPOLATION */:
  877. case 12 /* NodeTypes.TEXT_CALL */:
  878. return hasScopeRef(node.content, ids);
  879. case 2 /* NodeTypes.TEXT */:
  880. case 3 /* NodeTypes.COMMENT */:
  881. return false;
  882. default:
  883. return false;
  884. }
  885. }
  886. function getMemoedVNodeCall(node) {
  887. if (node.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */ && node.callee === WITH_MEMO) {
  888. return node.arguments[1].returns;
  889. }
  890. else {
  891. return node;
  892. }
  893. }
  894. function makeBlock(node, { helper, removeHelper, inSSR }) {
  895. if (!node.isBlock) {
  896. node.isBlock = true;
  897. removeHelper(getVNodeHelper(inSSR, node.isComponent));
  898. helper(OPEN_BLOCK);
  899. helper(getVNodeBlockHelper(inSSR, node.isComponent));
  900. }
  901. }
  902. const deprecationData = {
  903. ["COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */]: {
  904. message: `Platform-native elements with "is" prop will no longer be ` +
  905. `treated as components in Vue 3 unless the "is" value is explicitly ` +
  906. `prefixed with "vue:".`,
  907. link: `https://v3-migration.vuejs.org/breaking-changes/custom-elements-interop.html`
  908. },
  909. ["COMPILER_V_BIND_SYNC" /* CompilerDeprecationTypes.COMPILER_V_BIND_SYNC */]: {
  910. message: key => `.sync modifier for v-bind has been removed. Use v-model with ` +
  911. `argument instead. \`v-bind:${key}.sync\` should be changed to ` +
  912. `\`v-model:${key}\`.`,
  913. link: `https://v3-migration.vuejs.org/breaking-changes/v-model.html`
  914. },
  915. ["COMPILER_V_BIND_PROP" /* CompilerDeprecationTypes.COMPILER_V_BIND_PROP */]: {
  916. message: `.prop modifier for v-bind has been removed and no longer necessary. ` +
  917. `Vue 3 will automatically set a binding as DOM property when appropriate.`
  918. },
  919. ["COMPILER_V_BIND_OBJECT_ORDER" /* CompilerDeprecationTypes.COMPILER_V_BIND_OBJECT_ORDER */]: {
  920. message: `v-bind="obj" usage is now order sensitive and behaves like JavaScript ` +
  921. `object spread: it will now overwrite an existing non-mergeable attribute ` +
  922. `that appears before v-bind in the case of conflict. ` +
  923. `To retain 2.x behavior, move v-bind to make it the first attribute. ` +
  924. `You can also suppress this warning if the usage is intended.`,
  925. link: `https://v3-migration.vuejs.org/breaking-changes/v-bind.html`
  926. },
  927. ["COMPILER_V_ON_NATIVE" /* CompilerDeprecationTypes.COMPILER_V_ON_NATIVE */]: {
  928. message: `.native modifier for v-on has been removed as is no longer necessary.`,
  929. link: `https://v3-migration.vuejs.org/breaking-changes/v-on-native-modifier-removed.html`
  930. },
  931. ["COMPILER_V_IF_V_FOR_PRECEDENCE" /* CompilerDeprecationTypes.COMPILER_V_IF_V_FOR_PRECEDENCE */]: {
  932. message: `v-if / v-for precedence when used on the same element has changed ` +
  933. `in Vue 3: v-if now takes higher precedence and will no longer have ` +
  934. `access to v-for scope variables. It is best to avoid the ambiguity ` +
  935. `with <template> tags or use a computed property that filters v-for ` +
  936. `data source.`,
  937. link: `https://v3-migration.vuejs.org/breaking-changes/v-if-v-for.html`
  938. },
  939. ["COMPILER_NATIVE_TEMPLATE" /* CompilerDeprecationTypes.COMPILER_NATIVE_TEMPLATE */]: {
  940. message: `<template> with no special directives will render as a native template ` +
  941. `element instead of its inner content in Vue 3.`
  942. },
  943. ["COMPILER_INLINE_TEMPLATE" /* CompilerDeprecationTypes.COMPILER_INLINE_TEMPLATE */]: {
  944. message: `"inline-template" has been removed in Vue 3.`,
  945. link: `https://v3-migration.vuejs.org/breaking-changes/inline-template-attribute.html`
  946. },
  947. ["COMPILER_FILTER" /* CompilerDeprecationTypes.COMPILER_FILTERS */]: {
  948. message: `filters have been removed in Vue 3. ` +
  949. `The "|" symbol will be treated as native JavaScript bitwise OR operator. ` +
  950. `Use method calls or computed properties instead.`,
  951. link: `https://v3-migration.vuejs.org/breaking-changes/filters.html`
  952. }
  953. };
  954. function getCompatValue(key, context) {
  955. const config = context.options
  956. ? context.options.compatConfig
  957. : context.compatConfig;
  958. const value = config && config[key];
  959. if (key === 'MODE') {
  960. return value || 3; // compiler defaults to v3 behavior
  961. }
  962. else {
  963. return value;
  964. }
  965. }
  966. function isCompatEnabled(key, context) {
  967. const mode = getCompatValue('MODE', context);
  968. const value = getCompatValue(key, context);
  969. // in v3 mode, only enable if explicitly set to true
  970. // otherwise enable for any non-false value
  971. return mode === 3 ? value === true : value !== false;
  972. }
  973. function checkCompatEnabled(key, context, loc, ...args) {
  974. const enabled = isCompatEnabled(key, context);
  975. if (enabled) {
  976. warnDeprecation(key, context, loc, ...args);
  977. }
  978. return enabled;
  979. }
  980. function warnDeprecation(key, context, loc, ...args) {
  981. const val = getCompatValue(key, context);
  982. if (val === 'suppress-warning') {
  983. return;
  984. }
  985. const { message, link } = deprecationData[key];
  986. const msg = `(deprecation ${key}) ${typeof message === 'function' ? message(...args) : message}${link ? `\n Details: ${link}` : ``}`;
  987. const err = new SyntaxError(msg);
  988. err.code = key;
  989. if (loc)
  990. err.loc = loc;
  991. context.onWarn(err);
  992. }
  993. // The default decoder only provides escapes for characters reserved as part of
  994. // the template syntax, and is only used if the custom renderer did not provide
  995. // a platform-specific decoder.
  996. const decodeRE = /&(gt|lt|amp|apos|quot);/g;
  997. const decodeMap = {
  998. gt: '>',
  999. lt: '<',
  1000. amp: '&',
  1001. apos: "'",
  1002. quot: '"'
  1003. };
  1004. const defaultParserOptions = {
  1005. delimiters: [`{{`, `}}`],
  1006. getNamespace: () => 0 /* Namespaces.HTML */,
  1007. getTextMode: () => 0 /* TextModes.DATA */,
  1008. isVoidTag: NO,
  1009. isPreTag: NO,
  1010. isCustomElement: NO,
  1011. decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
  1012. onError: defaultOnError,
  1013. onWarn: defaultOnWarn,
  1014. comments: true
  1015. };
  1016. function baseParse(content, options = {}) {
  1017. const context = createParserContext(content, options);
  1018. const start = getCursor(context);
  1019. return createRoot(parseChildren(context, 0 /* TextModes.DATA */, []), getSelection(context, start));
  1020. }
  1021. function createParserContext(content, rawOptions) {
  1022. const options = extend({}, defaultParserOptions);
  1023. let key;
  1024. for (key in rawOptions) {
  1025. // @ts-ignore
  1026. options[key] =
  1027. rawOptions[key] === undefined
  1028. ? defaultParserOptions[key]
  1029. : rawOptions[key];
  1030. }
  1031. return {
  1032. options,
  1033. column: 1,
  1034. line: 1,
  1035. offset: 0,
  1036. originalSource: content,
  1037. source: content,
  1038. inPre: false,
  1039. inVPre: false,
  1040. onWarn: options.onWarn
  1041. };
  1042. }
  1043. function parseChildren(context, mode, ancestors) {
  1044. const parent = last(ancestors);
  1045. const ns = parent ? parent.ns : 0 /* Namespaces.HTML */;
  1046. const nodes = [];
  1047. while (!isEnd(context, mode, ancestors)) {
  1048. const s = context.source;
  1049. let node = undefined;
  1050. if (mode === 0 /* TextModes.DATA */ || mode === 1 /* TextModes.RCDATA */) {
  1051. if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
  1052. // '{{'
  1053. node = parseInterpolation(context, mode);
  1054. }
  1055. else if (mode === 0 /* TextModes.DATA */ && s[0] === '<') {
  1056. // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
  1057. if (s.length === 1) {
  1058. emitError(context, 5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */, 1);
  1059. }
  1060. else if (s[1] === '!') {
  1061. // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
  1062. if (startsWith(s, '<!--')) {
  1063. node = parseComment(context);
  1064. }
  1065. else if (startsWith(s, '<!DOCTYPE')) {
  1066. // Ignore DOCTYPE by a limitation.
  1067. node = parseBogusComment(context);
  1068. }
  1069. else if (startsWith(s, '<![CDATA[')) {
  1070. if (ns !== 0 /* Namespaces.HTML */) {
  1071. node = parseCDATA(context, ancestors);
  1072. }
  1073. else {
  1074. emitError(context, 1 /* ErrorCodes.CDATA_IN_HTML_CONTENT */);
  1075. node = parseBogusComment(context);
  1076. }
  1077. }
  1078. else {
  1079. emitError(context, 11 /* ErrorCodes.INCORRECTLY_OPENED_COMMENT */);
  1080. node = parseBogusComment(context);
  1081. }
  1082. }
  1083. else if (s[1] === '/') {
  1084. // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
  1085. if (s.length === 2) {
  1086. emitError(context, 5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */, 2);
  1087. }
  1088. else if (s[2] === '>') {
  1089. emitError(context, 14 /* ErrorCodes.MISSING_END_TAG_NAME */, 2);
  1090. advanceBy(context, 3);
  1091. continue;
  1092. }
  1093. else if (/[a-z]/i.test(s[2])) {
  1094. emitError(context, 23 /* ErrorCodes.X_INVALID_END_TAG */);
  1095. parseTag(context, 1 /* TagType.End */, parent);
  1096. continue;
  1097. }
  1098. else {
  1099. emitError(context, 12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
  1100. node = parseBogusComment(context);
  1101. }
  1102. }
  1103. else if (/[a-z]/i.test(s[1])) {
  1104. node = parseElement(context, ancestors);
  1105. // 2.x <template> with no directive compat
  1106. if (isCompatEnabled("COMPILER_NATIVE_TEMPLATE" /* CompilerDeprecationTypes.COMPILER_NATIVE_TEMPLATE */, context) &&
  1107. node &&
  1108. node.tag === 'template' &&
  1109. !node.props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  1110. isSpecialTemplateDirective(p.name))) {
  1111. warnDeprecation("COMPILER_NATIVE_TEMPLATE" /* CompilerDeprecationTypes.COMPILER_NATIVE_TEMPLATE */, context, node.loc);
  1112. node = node.children;
  1113. }
  1114. }
  1115. else if (s[1] === '?') {
  1116. emitError(context, 21 /* ErrorCodes.UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
  1117. node = parseBogusComment(context);
  1118. }
  1119. else {
  1120. emitError(context, 12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
  1121. }
  1122. }
  1123. }
  1124. if (!node) {
  1125. node = parseText(context, mode);
  1126. }
  1127. if (isArray(node)) {
  1128. for (let i = 0; i < node.length; i++) {
  1129. pushNode(nodes, node[i]);
  1130. }
  1131. }
  1132. else {
  1133. pushNode(nodes, node);
  1134. }
  1135. }
  1136. // Whitespace handling strategy like v2
  1137. let removedWhitespace = false;
  1138. if (mode !== 2 /* TextModes.RAWTEXT */ && mode !== 1 /* TextModes.RCDATA */) {
  1139. const shouldCondense = context.options.whitespace !== 'preserve';
  1140. for (let i = 0; i < nodes.length; i++) {
  1141. const node = nodes[i];
  1142. if (node.type === 2 /* NodeTypes.TEXT */) {
  1143. if (!context.inPre) {
  1144. if (!/[^\t\r\n\f ]/.test(node.content)) {
  1145. const prev = nodes[i - 1];
  1146. const next = nodes[i + 1];
  1147. // Remove if:
  1148. // - the whitespace is the first or last node, or:
  1149. // - (condense mode) the whitespace is between twos comments, or:
  1150. // - (condense mode) the whitespace is between comment and element, or:
  1151. // - (condense mode) the whitespace is between two elements AND contains newline
  1152. if (!prev ||
  1153. !next ||
  1154. (shouldCondense &&
  1155. ((prev.type === 3 /* NodeTypes.COMMENT */ &&
  1156. next.type === 3 /* NodeTypes.COMMENT */) ||
  1157. (prev.type === 3 /* NodeTypes.COMMENT */ &&
  1158. next.type === 1 /* NodeTypes.ELEMENT */) ||
  1159. (prev.type === 1 /* NodeTypes.ELEMENT */ &&
  1160. next.type === 3 /* NodeTypes.COMMENT */) ||
  1161. (prev.type === 1 /* NodeTypes.ELEMENT */ &&
  1162. next.type === 1 /* NodeTypes.ELEMENT */ &&
  1163. /[\r\n]/.test(node.content))))) {
  1164. removedWhitespace = true;
  1165. nodes[i] = null;
  1166. }
  1167. else {
  1168. // Otherwise, the whitespace is condensed into a single space
  1169. node.content = ' ';
  1170. }
  1171. }
  1172. else if (shouldCondense) {
  1173. // in condense mode, consecutive whitespaces in text are condensed
  1174. // down to a single space.
  1175. node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
  1176. }
  1177. }
  1178. else {
  1179. // #6410 normalize windows newlines in <pre>:
  1180. // in SSR, browsers normalize server-rendered \r\n into a single \n
  1181. // in the DOM
  1182. node.content = node.content.replace(/\r\n/g, '\n');
  1183. }
  1184. }
  1185. // Remove comment nodes if desired by configuration.
  1186. else if (node.type === 3 /* NodeTypes.COMMENT */ && !context.options.comments) {
  1187. removedWhitespace = true;
  1188. nodes[i] = null;
  1189. }
  1190. }
  1191. if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
  1192. // remove leading newline per html spec
  1193. // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
  1194. const first = nodes[0];
  1195. if (first && first.type === 2 /* NodeTypes.TEXT */) {
  1196. first.content = first.content.replace(/^\r?\n/, '');
  1197. }
  1198. }
  1199. }
  1200. return removedWhitespace ? nodes.filter(Boolean) : nodes;
  1201. }
  1202. function pushNode(nodes, node) {
  1203. if (node.type === 2 /* NodeTypes.TEXT */) {
  1204. const prev = last(nodes);
  1205. // Merge if both this and the previous node are text and those are
  1206. // consecutive. This happens for cases like "a < b".
  1207. if (prev &&
  1208. prev.type === 2 /* NodeTypes.TEXT */ &&
  1209. prev.loc.end.offset === node.loc.start.offset) {
  1210. prev.content += node.content;
  1211. prev.loc.end = node.loc.end;
  1212. prev.loc.source += node.loc.source;
  1213. return;
  1214. }
  1215. }
  1216. nodes.push(node);
  1217. }
  1218. function parseCDATA(context, ancestors) {
  1219. advanceBy(context, 9);
  1220. const nodes = parseChildren(context, 3 /* TextModes.CDATA */, ancestors);
  1221. if (context.source.length === 0) {
  1222. emitError(context, 6 /* ErrorCodes.EOF_IN_CDATA */);
  1223. }
  1224. else {
  1225. advanceBy(context, 3);
  1226. }
  1227. return nodes;
  1228. }
  1229. function parseComment(context) {
  1230. const start = getCursor(context);
  1231. let content;
  1232. // Regular comment.
  1233. const match = /--(\!)?>/.exec(context.source);
  1234. if (!match) {
  1235. content = context.source.slice(4);
  1236. advanceBy(context, context.source.length);
  1237. emitError(context, 7 /* ErrorCodes.EOF_IN_COMMENT */);
  1238. }
  1239. else {
  1240. if (match.index <= 3) {
  1241. emitError(context, 0 /* ErrorCodes.ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
  1242. }
  1243. if (match[1]) {
  1244. emitError(context, 10 /* ErrorCodes.INCORRECTLY_CLOSED_COMMENT */);
  1245. }
  1246. content = context.source.slice(4, match.index);
  1247. // Advancing with reporting nested comments.
  1248. const s = context.source.slice(0, match.index);
  1249. let prevIndex = 1, nestedIndex = 0;
  1250. while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
  1251. advanceBy(context, nestedIndex - prevIndex + 1);
  1252. if (nestedIndex + 4 < s.length) {
  1253. emitError(context, 16 /* ErrorCodes.NESTED_COMMENT */);
  1254. }
  1255. prevIndex = nestedIndex + 1;
  1256. }
  1257. advanceBy(context, match.index + match[0].length - prevIndex + 1);
  1258. }
  1259. return {
  1260. type: 3 /* NodeTypes.COMMENT */,
  1261. content,
  1262. loc: getSelection(context, start)
  1263. };
  1264. }
  1265. function parseBogusComment(context) {
  1266. const start = getCursor(context);
  1267. const contentStart = context.source[1] === '?' ? 1 : 2;
  1268. let content;
  1269. const closeIndex = context.source.indexOf('>');
  1270. if (closeIndex === -1) {
  1271. content = context.source.slice(contentStart);
  1272. advanceBy(context, context.source.length);
  1273. }
  1274. else {
  1275. content = context.source.slice(contentStart, closeIndex);
  1276. advanceBy(context, closeIndex + 1);
  1277. }
  1278. return {
  1279. type: 3 /* NodeTypes.COMMENT */,
  1280. content,
  1281. loc: getSelection(context, start)
  1282. };
  1283. }
  1284. function parseElement(context, ancestors) {
  1285. // Start tag.
  1286. const wasInPre = context.inPre;
  1287. const wasInVPre = context.inVPre;
  1288. const parent = last(ancestors);
  1289. const element = parseTag(context, 0 /* TagType.Start */, parent);
  1290. const isPreBoundary = context.inPre && !wasInPre;
  1291. const isVPreBoundary = context.inVPre && !wasInVPre;
  1292. if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
  1293. // #4030 self-closing <pre> tag
  1294. if (isPreBoundary) {
  1295. context.inPre = false;
  1296. }
  1297. if (isVPreBoundary) {
  1298. context.inVPre = false;
  1299. }
  1300. return element;
  1301. }
  1302. // Children.
  1303. ancestors.push(element);
  1304. const mode = context.options.getTextMode(element, parent);
  1305. const children = parseChildren(context, mode, ancestors);
  1306. ancestors.pop();
  1307. // 2.x inline-template compat
  1308. {
  1309. const inlineTemplateProp = element.props.find(p => p.type === 6 /* NodeTypes.ATTRIBUTE */ && p.name === 'inline-template');
  1310. if (inlineTemplateProp &&
  1311. checkCompatEnabled("COMPILER_INLINE_TEMPLATE" /* CompilerDeprecationTypes.COMPILER_INLINE_TEMPLATE */, context, inlineTemplateProp.loc)) {
  1312. const loc = getSelection(context, element.loc.end);
  1313. inlineTemplateProp.value = {
  1314. type: 2 /* NodeTypes.TEXT */,
  1315. content: loc.source,
  1316. loc
  1317. };
  1318. }
  1319. }
  1320. element.children = children;
  1321. // End tag.
  1322. if (startsWithEndTagOpen(context.source, element.tag)) {
  1323. parseTag(context, 1 /* TagType.End */, parent);
  1324. }
  1325. else {
  1326. emitError(context, 24 /* ErrorCodes.X_MISSING_END_TAG */, 0, element.loc.start);
  1327. if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
  1328. const first = children[0];
  1329. if (first && startsWith(first.loc.source, '<!--')) {
  1330. emitError(context, 8 /* ErrorCodes.EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
  1331. }
  1332. }
  1333. }
  1334. element.loc = getSelection(context, element.loc.start);
  1335. if (isPreBoundary) {
  1336. context.inPre = false;
  1337. }
  1338. if (isVPreBoundary) {
  1339. context.inVPre = false;
  1340. }
  1341. return element;
  1342. }
  1343. const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
  1344. function parseTag(context, type, parent) {
  1345. // Tag open.
  1346. const start = getCursor(context);
  1347. const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
  1348. const tag = match[1];
  1349. const ns = context.options.getNamespace(tag, parent);
  1350. advanceBy(context, match[0].length);
  1351. advanceSpaces(context);
  1352. // save current state in case we need to re-parse attributes with v-pre
  1353. const cursor = getCursor(context);
  1354. const currentSource = context.source;
  1355. // check <pre> tag
  1356. if (context.options.isPreTag(tag)) {
  1357. context.inPre = true;
  1358. }
  1359. // Attributes.
  1360. let props = parseAttributes(context, type);
  1361. // check v-pre
  1362. if (type === 0 /* TagType.Start */ &&
  1363. !context.inVPre &&
  1364. props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'pre')) {
  1365. context.inVPre = true;
  1366. // reset context
  1367. extend(context, cursor);
  1368. context.source = currentSource;
  1369. // re-parse attrs and filter out v-pre itself
  1370. props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
  1371. }
  1372. // Tag close.
  1373. let isSelfClosing = false;
  1374. if (context.source.length === 0) {
  1375. emitError(context, 9 /* ErrorCodes.EOF_IN_TAG */);
  1376. }
  1377. else {
  1378. isSelfClosing = startsWith(context.source, '/>');
  1379. if (type === 1 /* TagType.End */ && isSelfClosing) {
  1380. emitError(context, 4 /* ErrorCodes.END_TAG_WITH_TRAILING_SOLIDUS */);
  1381. }
  1382. advanceBy(context, isSelfClosing ? 2 : 1);
  1383. }
  1384. if (type === 1 /* TagType.End */) {
  1385. return;
  1386. }
  1387. // 2.x deprecation checks
  1388. if (isCompatEnabled("COMPILER_V_IF_V_FOR_PRECEDENCE" /* CompilerDeprecationTypes.COMPILER_V_IF_V_FOR_PRECEDENCE */, context)) {
  1389. let hasIf = false;
  1390. let hasFor = false;
  1391. for (let i = 0; i < props.length; i++) {
  1392. const p = props[i];
  1393. if (p.type === 7 /* NodeTypes.DIRECTIVE */) {
  1394. if (p.name === 'if') {
  1395. hasIf = true;
  1396. }
  1397. else if (p.name === 'for') {
  1398. hasFor = true;
  1399. }
  1400. }
  1401. if (hasIf && hasFor) {
  1402. warnDeprecation("COMPILER_V_IF_V_FOR_PRECEDENCE" /* CompilerDeprecationTypes.COMPILER_V_IF_V_FOR_PRECEDENCE */, context, getSelection(context, start));
  1403. break;
  1404. }
  1405. }
  1406. }
  1407. let tagType = 0 /* ElementTypes.ELEMENT */;
  1408. if (!context.inVPre) {
  1409. if (tag === 'slot') {
  1410. tagType = 2 /* ElementTypes.SLOT */;
  1411. }
  1412. else if (tag === 'template') {
  1413. if (props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ && isSpecialTemplateDirective(p.name))) {
  1414. tagType = 3 /* ElementTypes.TEMPLATE */;
  1415. }
  1416. }
  1417. else if (isComponent(tag, props, context)) {
  1418. tagType = 1 /* ElementTypes.COMPONENT */;
  1419. }
  1420. }
  1421. return {
  1422. type: 1 /* NodeTypes.ELEMENT */,
  1423. ns,
  1424. tag,
  1425. tagType,
  1426. props,
  1427. isSelfClosing,
  1428. children: [],
  1429. loc: getSelection(context, start),
  1430. codegenNode: undefined // to be created during transform phase
  1431. };
  1432. }
  1433. function isComponent(tag, props, context) {
  1434. const options = context.options;
  1435. if (options.isCustomElement(tag)) {
  1436. return false;
  1437. }
  1438. if (tag === 'component' ||
  1439. /^[A-Z]/.test(tag) ||
  1440. isCoreComponent(tag) ||
  1441. (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
  1442. (options.isNativeTag && !options.isNativeTag(tag))) {
  1443. return true;
  1444. }
  1445. // at this point the tag should be a native tag, but check for potential "is"
  1446. // casting
  1447. for (let i = 0; i < props.length; i++) {
  1448. const p = props[i];
  1449. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  1450. if (p.name === 'is' && p.value) {
  1451. if (p.value.content.startsWith('vue:')) {
  1452. return true;
  1453. }
  1454. else if (checkCompatEnabled("COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */, context, p.loc)) {
  1455. return true;
  1456. }
  1457. }
  1458. }
  1459. else {
  1460. // directive
  1461. // v-is (TODO Deprecate)
  1462. if (p.name === 'is') {
  1463. return true;
  1464. }
  1465. else if (
  1466. // :is on plain element - only treat as component in compat mode
  1467. p.name === 'bind' &&
  1468. isStaticArgOf(p.arg, 'is') &&
  1469. true &&
  1470. checkCompatEnabled("COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */, context, p.loc)) {
  1471. return true;
  1472. }
  1473. }
  1474. }
  1475. }
  1476. function parseAttributes(context, type) {
  1477. const props = [];
  1478. const attributeNames = new Set();
  1479. while (context.source.length > 0 &&
  1480. !startsWith(context.source, '>') &&
  1481. !startsWith(context.source, '/>')) {
  1482. if (startsWith(context.source, '/')) {
  1483. emitError(context, 22 /* ErrorCodes.UNEXPECTED_SOLIDUS_IN_TAG */);
  1484. advanceBy(context, 1);
  1485. advanceSpaces(context);
  1486. continue;
  1487. }
  1488. if (type === 1 /* TagType.End */) {
  1489. emitError(context, 3 /* ErrorCodes.END_TAG_WITH_ATTRIBUTES */);
  1490. }
  1491. const attr = parseAttribute(context, attributeNames);
  1492. // Trim whitespace between class
  1493. // https://github.com/vuejs/core/issues/4251
  1494. if (attr.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  1495. attr.value &&
  1496. attr.name === 'class') {
  1497. attr.value.content = attr.value.content.replace(/\s+/g, ' ').trim();
  1498. }
  1499. if (type === 0 /* TagType.Start */) {
  1500. props.push(attr);
  1501. }
  1502. if (/^[^\t\r\n\f />]/.test(context.source)) {
  1503. emitError(context, 15 /* ErrorCodes.MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
  1504. }
  1505. advanceSpaces(context);
  1506. }
  1507. return props;
  1508. }
  1509. function parseAttribute(context, nameSet) {
  1510. // Name.
  1511. const start = getCursor(context);
  1512. const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
  1513. const name = match[0];
  1514. if (nameSet.has(name)) {
  1515. emitError(context, 2 /* ErrorCodes.DUPLICATE_ATTRIBUTE */);
  1516. }
  1517. nameSet.add(name);
  1518. if (name[0] === '=') {
  1519. emitError(context, 19 /* ErrorCodes.UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
  1520. }
  1521. {
  1522. const pattern = /["'<]/g;
  1523. let m;
  1524. while ((m = pattern.exec(name))) {
  1525. emitError(context, 17 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
  1526. }
  1527. }
  1528. advanceBy(context, name.length);
  1529. // Value
  1530. let value = undefined;
  1531. if (/^[\t\r\n\f ]*=/.test(context.source)) {
  1532. advanceSpaces(context);
  1533. advanceBy(context, 1);
  1534. advanceSpaces(context);
  1535. value = parseAttributeValue(context);
  1536. if (!value) {
  1537. emitError(context, 13 /* ErrorCodes.MISSING_ATTRIBUTE_VALUE */);
  1538. }
  1539. }
  1540. const loc = getSelection(context, start);
  1541. if (!context.inVPre && /^(v-[A-Za-z0-9-]|:|\.|@|#)/.test(name)) {
  1542. const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^\.|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
  1543. let isPropShorthand = startsWith(name, '.');
  1544. let dirName = match[1] ||
  1545. (isPropShorthand || startsWith(name, ':')
  1546. ? 'bind'
  1547. : startsWith(name, '@')
  1548. ? 'on'
  1549. : 'slot');
  1550. let arg;
  1551. if (match[2]) {
  1552. const isSlot = dirName === 'slot';
  1553. const startOffset = name.lastIndexOf(match[2]);
  1554. const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
  1555. let content = match[2];
  1556. let isStatic = true;
  1557. if (content.startsWith('[')) {
  1558. isStatic = false;
  1559. if (!content.endsWith(']')) {
  1560. emitError(context, 27 /* ErrorCodes.X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
  1561. content = content.slice(1);
  1562. }
  1563. else {
  1564. content = content.slice(1, content.length - 1);
  1565. }
  1566. }
  1567. else if (isSlot) {
  1568. // #1241 special case for v-slot: vuetify relies extensively on slot
  1569. // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
  1570. // supports such usage so we are keeping it consistent with 2.x.
  1571. content += match[3] || '';
  1572. }
  1573. arg = {
  1574. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  1575. content,
  1576. isStatic,
  1577. constType: isStatic
  1578. ? 3 /* ConstantTypes.CAN_STRINGIFY */
  1579. : 0 /* ConstantTypes.NOT_CONSTANT */,
  1580. loc
  1581. };
  1582. }
  1583. if (value && value.isQuoted) {
  1584. const valueLoc = value.loc;
  1585. valueLoc.start.offset++;
  1586. valueLoc.start.column++;
  1587. valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
  1588. valueLoc.source = valueLoc.source.slice(1, -1);
  1589. }
  1590. const modifiers = match[3] ? match[3].slice(1).split('.') : [];
  1591. if (isPropShorthand)
  1592. modifiers.push('prop');
  1593. // 2.x compat v-bind:foo.sync -> v-model:foo
  1594. if (dirName === 'bind' && arg) {
  1595. if (modifiers.includes('sync') &&
  1596. checkCompatEnabled("COMPILER_V_BIND_SYNC" /* CompilerDeprecationTypes.COMPILER_V_BIND_SYNC */, context, loc, arg.loc.source)) {
  1597. dirName = 'model';
  1598. modifiers.splice(modifiers.indexOf('sync'), 1);
  1599. }
  1600. if (modifiers.includes('prop')) {
  1601. checkCompatEnabled("COMPILER_V_BIND_PROP" /* CompilerDeprecationTypes.COMPILER_V_BIND_PROP */, context, loc);
  1602. }
  1603. }
  1604. return {
  1605. type: 7 /* NodeTypes.DIRECTIVE */,
  1606. name: dirName,
  1607. exp: value && {
  1608. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  1609. content: value.content,
  1610. isStatic: false,
  1611. // Treat as non-constant by default. This can be potentially set to
  1612. // other values by `transformExpression` to make it eligible for hoisting.
  1613. constType: 0 /* ConstantTypes.NOT_CONSTANT */,
  1614. loc: value.loc
  1615. },
  1616. arg,
  1617. modifiers,
  1618. loc
  1619. };
  1620. }
  1621. // missing directive name or illegal directive name
  1622. if (!context.inVPre && startsWith(name, 'v-')) {
  1623. emitError(context, 26 /* ErrorCodes.X_MISSING_DIRECTIVE_NAME */);
  1624. }
  1625. return {
  1626. type: 6 /* NodeTypes.ATTRIBUTE */,
  1627. name,
  1628. value: value && {
  1629. type: 2 /* NodeTypes.TEXT */,
  1630. content: value.content,
  1631. loc: value.loc
  1632. },
  1633. loc
  1634. };
  1635. }
  1636. function parseAttributeValue(context) {
  1637. const start = getCursor(context);
  1638. let content;
  1639. const quote = context.source[0];
  1640. const isQuoted = quote === `"` || quote === `'`;
  1641. if (isQuoted) {
  1642. // Quoted value.
  1643. advanceBy(context, 1);
  1644. const endIndex = context.source.indexOf(quote);
  1645. if (endIndex === -1) {
  1646. content = parseTextData(context, context.source.length, 4 /* TextModes.ATTRIBUTE_VALUE */);
  1647. }
  1648. else {
  1649. content = parseTextData(context, endIndex, 4 /* TextModes.ATTRIBUTE_VALUE */);
  1650. advanceBy(context, 1);
  1651. }
  1652. }
  1653. else {
  1654. // Unquoted
  1655. const match = /^[^\t\r\n\f >]+/.exec(context.source);
  1656. if (!match) {
  1657. return undefined;
  1658. }
  1659. const unexpectedChars = /["'<=`]/g;
  1660. let m;
  1661. while ((m = unexpectedChars.exec(match[0]))) {
  1662. emitError(context, 18 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
  1663. }
  1664. content = parseTextData(context, match[0].length, 4 /* TextModes.ATTRIBUTE_VALUE */);
  1665. }
  1666. return { content, isQuoted, loc: getSelection(context, start) };
  1667. }
  1668. function parseInterpolation(context, mode) {
  1669. const [open, close] = context.options.delimiters;
  1670. const closeIndex = context.source.indexOf(close, open.length);
  1671. if (closeIndex === -1) {
  1672. emitError(context, 25 /* ErrorCodes.X_MISSING_INTERPOLATION_END */);
  1673. return undefined;
  1674. }
  1675. const start = getCursor(context);
  1676. advanceBy(context, open.length);
  1677. const innerStart = getCursor(context);
  1678. const innerEnd = getCursor(context);
  1679. const rawContentLength = closeIndex - open.length;
  1680. const rawContent = context.source.slice(0, rawContentLength);
  1681. const preTrimContent = parseTextData(context, rawContentLength, mode);
  1682. const content = preTrimContent.trim();
  1683. const startOffset = preTrimContent.indexOf(content);
  1684. if (startOffset > 0) {
  1685. advancePositionWithMutation(innerStart, rawContent, startOffset);
  1686. }
  1687. const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
  1688. advancePositionWithMutation(innerEnd, rawContent, endOffset);
  1689. advanceBy(context, close.length);
  1690. return {
  1691. type: 5 /* NodeTypes.INTERPOLATION */,
  1692. content: {
  1693. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  1694. isStatic: false,
  1695. // Set `isConstant` to false by default and will decide in transformExpression
  1696. constType: 0 /* ConstantTypes.NOT_CONSTANT */,
  1697. content,
  1698. loc: getSelection(context, innerStart, innerEnd)
  1699. },
  1700. loc: getSelection(context, start)
  1701. };
  1702. }
  1703. function parseText(context, mode) {
  1704. const endTokens = mode === 3 /* TextModes.CDATA */ ? [']]>'] : ['<', context.options.delimiters[0]];
  1705. let endIndex = context.source.length;
  1706. for (let i = 0; i < endTokens.length; i++) {
  1707. const index = context.source.indexOf(endTokens[i], 1);
  1708. if (index !== -1 && endIndex > index) {
  1709. endIndex = index;
  1710. }
  1711. }
  1712. const start = getCursor(context);
  1713. const content = parseTextData(context, endIndex, mode);
  1714. return {
  1715. type: 2 /* NodeTypes.TEXT */,
  1716. content,
  1717. loc: getSelection(context, start)
  1718. };
  1719. }
  1720. /**
  1721. * Get text data with a given length from the current location.
  1722. * This translates HTML entities in the text data.
  1723. */
  1724. function parseTextData(context, length, mode) {
  1725. const rawText = context.source.slice(0, length);
  1726. advanceBy(context, length);
  1727. if (mode === 2 /* TextModes.RAWTEXT */ ||
  1728. mode === 3 /* TextModes.CDATA */ ||
  1729. !rawText.includes('&')) {
  1730. return rawText;
  1731. }
  1732. else {
  1733. // DATA or RCDATA containing "&"". Entity decoding required.
  1734. return context.options.decodeEntities(rawText, mode === 4 /* TextModes.ATTRIBUTE_VALUE */);
  1735. }
  1736. }
  1737. function getCursor(context) {
  1738. const { column, line, offset } = context;
  1739. return { column, line, offset };
  1740. }
  1741. function getSelection(context, start, end) {
  1742. end = end || getCursor(context);
  1743. return {
  1744. start,
  1745. end,
  1746. source: context.originalSource.slice(start.offset, end.offset)
  1747. };
  1748. }
  1749. function last(xs) {
  1750. return xs[xs.length - 1];
  1751. }
  1752. function startsWith(source, searchString) {
  1753. return source.startsWith(searchString);
  1754. }
  1755. function advanceBy(context, numberOfCharacters) {
  1756. const { source } = context;
  1757. advancePositionWithMutation(context, source, numberOfCharacters);
  1758. context.source = source.slice(numberOfCharacters);
  1759. }
  1760. function advanceSpaces(context) {
  1761. const match = /^[\t\r\n\f ]+/.exec(context.source);
  1762. if (match) {
  1763. advanceBy(context, match[0].length);
  1764. }
  1765. }
  1766. function getNewPosition(context, start, numberOfCharacters) {
  1767. return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
  1768. }
  1769. function emitError(context, code, offset, loc = getCursor(context)) {
  1770. if (offset) {
  1771. loc.offset += offset;
  1772. loc.column += offset;
  1773. }
  1774. context.options.onError(createCompilerError(code, {
  1775. start: loc,
  1776. end: loc,
  1777. source: ''
  1778. }));
  1779. }
  1780. function isEnd(context, mode, ancestors) {
  1781. const s = context.source;
  1782. switch (mode) {
  1783. case 0 /* TextModes.DATA */:
  1784. if (startsWith(s, '</')) {
  1785. // TODO: probably bad performance
  1786. for (let i = ancestors.length - 1; i >= 0; --i) {
  1787. if (startsWithEndTagOpen(s, ancestors[i].tag)) {
  1788. return true;
  1789. }
  1790. }
  1791. }
  1792. break;
  1793. case 1 /* TextModes.RCDATA */:
  1794. case 2 /* TextModes.RAWTEXT */: {
  1795. const parent = last(ancestors);
  1796. if (parent && startsWithEndTagOpen(s, parent.tag)) {
  1797. return true;
  1798. }
  1799. break;
  1800. }
  1801. case 3 /* TextModes.CDATA */:
  1802. if (startsWith(s, ']]>')) {
  1803. return true;
  1804. }
  1805. break;
  1806. }
  1807. return !s;
  1808. }
  1809. function startsWithEndTagOpen(source, tag) {
  1810. return (startsWith(source, '</') &&
  1811. source.slice(2, 2 + tag.length).toLowerCase() === tag.toLowerCase() &&
  1812. /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
  1813. }
  1814. function hoistStatic(root, context) {
  1815. walk(root, context,
  1816. // Root node is unfortunately non-hoistable due to potential parent
  1817. // fallthrough attributes.
  1818. isSingleElementRoot(root, root.children[0]));
  1819. }
  1820. function isSingleElementRoot(root, child) {
  1821. const { children } = root;
  1822. return (children.length === 1 &&
  1823. child.type === 1 /* NodeTypes.ELEMENT */ &&
  1824. !isSlotOutlet(child));
  1825. }
  1826. function walk(node, context, doNotHoistNode = false) {
  1827. const { children } = node;
  1828. const originalCount = children.length;
  1829. let hoistedCount = 0;
  1830. for (let i = 0; i < children.length; i++) {
  1831. const child = children[i];
  1832. // only plain elements & text calls are eligible for hoisting.
  1833. if (child.type === 1 /* NodeTypes.ELEMENT */ &&
  1834. child.tagType === 0 /* ElementTypes.ELEMENT */) {
  1835. const constantType = doNotHoistNode
  1836. ? 0 /* ConstantTypes.NOT_CONSTANT */
  1837. : getConstantType(child, context);
  1838. if (constantType > 0 /* ConstantTypes.NOT_CONSTANT */) {
  1839. if (constantType >= 2 /* ConstantTypes.CAN_HOIST */) {
  1840. child.codegenNode.patchFlag =
  1841. -1 /* PatchFlags.HOISTED */ + (` /* HOISTED */` );
  1842. child.codegenNode = context.hoist(child.codegenNode);
  1843. hoistedCount++;
  1844. continue;
  1845. }
  1846. }
  1847. else {
  1848. // node may contain dynamic children, but its props may be eligible for
  1849. // hoisting.
  1850. const codegenNode = child.codegenNode;
  1851. if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  1852. const flag = getPatchFlag(codegenNode);
  1853. if ((!flag ||
  1854. flag === 512 /* PatchFlags.NEED_PATCH */ ||
  1855. flag === 1 /* PatchFlags.TEXT */) &&
  1856. getGeneratedPropsConstantType(child, context) >=
  1857. 2 /* ConstantTypes.CAN_HOIST */) {
  1858. const props = getNodeProps(child);
  1859. if (props) {
  1860. codegenNode.props = context.hoist(props);
  1861. }
  1862. }
  1863. if (codegenNode.dynamicProps) {
  1864. codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps);
  1865. }
  1866. }
  1867. }
  1868. }
  1869. // walk further
  1870. if (child.type === 1 /* NodeTypes.ELEMENT */) {
  1871. const isComponent = child.tagType === 1 /* ElementTypes.COMPONENT */;
  1872. if (isComponent) {
  1873. context.scopes.vSlot++;
  1874. }
  1875. walk(child, context);
  1876. if (isComponent) {
  1877. context.scopes.vSlot--;
  1878. }
  1879. }
  1880. else if (child.type === 11 /* NodeTypes.FOR */) {
  1881. // Do not hoist v-for single child because it has to be a block
  1882. walk(child, context, child.children.length === 1);
  1883. }
  1884. else if (child.type === 9 /* NodeTypes.IF */) {
  1885. for (let i = 0; i < child.branches.length; i++) {
  1886. // Do not hoist v-if single child because it has to be a block
  1887. walk(child.branches[i], context, child.branches[i].children.length === 1);
  1888. }
  1889. }
  1890. }
  1891. if (hoistedCount && context.transformHoist) {
  1892. context.transformHoist(children, context, node);
  1893. }
  1894. // all children were hoisted - the entire children array is hoistable.
  1895. if (hoistedCount &&
  1896. hoistedCount === originalCount &&
  1897. node.type === 1 /* NodeTypes.ELEMENT */ &&
  1898. node.tagType === 0 /* ElementTypes.ELEMENT */ &&
  1899. node.codegenNode &&
  1900. node.codegenNode.type === 13 /* NodeTypes.VNODE_CALL */ &&
  1901. isArray(node.codegenNode.children)) {
  1902. node.codegenNode.children = context.hoist(createArrayExpression(node.codegenNode.children));
  1903. }
  1904. }
  1905. function getConstantType(node, context) {
  1906. const { constantCache } = context;
  1907. switch (node.type) {
  1908. case 1 /* NodeTypes.ELEMENT */:
  1909. if (node.tagType !== 0 /* ElementTypes.ELEMENT */) {
  1910. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1911. }
  1912. const cached = constantCache.get(node);
  1913. if (cached !== undefined) {
  1914. return cached;
  1915. }
  1916. const codegenNode = node.codegenNode;
  1917. if (codegenNode.type !== 13 /* NodeTypes.VNODE_CALL */) {
  1918. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1919. }
  1920. if (codegenNode.isBlock &&
  1921. node.tag !== 'svg' &&
  1922. node.tag !== 'foreignObject') {
  1923. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1924. }
  1925. const flag = getPatchFlag(codegenNode);
  1926. if (!flag) {
  1927. let returnType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  1928. // Element itself has no patch flag. However we still need to check:
  1929. // 1. Even for a node with no patch flag, it is possible for it to contain
  1930. // non-hoistable expressions that refers to scope variables, e.g. compiler
  1931. // injected keys or cached event handlers. Therefore we need to always
  1932. // check the codegenNode's props to be sure.
  1933. const generatedPropsType = getGeneratedPropsConstantType(node, context);
  1934. if (generatedPropsType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  1935. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  1936. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1937. }
  1938. if (generatedPropsType < returnType) {
  1939. returnType = generatedPropsType;
  1940. }
  1941. // 2. its children.
  1942. for (let i = 0; i < node.children.length; i++) {
  1943. const childType = getConstantType(node.children[i], context);
  1944. if (childType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  1945. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  1946. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1947. }
  1948. if (childType < returnType) {
  1949. returnType = childType;
  1950. }
  1951. }
  1952. // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
  1953. // type, check if any of the props can cause the type to be lowered
  1954. // we can skip can_patch because it's guaranteed by the absence of a
  1955. // patchFlag.
  1956. if (returnType > 1 /* ConstantTypes.CAN_SKIP_PATCH */) {
  1957. for (let i = 0; i < node.props.length; i++) {
  1958. const p = node.props[i];
  1959. if (p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'bind' && p.exp) {
  1960. const expType = getConstantType(p.exp, context);
  1961. if (expType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  1962. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  1963. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1964. }
  1965. if (expType < returnType) {
  1966. returnType = expType;
  1967. }
  1968. }
  1969. }
  1970. }
  1971. // only svg/foreignObject could be block here, however if they are
  1972. // static then they don't need to be blocks since there will be no
  1973. // nested updates.
  1974. if (codegenNode.isBlock) {
  1975. // except set custom directives.
  1976. for (let i = 0; i < node.props.length; i++) {
  1977. const p = node.props[i];
  1978. if (p.type === 7 /* NodeTypes.DIRECTIVE */) {
  1979. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  1980. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1981. }
  1982. }
  1983. context.removeHelper(OPEN_BLOCK);
  1984. context.removeHelper(getVNodeBlockHelper(context.inSSR, codegenNode.isComponent));
  1985. codegenNode.isBlock = false;
  1986. context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent));
  1987. }
  1988. constantCache.set(node, returnType);
  1989. return returnType;
  1990. }
  1991. else {
  1992. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  1993. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1994. }
  1995. case 2 /* NodeTypes.TEXT */:
  1996. case 3 /* NodeTypes.COMMENT */:
  1997. return 3 /* ConstantTypes.CAN_STRINGIFY */;
  1998. case 9 /* NodeTypes.IF */:
  1999. case 11 /* NodeTypes.FOR */:
  2000. case 10 /* NodeTypes.IF_BRANCH */:
  2001. return 0 /* ConstantTypes.NOT_CONSTANT */;
  2002. case 5 /* NodeTypes.INTERPOLATION */:
  2003. case 12 /* NodeTypes.TEXT_CALL */:
  2004. return getConstantType(node.content, context);
  2005. case 4 /* NodeTypes.SIMPLE_EXPRESSION */:
  2006. return node.constType;
  2007. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  2008. let returnType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  2009. for (let i = 0; i < node.children.length; i++) {
  2010. const child = node.children[i];
  2011. if (isString(child) || isSymbol(child)) {
  2012. continue;
  2013. }
  2014. const childType = getConstantType(child, context);
  2015. if (childType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  2016. return 0 /* ConstantTypes.NOT_CONSTANT */;
  2017. }
  2018. else if (childType < returnType) {
  2019. returnType = childType;
  2020. }
  2021. }
  2022. return returnType;
  2023. default:
  2024. return 0 /* ConstantTypes.NOT_CONSTANT */;
  2025. }
  2026. }
  2027. const allowHoistedHelperSet = new Set([
  2028. NORMALIZE_CLASS,
  2029. NORMALIZE_STYLE,
  2030. NORMALIZE_PROPS,
  2031. GUARD_REACTIVE_PROPS
  2032. ]);
  2033. function getConstantTypeOfHelperCall(value, context) {
  2034. if (value.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */ &&
  2035. !isString(value.callee) &&
  2036. allowHoistedHelperSet.has(value.callee)) {
  2037. const arg = value.arguments[0];
  2038. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  2039. return getConstantType(arg, context);
  2040. }
  2041. else if (arg.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  2042. // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(exp))`
  2043. return getConstantTypeOfHelperCall(arg, context);
  2044. }
  2045. }
  2046. return 0 /* ConstantTypes.NOT_CONSTANT */;
  2047. }
  2048. function getGeneratedPropsConstantType(node, context) {
  2049. let returnType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  2050. const props = getNodeProps(node);
  2051. if (props && props.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
  2052. const { properties } = props;
  2053. for (let i = 0; i < properties.length; i++) {
  2054. const { key, value } = properties[i];
  2055. const keyType = getConstantType(key, context);
  2056. if (keyType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  2057. return keyType;
  2058. }
  2059. if (keyType < returnType) {
  2060. returnType = keyType;
  2061. }
  2062. let valueType;
  2063. if (value.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  2064. valueType = getConstantType(value, context);
  2065. }
  2066. else if (value.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  2067. // some helper calls can be hoisted,
  2068. // such as the `normalizeProps` generated by the compiler for pre-normalize class,
  2069. // in this case we need to respect the ConstantType of the helper's arguments
  2070. valueType = getConstantTypeOfHelperCall(value, context);
  2071. }
  2072. else {
  2073. valueType = 0 /* ConstantTypes.NOT_CONSTANT */;
  2074. }
  2075. if (valueType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  2076. return valueType;
  2077. }
  2078. if (valueType < returnType) {
  2079. returnType = valueType;
  2080. }
  2081. }
  2082. }
  2083. return returnType;
  2084. }
  2085. function getNodeProps(node) {
  2086. const codegenNode = node.codegenNode;
  2087. if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  2088. return codegenNode.props;
  2089. }
  2090. }
  2091. function getPatchFlag(node) {
  2092. const flag = node.patchFlag;
  2093. return flag ? parseInt(flag, 10) : undefined;
  2094. }
  2095. 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 }) {
  2096. const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
  2097. const context = {
  2098. // options
  2099. selfName: nameMatch && capitalize(camelize(nameMatch[1])),
  2100. prefixIdentifiers,
  2101. hoistStatic,
  2102. cacheHandlers,
  2103. nodeTransforms,
  2104. directiveTransforms,
  2105. transformHoist,
  2106. isBuiltInComponent,
  2107. isCustomElement,
  2108. expressionPlugins,
  2109. scopeId,
  2110. slotted,
  2111. ssr,
  2112. inSSR,
  2113. ssrCssVars,
  2114. bindingMetadata,
  2115. inline,
  2116. isTS,
  2117. onError,
  2118. onWarn,
  2119. compatConfig,
  2120. // state
  2121. root,
  2122. helpers: new Map(),
  2123. components: new Set(),
  2124. directives: new Set(),
  2125. hoists: [],
  2126. imports: [],
  2127. constantCache: new Map(),
  2128. temps: 0,
  2129. cached: 0,
  2130. identifiers: Object.create(null),
  2131. scopes: {
  2132. vFor: 0,
  2133. vSlot: 0,
  2134. vPre: 0,
  2135. vOnce: 0
  2136. },
  2137. parent: null,
  2138. currentNode: root,
  2139. childIndex: 0,
  2140. inVOnce: false,
  2141. // methods
  2142. helper(name) {
  2143. const count = context.helpers.get(name) || 0;
  2144. context.helpers.set(name, count + 1);
  2145. return name;
  2146. },
  2147. removeHelper(name) {
  2148. const count = context.helpers.get(name);
  2149. if (count) {
  2150. const currentCount = count - 1;
  2151. if (!currentCount) {
  2152. context.helpers.delete(name);
  2153. }
  2154. else {
  2155. context.helpers.set(name, currentCount);
  2156. }
  2157. }
  2158. },
  2159. helperString(name) {
  2160. return `_${helperNameMap[context.helper(name)]}`;
  2161. },
  2162. replaceNode(node) {
  2163. /* istanbul ignore if */
  2164. {
  2165. if (!context.currentNode) {
  2166. throw new Error(`Node being replaced is already removed.`);
  2167. }
  2168. if (!context.parent) {
  2169. throw new Error(`Cannot replace root node.`);
  2170. }
  2171. }
  2172. context.parent.children[context.childIndex] = context.currentNode = node;
  2173. },
  2174. removeNode(node) {
  2175. if (!context.parent) {
  2176. throw new Error(`Cannot remove root node.`);
  2177. }
  2178. const list = context.parent.children;
  2179. const removalIndex = node
  2180. ? list.indexOf(node)
  2181. : context.currentNode
  2182. ? context.childIndex
  2183. : -1;
  2184. /* istanbul ignore if */
  2185. if (removalIndex < 0) {
  2186. throw new Error(`node being removed is not a child of current parent`);
  2187. }
  2188. if (!node || node === context.currentNode) {
  2189. // current node removed
  2190. context.currentNode = null;
  2191. context.onNodeRemoved();
  2192. }
  2193. else {
  2194. // sibling node removed
  2195. if (context.childIndex > removalIndex) {
  2196. context.childIndex--;
  2197. context.onNodeRemoved();
  2198. }
  2199. }
  2200. context.parent.children.splice(removalIndex, 1);
  2201. },
  2202. onNodeRemoved: () => { },
  2203. addIdentifiers(exp) {
  2204. },
  2205. removeIdentifiers(exp) {
  2206. },
  2207. hoist(exp) {
  2208. if (isString(exp))
  2209. exp = createSimpleExpression(exp);
  2210. context.hoists.push(exp);
  2211. const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* ConstantTypes.CAN_HOIST */);
  2212. identifier.hoisted = exp;
  2213. return identifier;
  2214. },
  2215. cache(exp, isVNode = false) {
  2216. return createCacheExpression(context.cached++, exp, isVNode);
  2217. }
  2218. };
  2219. {
  2220. context.filters = new Set();
  2221. }
  2222. return context;
  2223. }
  2224. function transform(root, options) {
  2225. const context = createTransformContext(root, options);
  2226. traverseNode(root, context);
  2227. if (options.hoistStatic) {
  2228. hoistStatic(root, context);
  2229. }
  2230. if (!options.ssr) {
  2231. createRootCodegen(root, context);
  2232. }
  2233. // finalize meta information
  2234. root.helpers = [...context.helpers.keys()];
  2235. root.components = [...context.components];
  2236. root.directives = [...context.directives];
  2237. root.imports = context.imports;
  2238. root.hoists = context.hoists;
  2239. root.temps = context.temps;
  2240. root.cached = context.cached;
  2241. {
  2242. root.filters = [...context.filters];
  2243. }
  2244. }
  2245. function createRootCodegen(root, context) {
  2246. const { helper } = context;
  2247. const { children } = root;
  2248. if (children.length === 1) {
  2249. const child = children[0];
  2250. // if the single child is an element, turn it into a block.
  2251. if (isSingleElementRoot(root, child) && child.codegenNode) {
  2252. // single element root is never hoisted so codegenNode will never be
  2253. // SimpleExpressionNode
  2254. const codegenNode = child.codegenNode;
  2255. if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  2256. makeBlock(codegenNode, context);
  2257. }
  2258. root.codegenNode = codegenNode;
  2259. }
  2260. else {
  2261. // - single <slot/>, IfNode, ForNode: already blocks.
  2262. // - single text node: always patched.
  2263. // root codegen falls through via genNode()
  2264. root.codegenNode = child;
  2265. }
  2266. }
  2267. else if (children.length > 1) {
  2268. // root has multiple nodes - return a fragment block.
  2269. let patchFlag = 64 /* PatchFlags.STABLE_FRAGMENT */;
  2270. let patchFlagText = PatchFlagNames[64 /* PatchFlags.STABLE_FRAGMENT */];
  2271. // check if the fragment actually contains a single valid child with
  2272. // the rest being comments
  2273. if (children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */).length === 1) {
  2274. patchFlag |= 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */;
  2275. patchFlagText += `, ${PatchFlagNames[2048 /* PatchFlags.DEV_ROOT_FRAGMENT */]}`;
  2276. }
  2277. root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, undefined, false /* isComponent */);
  2278. }
  2279. else ;
  2280. }
  2281. function traverseChildren(parent, context) {
  2282. let i = 0;
  2283. const nodeRemoved = () => {
  2284. i--;
  2285. };
  2286. for (; i < parent.children.length; i++) {
  2287. const child = parent.children[i];
  2288. if (isString(child))
  2289. continue;
  2290. context.parent = parent;
  2291. context.childIndex = i;
  2292. context.onNodeRemoved = nodeRemoved;
  2293. traverseNode(child, context);
  2294. }
  2295. }
  2296. function traverseNode(node, context) {
  2297. context.currentNode = node;
  2298. // apply transform plugins
  2299. const { nodeTransforms } = context;
  2300. const exitFns = [];
  2301. for (let i = 0; i < nodeTransforms.length; i++) {
  2302. const onExit = nodeTransforms[i](node, context);
  2303. if (onExit) {
  2304. if (isArray(onExit)) {
  2305. exitFns.push(...onExit);
  2306. }
  2307. else {
  2308. exitFns.push(onExit);
  2309. }
  2310. }
  2311. if (!context.currentNode) {
  2312. // node was removed
  2313. return;
  2314. }
  2315. else {
  2316. // node may have been replaced
  2317. node = context.currentNode;
  2318. }
  2319. }
  2320. switch (node.type) {
  2321. case 3 /* NodeTypes.COMMENT */:
  2322. if (!context.ssr) {
  2323. // inject import for the Comment symbol, which is needed for creating
  2324. // comment nodes with `createVNode`
  2325. context.helper(CREATE_COMMENT);
  2326. }
  2327. break;
  2328. case 5 /* NodeTypes.INTERPOLATION */:
  2329. // no need to traverse, but we need to inject toString helper
  2330. if (!context.ssr) {
  2331. context.helper(TO_DISPLAY_STRING);
  2332. }
  2333. break;
  2334. // for container types, further traverse downwards
  2335. case 9 /* NodeTypes.IF */:
  2336. for (let i = 0; i < node.branches.length; i++) {
  2337. traverseNode(node.branches[i], context);
  2338. }
  2339. break;
  2340. case 10 /* NodeTypes.IF_BRANCH */:
  2341. case 11 /* NodeTypes.FOR */:
  2342. case 1 /* NodeTypes.ELEMENT */:
  2343. case 0 /* NodeTypes.ROOT */:
  2344. traverseChildren(node, context);
  2345. break;
  2346. }
  2347. // exit transforms
  2348. context.currentNode = node;
  2349. let i = exitFns.length;
  2350. while (i--) {
  2351. exitFns[i]();
  2352. }
  2353. }
  2354. function createStructuralDirectiveTransform(name, fn) {
  2355. const matches = isString(name)
  2356. ? (n) => n === name
  2357. : (n) => name.test(n);
  2358. return (node, context) => {
  2359. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  2360. const { props } = node;
  2361. // structural directive transforms are not concerned with slots
  2362. // as they are handled separately in vSlot.ts
  2363. if (node.tagType === 3 /* ElementTypes.TEMPLATE */ && props.some(isVSlot)) {
  2364. return;
  2365. }
  2366. const exitFns = [];
  2367. for (let i = 0; i < props.length; i++) {
  2368. const prop = props[i];
  2369. if (prop.type === 7 /* NodeTypes.DIRECTIVE */ && matches(prop.name)) {
  2370. // structural directives are removed to avoid infinite recursion
  2371. // also we remove them *before* applying so that it can further
  2372. // traverse itself in case it moves the node around
  2373. props.splice(i, 1);
  2374. i--;
  2375. const onExit = fn(node, prop, context);
  2376. if (onExit)
  2377. exitFns.push(onExit);
  2378. }
  2379. }
  2380. return exitFns;
  2381. }
  2382. };
  2383. }
  2384. const PURE_ANNOTATION = `/*#__PURE__*/`;
  2385. const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
  2386. 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 }) {
  2387. const context = {
  2388. mode,
  2389. prefixIdentifiers,
  2390. sourceMap,
  2391. filename,
  2392. scopeId,
  2393. optimizeImports,
  2394. runtimeGlobalName,
  2395. runtimeModuleName,
  2396. ssrRuntimeModuleName,
  2397. ssr,
  2398. isTS,
  2399. inSSR,
  2400. source: ast.loc.source,
  2401. code: ``,
  2402. column: 1,
  2403. line: 1,
  2404. offset: 0,
  2405. indentLevel: 0,
  2406. pure: false,
  2407. map: undefined,
  2408. helper(key) {
  2409. return `_${helperNameMap[key]}`;
  2410. },
  2411. push(code, node) {
  2412. context.code += code;
  2413. },
  2414. indent() {
  2415. newline(++context.indentLevel);
  2416. },
  2417. deindent(withoutNewLine = false) {
  2418. if (withoutNewLine) {
  2419. --context.indentLevel;
  2420. }
  2421. else {
  2422. newline(--context.indentLevel);
  2423. }
  2424. },
  2425. newline() {
  2426. newline(context.indentLevel);
  2427. }
  2428. };
  2429. function newline(n) {
  2430. context.push('\n' + ` `.repeat(n));
  2431. }
  2432. return context;
  2433. }
  2434. function generate(ast, options = {}) {
  2435. const context = createCodegenContext(ast, options);
  2436. if (options.onContextCreated)
  2437. options.onContextCreated(context);
  2438. const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
  2439. const hasHelpers = ast.helpers.length > 0;
  2440. const useWithBlock = !prefixIdentifiers && mode !== 'module';
  2441. // preambles
  2442. // in setup() inline mode, the preamble is generated in a sub context
  2443. // and returned separately.
  2444. const preambleContext = context;
  2445. {
  2446. genFunctionPreamble(ast, preambleContext);
  2447. }
  2448. // enter render function
  2449. const functionName = ssr ? `ssrRender` : `render`;
  2450. const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
  2451. const signature = args.join(', ');
  2452. {
  2453. push(`function ${functionName}(${signature}) {`);
  2454. }
  2455. indent();
  2456. if (useWithBlock) {
  2457. push(`with (_ctx) {`);
  2458. indent();
  2459. // function mode const declarations should be inside with block
  2460. // also they should be renamed to avoid collision with user properties
  2461. if (hasHelpers) {
  2462. push(`const { ${ast.helpers.map(aliasHelper).join(', ')} } = _Vue`);
  2463. push(`\n`);
  2464. newline();
  2465. }
  2466. }
  2467. // generate asset resolution statements
  2468. if (ast.components.length) {
  2469. genAssets(ast.components, 'component', context);
  2470. if (ast.directives.length || ast.temps > 0) {
  2471. newline();
  2472. }
  2473. }
  2474. if (ast.directives.length) {
  2475. genAssets(ast.directives, 'directive', context);
  2476. if (ast.temps > 0) {
  2477. newline();
  2478. }
  2479. }
  2480. if (ast.filters && ast.filters.length) {
  2481. newline();
  2482. genAssets(ast.filters, 'filter', context);
  2483. newline();
  2484. }
  2485. if (ast.temps > 0) {
  2486. push(`let `);
  2487. for (let i = 0; i < ast.temps; i++) {
  2488. push(`${i > 0 ? `, ` : ``}_temp${i}`);
  2489. }
  2490. }
  2491. if (ast.components.length || ast.directives.length || ast.temps) {
  2492. push(`\n`);
  2493. newline();
  2494. }
  2495. // generate the VNode tree expression
  2496. if (!ssr) {
  2497. push(`return `);
  2498. }
  2499. if (ast.codegenNode) {
  2500. genNode(ast.codegenNode, context);
  2501. }
  2502. else {
  2503. push(`null`);
  2504. }
  2505. if (useWithBlock) {
  2506. deindent();
  2507. push(`}`);
  2508. }
  2509. deindent();
  2510. push(`}`);
  2511. return {
  2512. ast,
  2513. code: context.code,
  2514. preamble: ``,
  2515. // SourceMapGenerator does have toJSON() method but it's not in the types
  2516. map: context.map ? context.map.toJSON() : undefined
  2517. };
  2518. }
  2519. function genFunctionPreamble(ast, context) {
  2520. const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName, ssrRuntimeModuleName } = context;
  2521. const VueBinding = runtimeGlobalName;
  2522. // Generate const declaration for helpers
  2523. // In prefix mode, we place the const declaration at top so it's done
  2524. // only once; But if we not prefixing, we place the declaration inside the
  2525. // with block so it doesn't incur the `in` check cost for every helper access.
  2526. if (ast.helpers.length > 0) {
  2527. {
  2528. // "with" mode.
  2529. // save Vue in a separate variable to avoid collision
  2530. push(`const _Vue = ${VueBinding}\n`);
  2531. // in "with" mode, helpers are declared inside the with block to avoid
  2532. // has check cost, but hoists are lifted out of the function - we need
  2533. // to provide the helper here.
  2534. if (ast.hoists.length) {
  2535. const staticHelpers = [
  2536. CREATE_VNODE,
  2537. CREATE_ELEMENT_VNODE,
  2538. CREATE_COMMENT,
  2539. CREATE_TEXT,
  2540. CREATE_STATIC
  2541. ]
  2542. .filter(helper => ast.helpers.includes(helper))
  2543. .map(aliasHelper)
  2544. .join(', ');
  2545. push(`const { ${staticHelpers} } = _Vue\n`);
  2546. }
  2547. }
  2548. }
  2549. genHoists(ast.hoists, context);
  2550. newline();
  2551. push(`return `);
  2552. }
  2553. function genAssets(assets, type, { helper, push, newline, isTS }) {
  2554. const resolver = helper(type === 'filter'
  2555. ? RESOLVE_FILTER
  2556. : type === 'component'
  2557. ? RESOLVE_COMPONENT
  2558. : RESOLVE_DIRECTIVE);
  2559. for (let i = 0; i < assets.length; i++) {
  2560. let id = assets[i];
  2561. // potential component implicit self-reference inferred from SFC filename
  2562. const maybeSelfReference = id.endsWith('__self');
  2563. if (maybeSelfReference) {
  2564. id = id.slice(0, -6);
  2565. }
  2566. push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}`);
  2567. if (i < assets.length - 1) {
  2568. newline();
  2569. }
  2570. }
  2571. }
  2572. function genHoists(hoists, context) {
  2573. if (!hoists.length) {
  2574. return;
  2575. }
  2576. context.pure = true;
  2577. const { push, newline, helper, scopeId, mode } = context;
  2578. newline();
  2579. for (let i = 0; i < hoists.length; i++) {
  2580. const exp = hoists[i];
  2581. if (exp) {
  2582. push(`const _hoisted_${i + 1} = ${``}`);
  2583. genNode(exp, context);
  2584. newline();
  2585. }
  2586. }
  2587. context.pure = false;
  2588. }
  2589. function isText$1(n) {
  2590. return (isString(n) ||
  2591. n.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
  2592. n.type === 2 /* NodeTypes.TEXT */ ||
  2593. n.type === 5 /* NodeTypes.INTERPOLATION */ ||
  2594. n.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */);
  2595. }
  2596. function genNodeListAsArray(nodes, context) {
  2597. const multilines = nodes.length > 3 ||
  2598. (nodes.some(n => isArray(n) || !isText$1(n)));
  2599. context.push(`[`);
  2600. multilines && context.indent();
  2601. genNodeList(nodes, context, multilines);
  2602. multilines && context.deindent();
  2603. context.push(`]`);
  2604. }
  2605. function genNodeList(nodes, context, multilines = false, comma = true) {
  2606. const { push, newline } = context;
  2607. for (let i = 0; i < nodes.length; i++) {
  2608. const node = nodes[i];
  2609. if (isString(node)) {
  2610. push(node);
  2611. }
  2612. else if (isArray(node)) {
  2613. genNodeListAsArray(node, context);
  2614. }
  2615. else {
  2616. genNode(node, context);
  2617. }
  2618. if (i < nodes.length - 1) {
  2619. if (multilines) {
  2620. comma && push(',');
  2621. newline();
  2622. }
  2623. else {
  2624. comma && push(', ');
  2625. }
  2626. }
  2627. }
  2628. }
  2629. function genNode(node, context) {
  2630. if (isString(node)) {
  2631. context.push(node);
  2632. return;
  2633. }
  2634. if (isSymbol(node)) {
  2635. context.push(context.helper(node));
  2636. return;
  2637. }
  2638. switch (node.type) {
  2639. case 1 /* NodeTypes.ELEMENT */:
  2640. case 9 /* NodeTypes.IF */:
  2641. case 11 /* NodeTypes.FOR */:
  2642. assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
  2643. `Apply appropriate transforms first.`);
  2644. genNode(node.codegenNode, context);
  2645. break;
  2646. case 2 /* NodeTypes.TEXT */:
  2647. genText(node, context);
  2648. break;
  2649. case 4 /* NodeTypes.SIMPLE_EXPRESSION */:
  2650. genExpression(node, context);
  2651. break;
  2652. case 5 /* NodeTypes.INTERPOLATION */:
  2653. genInterpolation(node, context);
  2654. break;
  2655. case 12 /* NodeTypes.TEXT_CALL */:
  2656. genNode(node.codegenNode, context);
  2657. break;
  2658. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  2659. genCompoundExpression(node, context);
  2660. break;
  2661. case 3 /* NodeTypes.COMMENT */:
  2662. genComment(node, context);
  2663. break;
  2664. case 13 /* NodeTypes.VNODE_CALL */:
  2665. genVNodeCall(node, context);
  2666. break;
  2667. case 14 /* NodeTypes.JS_CALL_EXPRESSION */:
  2668. genCallExpression(node, context);
  2669. break;
  2670. case 15 /* NodeTypes.JS_OBJECT_EXPRESSION */:
  2671. genObjectExpression(node, context);
  2672. break;
  2673. case 17 /* NodeTypes.JS_ARRAY_EXPRESSION */:
  2674. genArrayExpression(node, context);
  2675. break;
  2676. case 18 /* NodeTypes.JS_FUNCTION_EXPRESSION */:
  2677. genFunctionExpression(node, context);
  2678. break;
  2679. case 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */:
  2680. genConditionalExpression(node, context);
  2681. break;
  2682. case 20 /* NodeTypes.JS_CACHE_EXPRESSION */:
  2683. genCacheExpression(node, context);
  2684. break;
  2685. case 21 /* NodeTypes.JS_BLOCK_STATEMENT */:
  2686. genNodeList(node.body, context, true, false);
  2687. break;
  2688. // SSR only types
  2689. case 22 /* NodeTypes.JS_TEMPLATE_LITERAL */:
  2690. break;
  2691. case 23 /* NodeTypes.JS_IF_STATEMENT */:
  2692. break;
  2693. case 24 /* NodeTypes.JS_ASSIGNMENT_EXPRESSION */:
  2694. break;
  2695. case 25 /* NodeTypes.JS_SEQUENCE_EXPRESSION */:
  2696. break;
  2697. case 26 /* NodeTypes.JS_RETURN_STATEMENT */:
  2698. break;
  2699. /* istanbul ignore next */
  2700. case 10 /* NodeTypes.IF_BRANCH */:
  2701. // noop
  2702. break;
  2703. default:
  2704. {
  2705. assert(false, `unhandled codegen node type: ${node.type}`);
  2706. // make sure we exhaust all possible types
  2707. const exhaustiveCheck = node;
  2708. return exhaustiveCheck;
  2709. }
  2710. }
  2711. }
  2712. function genText(node, context) {
  2713. context.push(JSON.stringify(node.content), node);
  2714. }
  2715. function genExpression(node, context) {
  2716. const { content, isStatic } = node;
  2717. context.push(isStatic ? JSON.stringify(content) : content, node);
  2718. }
  2719. function genInterpolation(node, context) {
  2720. const { push, helper, pure } = context;
  2721. if (pure)
  2722. push(PURE_ANNOTATION);
  2723. push(`${helper(TO_DISPLAY_STRING)}(`);
  2724. genNode(node.content, context);
  2725. push(`)`);
  2726. }
  2727. function genCompoundExpression(node, context) {
  2728. for (let i = 0; i < node.children.length; i++) {
  2729. const child = node.children[i];
  2730. if (isString(child)) {
  2731. context.push(child);
  2732. }
  2733. else {
  2734. genNode(child, context);
  2735. }
  2736. }
  2737. }
  2738. function genExpressionAsPropertyKey(node, context) {
  2739. const { push } = context;
  2740. if (node.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) {
  2741. push(`[`);
  2742. genCompoundExpression(node, context);
  2743. push(`]`);
  2744. }
  2745. else if (node.isStatic) {
  2746. // only quote keys if necessary
  2747. const text = isSimpleIdentifier(node.content)
  2748. ? node.content
  2749. : JSON.stringify(node.content);
  2750. push(text, node);
  2751. }
  2752. else {
  2753. push(`[${node.content}]`, node);
  2754. }
  2755. }
  2756. function genComment(node, context) {
  2757. const { push, helper, pure } = context;
  2758. if (pure) {
  2759. push(PURE_ANNOTATION);
  2760. }
  2761. push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
  2762. }
  2763. function genVNodeCall(node, context) {
  2764. const { push, helper, pure } = context;
  2765. const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking, isComponent } = node;
  2766. if (directives) {
  2767. push(helper(WITH_DIRECTIVES) + `(`);
  2768. }
  2769. if (isBlock) {
  2770. push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
  2771. }
  2772. if (pure) {
  2773. push(PURE_ANNOTATION);
  2774. }
  2775. const callHelper = isBlock
  2776. ? getVNodeBlockHelper(context.inSSR, isComponent)
  2777. : getVNodeHelper(context.inSSR, isComponent);
  2778. push(helper(callHelper) + `(`, node);
  2779. genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
  2780. push(`)`);
  2781. if (isBlock) {
  2782. push(`)`);
  2783. }
  2784. if (directives) {
  2785. push(`, `);
  2786. genNode(directives, context);
  2787. push(`)`);
  2788. }
  2789. }
  2790. function genNullableArgs(args) {
  2791. let i = args.length;
  2792. while (i--) {
  2793. if (args[i] != null)
  2794. break;
  2795. }
  2796. return args.slice(0, i + 1).map(arg => arg || `null`);
  2797. }
  2798. // JavaScript
  2799. function genCallExpression(node, context) {
  2800. const { push, helper, pure } = context;
  2801. const callee = isString(node.callee) ? node.callee : helper(node.callee);
  2802. if (pure) {
  2803. push(PURE_ANNOTATION);
  2804. }
  2805. push(callee + `(`, node);
  2806. genNodeList(node.arguments, context);
  2807. push(`)`);
  2808. }
  2809. function genObjectExpression(node, context) {
  2810. const { push, indent, deindent, newline } = context;
  2811. const { properties } = node;
  2812. if (!properties.length) {
  2813. push(`{}`, node);
  2814. return;
  2815. }
  2816. const multilines = properties.length > 1 ||
  2817. (properties.some(p => p.value.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */));
  2818. push(multilines ? `{` : `{ `);
  2819. multilines && indent();
  2820. for (let i = 0; i < properties.length; i++) {
  2821. const { key, value } = properties[i];
  2822. // key
  2823. genExpressionAsPropertyKey(key, context);
  2824. push(`: `);
  2825. // value
  2826. genNode(value, context);
  2827. if (i < properties.length - 1) {
  2828. // will only reach this if it's multilines
  2829. push(`,`);
  2830. newline();
  2831. }
  2832. }
  2833. multilines && deindent();
  2834. push(multilines ? `}` : ` }`);
  2835. }
  2836. function genArrayExpression(node, context) {
  2837. genNodeListAsArray(node.elements, context);
  2838. }
  2839. function genFunctionExpression(node, context) {
  2840. const { push, indent, deindent } = context;
  2841. const { params, returns, body, newline, isSlot } = node;
  2842. if (isSlot) {
  2843. // wrap slot functions with owner context
  2844. push(`_${helperNameMap[WITH_CTX]}(`);
  2845. }
  2846. push(`(`, node);
  2847. if (isArray(params)) {
  2848. genNodeList(params, context);
  2849. }
  2850. else if (params) {
  2851. genNode(params, context);
  2852. }
  2853. push(`) => `);
  2854. if (newline || body) {
  2855. push(`{`);
  2856. indent();
  2857. }
  2858. if (returns) {
  2859. if (newline) {
  2860. push(`return `);
  2861. }
  2862. if (isArray(returns)) {
  2863. genNodeListAsArray(returns, context);
  2864. }
  2865. else {
  2866. genNode(returns, context);
  2867. }
  2868. }
  2869. else if (body) {
  2870. genNode(body, context);
  2871. }
  2872. if (newline || body) {
  2873. deindent();
  2874. push(`}`);
  2875. }
  2876. if (isSlot) {
  2877. if (node.isNonScopedSlot) {
  2878. push(`, undefined, true`);
  2879. }
  2880. push(`)`);
  2881. }
  2882. }
  2883. function genConditionalExpression(node, context) {
  2884. const { test, consequent, alternate, newline: needNewline } = node;
  2885. const { push, indent, deindent, newline } = context;
  2886. if (test.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  2887. const needsParens = !isSimpleIdentifier(test.content);
  2888. needsParens && push(`(`);
  2889. genExpression(test, context);
  2890. needsParens && push(`)`);
  2891. }
  2892. else {
  2893. push(`(`);
  2894. genNode(test, context);
  2895. push(`)`);
  2896. }
  2897. needNewline && indent();
  2898. context.indentLevel++;
  2899. needNewline || push(` `);
  2900. push(`? `);
  2901. genNode(consequent, context);
  2902. context.indentLevel--;
  2903. needNewline && newline();
  2904. needNewline || push(` `);
  2905. push(`: `);
  2906. const isNested = alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */;
  2907. if (!isNested) {
  2908. context.indentLevel++;
  2909. }
  2910. genNode(alternate, context);
  2911. if (!isNested) {
  2912. context.indentLevel--;
  2913. }
  2914. needNewline && deindent(true /* without newline */);
  2915. }
  2916. function genCacheExpression(node, context) {
  2917. const { push, helper, indent, deindent, newline } = context;
  2918. push(`_cache[${node.index}] || (`);
  2919. if (node.isVNode) {
  2920. indent();
  2921. push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
  2922. newline();
  2923. }
  2924. push(`_cache[${node.index}] = `);
  2925. genNode(node.value, context);
  2926. if (node.isVNode) {
  2927. push(`,`);
  2928. newline();
  2929. push(`${helper(SET_BLOCK_TRACKING)}(1),`);
  2930. newline();
  2931. push(`_cache[${node.index}]`);
  2932. deindent();
  2933. }
  2934. push(`)`);
  2935. }
  2936. function walkIdentifiers(root, onIdentifier, includeAll = false, parentStack = [], knownIds = Object.create(null)) {
  2937. {
  2938. return;
  2939. }
  2940. }
  2941. function isReferencedIdentifier(id, parent, parentStack) {
  2942. {
  2943. return false;
  2944. }
  2945. }
  2946. function isInDestructureAssignment(parent, parentStack) {
  2947. if (parent &&
  2948. (parent.type === 'ObjectProperty' || parent.type === 'ArrayPattern')) {
  2949. let i = parentStack.length;
  2950. while (i--) {
  2951. const p = parentStack[i];
  2952. if (p.type === 'AssignmentExpression') {
  2953. return true;
  2954. }
  2955. else if (p.type !== 'ObjectProperty' && !p.type.endsWith('Pattern')) {
  2956. break;
  2957. }
  2958. }
  2959. }
  2960. return false;
  2961. }
  2962. function walkFunctionParams(node, onIdent) {
  2963. for (const p of node.params) {
  2964. for (const id of extractIdentifiers(p)) {
  2965. onIdent(id);
  2966. }
  2967. }
  2968. }
  2969. function walkBlockDeclarations(block, onIdent) {
  2970. for (const stmt of block.body) {
  2971. if (stmt.type === 'VariableDeclaration') {
  2972. if (stmt.declare)
  2973. continue;
  2974. for (const decl of stmt.declarations) {
  2975. for (const id of extractIdentifiers(decl.id)) {
  2976. onIdent(id);
  2977. }
  2978. }
  2979. }
  2980. else if (stmt.type === 'FunctionDeclaration' ||
  2981. stmt.type === 'ClassDeclaration') {
  2982. if (stmt.declare || !stmt.id)
  2983. continue;
  2984. onIdent(stmt.id);
  2985. }
  2986. }
  2987. }
  2988. function extractIdentifiers(param, nodes = []) {
  2989. switch (param.type) {
  2990. case 'Identifier':
  2991. nodes.push(param);
  2992. break;
  2993. case 'MemberExpression':
  2994. let object = param;
  2995. while (object.type === 'MemberExpression') {
  2996. object = object.object;
  2997. }
  2998. nodes.push(object);
  2999. break;
  3000. case 'ObjectPattern':
  3001. for (const prop of param.properties) {
  3002. if (prop.type === 'RestElement') {
  3003. extractIdentifiers(prop.argument, nodes);
  3004. }
  3005. else {
  3006. extractIdentifiers(prop.value, nodes);
  3007. }
  3008. }
  3009. break;
  3010. case 'ArrayPattern':
  3011. param.elements.forEach(element => {
  3012. if (element)
  3013. extractIdentifiers(element, nodes);
  3014. });
  3015. break;
  3016. case 'RestElement':
  3017. extractIdentifiers(param.argument, nodes);
  3018. break;
  3019. case 'AssignmentPattern':
  3020. extractIdentifiers(param.left, nodes);
  3021. break;
  3022. }
  3023. return nodes;
  3024. }
  3025. const isFunctionType = (node) => {
  3026. return /Function(?:Expression|Declaration)$|Method$/.test(node.type);
  3027. };
  3028. const isStaticProperty = (node) => node &&
  3029. (node.type === 'ObjectProperty' || node.type === 'ObjectMethod') &&
  3030. !node.computed;
  3031. const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node;
  3032. // these keywords should not appear inside expressions, but operators like
  3033. // typeof, instanceof and in are allowed
  3034. const prohibitedKeywordRE = new RegExp('\\b' +
  3035. ('do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
  3036. 'super,throw,while,yield,delete,export,import,return,switch,default,' +
  3037. 'extends,finally,continue,debugger,function,arguments,typeof,void')
  3038. .split(',')
  3039. .join('\\b|\\b') +
  3040. '\\b');
  3041. // strip strings in expressions
  3042. const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
  3043. /**
  3044. * Validate a non-prefixed expression.
  3045. * This is only called when using the in-browser runtime compiler since it
  3046. * doesn't prefix expressions.
  3047. */
  3048. function validateBrowserExpression(node, context, asParams = false, asRawStatements = false) {
  3049. const exp = node.content;
  3050. // empty expressions are validated per-directive since some directives
  3051. // do allow empty expressions.
  3052. if (!exp.trim()) {
  3053. return;
  3054. }
  3055. try {
  3056. new Function(asRawStatements
  3057. ? ` ${exp} `
  3058. : `return ${asParams ? `(${exp}) => {}` : `(${exp})`}`);
  3059. }
  3060. catch (e) {
  3061. let message = e.message;
  3062. const keywordMatch = exp
  3063. .replace(stripStringRE, '')
  3064. .match(prohibitedKeywordRE);
  3065. if (keywordMatch) {
  3066. message = `avoid using JavaScript keyword as property name: "${keywordMatch[0]}"`;
  3067. }
  3068. context.onError(createCompilerError(45 /* ErrorCodes.X_INVALID_EXPRESSION */, node.loc, undefined, message));
  3069. }
  3070. }
  3071. const transformExpression = (node, context) => {
  3072. if (node.type === 5 /* NodeTypes.INTERPOLATION */) {
  3073. node.content = processExpression(node.content, context);
  3074. }
  3075. else if (node.type === 1 /* NodeTypes.ELEMENT */) {
  3076. // handle directives on element
  3077. for (let i = 0; i < node.props.length; i++) {
  3078. const dir = node.props[i];
  3079. // do not process for v-on & v-for since they are special handled
  3080. if (dir.type === 7 /* NodeTypes.DIRECTIVE */ && dir.name !== 'for') {
  3081. const exp = dir.exp;
  3082. const arg = dir.arg;
  3083. // do not process exp if this is v-on:arg - we need special handling
  3084. // for wrapping inline statements.
  3085. if (exp &&
  3086. exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  3087. !(dir.name === 'on' && arg)) {
  3088. dir.exp = processExpression(exp, context,
  3089. // slot args must be processed as function params
  3090. dir.name === 'slot');
  3091. }
  3092. if (arg && arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && !arg.isStatic) {
  3093. dir.arg = processExpression(arg, context);
  3094. }
  3095. }
  3096. }
  3097. }
  3098. };
  3099. // Important: since this function uses Node.js only dependencies, it should
  3100. // always be used with a leading !true check so that it can be
  3101. // tree-shaken from the browser build.
  3102. function processExpression(node, context,
  3103. // some expressions like v-slot props & v-for aliases should be parsed as
  3104. // function params
  3105. asParams = false,
  3106. // v-on handler values may contain multiple statements
  3107. asRawStatements = false, localVars = Object.create(context.identifiers)) {
  3108. {
  3109. {
  3110. // simple in-browser validation (same logic in 2.x)
  3111. validateBrowserExpression(node, context, asParams, asRawStatements);
  3112. }
  3113. return node;
  3114. }
  3115. }
  3116. function stringifyExpression(exp) {
  3117. if (isString(exp)) {
  3118. return exp;
  3119. }
  3120. else if (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  3121. return exp.content;
  3122. }
  3123. else {
  3124. return exp.children
  3125. .map(stringifyExpression)
  3126. .join('');
  3127. }
  3128. }
  3129. const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
  3130. return processIf(node, dir, context, (ifNode, branch, isRoot) => {
  3131. // #1587: We need to dynamically increment the key based on the current
  3132. // node's sibling nodes, since chained v-if/else branches are
  3133. // rendered at the same depth
  3134. const siblings = context.parent.children;
  3135. let i = siblings.indexOf(ifNode);
  3136. let key = 0;
  3137. while (i-- >= 0) {
  3138. const sibling = siblings[i];
  3139. if (sibling && sibling.type === 9 /* NodeTypes.IF */) {
  3140. key += sibling.branches.length;
  3141. }
  3142. }
  3143. // Exit callback. Complete the codegenNode when all children have been
  3144. // transformed.
  3145. return () => {
  3146. if (isRoot) {
  3147. ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
  3148. }
  3149. else {
  3150. // attach this branch's codegen node to the v-if root.
  3151. const parentCondition = getParentCondition(ifNode.codegenNode);
  3152. parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
  3153. }
  3154. };
  3155. });
  3156. });
  3157. // target-agnostic transform used for both Client and SSR
  3158. function processIf(node, dir, context, processCodegen) {
  3159. if (dir.name !== 'else' &&
  3160. (!dir.exp || !dir.exp.content.trim())) {
  3161. const loc = dir.exp ? dir.exp.loc : node.loc;
  3162. context.onError(createCompilerError(28 /* ErrorCodes.X_V_IF_NO_EXPRESSION */, dir.loc));
  3163. dir.exp = createSimpleExpression(`true`, false, loc);
  3164. }
  3165. if (dir.exp) {
  3166. validateBrowserExpression(dir.exp, context);
  3167. }
  3168. if (dir.name === 'if') {
  3169. const branch = createIfBranch(node, dir);
  3170. const ifNode = {
  3171. type: 9 /* NodeTypes.IF */,
  3172. loc: node.loc,
  3173. branches: [branch]
  3174. };
  3175. context.replaceNode(ifNode);
  3176. if (processCodegen) {
  3177. return processCodegen(ifNode, branch, true);
  3178. }
  3179. }
  3180. else {
  3181. // locate the adjacent v-if
  3182. const siblings = context.parent.children;
  3183. const comments = [];
  3184. let i = siblings.indexOf(node);
  3185. while (i-- >= -1) {
  3186. const sibling = siblings[i];
  3187. if (sibling && sibling.type === 3 /* NodeTypes.COMMENT */) {
  3188. context.removeNode(sibling);
  3189. comments.unshift(sibling);
  3190. continue;
  3191. }
  3192. if (sibling &&
  3193. sibling.type === 2 /* NodeTypes.TEXT */ &&
  3194. !sibling.content.trim().length) {
  3195. context.removeNode(sibling);
  3196. continue;
  3197. }
  3198. if (sibling && sibling.type === 9 /* NodeTypes.IF */) {
  3199. // Check if v-else was followed by v-else-if
  3200. if (dir.name === 'else-if' &&
  3201. sibling.branches[sibling.branches.length - 1].condition === undefined) {
  3202. context.onError(createCompilerError(30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  3203. }
  3204. // move the node to the if node's branches
  3205. context.removeNode();
  3206. const branch = createIfBranch(node, dir);
  3207. if (comments.length &&
  3208. // #3619 ignore comments if the v-if is direct child of <transition>
  3209. !(context.parent &&
  3210. context.parent.type === 1 /* NodeTypes.ELEMENT */ &&
  3211. isBuiltInType(context.parent.tag, 'transition'))) {
  3212. branch.children = [...comments, ...branch.children];
  3213. }
  3214. // check if user is forcing same key on different branches
  3215. {
  3216. const key = branch.userKey;
  3217. if (key) {
  3218. sibling.branches.forEach(({ userKey }) => {
  3219. if (isSameKey(userKey, key)) {
  3220. context.onError(createCompilerError(29 /* ErrorCodes.X_V_IF_SAME_KEY */, branch.userKey.loc));
  3221. }
  3222. });
  3223. }
  3224. }
  3225. sibling.branches.push(branch);
  3226. const onExit = processCodegen && processCodegen(sibling, branch, false);
  3227. // since the branch was removed, it will not be traversed.
  3228. // make sure to traverse here.
  3229. traverseNode(branch, context);
  3230. // call on exit
  3231. if (onExit)
  3232. onExit();
  3233. // make sure to reset currentNode after traversal to indicate this
  3234. // node has been removed.
  3235. context.currentNode = null;
  3236. }
  3237. else {
  3238. context.onError(createCompilerError(30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  3239. }
  3240. break;
  3241. }
  3242. }
  3243. }
  3244. function createIfBranch(node, dir) {
  3245. const isTemplateIf = node.tagType === 3 /* ElementTypes.TEMPLATE */;
  3246. return {
  3247. type: 10 /* NodeTypes.IF_BRANCH */,
  3248. loc: node.loc,
  3249. condition: dir.name === 'else' ? undefined : dir.exp,
  3250. children: isTemplateIf && !findDir(node, 'for') ? node.children : [node],
  3251. userKey: findProp(node, `key`),
  3252. isTemplateIf
  3253. };
  3254. }
  3255. function createCodegenNodeForBranch(branch, keyIndex, context) {
  3256. if (branch.condition) {
  3257. return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
  3258. // make sure to pass in asBlock: true so that the comment node call
  3259. // closes the current block.
  3260. createCallExpression(context.helper(CREATE_COMMENT), [
  3261. '"v-if"' ,
  3262. 'true'
  3263. ]));
  3264. }
  3265. else {
  3266. return createChildrenCodegenNode(branch, keyIndex, context);
  3267. }
  3268. }
  3269. function createChildrenCodegenNode(branch, keyIndex, context) {
  3270. const { helper } = context;
  3271. const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* ConstantTypes.CAN_HOIST */));
  3272. const { children } = branch;
  3273. const firstChild = children[0];
  3274. const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* NodeTypes.ELEMENT */;
  3275. if (needFragmentWrapper) {
  3276. if (children.length === 1 && firstChild.type === 11 /* NodeTypes.FOR */) {
  3277. // optimize away nested fragments when child is a ForNode
  3278. const vnodeCall = firstChild.codegenNode;
  3279. injectProp(vnodeCall, keyProperty, context);
  3280. return vnodeCall;
  3281. }
  3282. else {
  3283. let patchFlag = 64 /* PatchFlags.STABLE_FRAGMENT */;
  3284. let patchFlagText = PatchFlagNames[64 /* PatchFlags.STABLE_FRAGMENT */];
  3285. // check if the fragment actually contains a single valid child with
  3286. // the rest being comments
  3287. if (!branch.isTemplateIf &&
  3288. children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */).length === 1) {
  3289. patchFlag |= 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */;
  3290. patchFlagText += `, ${PatchFlagNames[2048 /* PatchFlags.DEV_ROOT_FRAGMENT */]}`;
  3291. }
  3292. return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, false, false /* isComponent */, branch.loc);
  3293. }
  3294. }
  3295. else {
  3296. const ret = firstChild.codegenNode;
  3297. const vnodeCall = getMemoedVNodeCall(ret);
  3298. // Change createVNode to createBlock.
  3299. if (vnodeCall.type === 13 /* NodeTypes.VNODE_CALL */) {
  3300. makeBlock(vnodeCall, context);
  3301. }
  3302. // inject branch key
  3303. injectProp(vnodeCall, keyProperty, context);
  3304. return ret;
  3305. }
  3306. }
  3307. function isSameKey(a, b) {
  3308. if (!a || a.type !== b.type) {
  3309. return false;
  3310. }
  3311. if (a.type === 6 /* NodeTypes.ATTRIBUTE */) {
  3312. if (a.value.content !== b.value.content) {
  3313. return false;
  3314. }
  3315. }
  3316. else {
  3317. // directive
  3318. const exp = a.exp;
  3319. const branchExp = b.exp;
  3320. if (exp.type !== branchExp.type) {
  3321. return false;
  3322. }
  3323. if (exp.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
  3324. exp.isStatic !== branchExp.isStatic ||
  3325. exp.content !== branchExp.content) {
  3326. return false;
  3327. }
  3328. }
  3329. return true;
  3330. }
  3331. function getParentCondition(node) {
  3332. while (true) {
  3333. if (node.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */) {
  3334. if (node.alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */) {
  3335. node = node.alternate;
  3336. }
  3337. else {
  3338. return node;
  3339. }
  3340. }
  3341. else if (node.type === 20 /* NodeTypes.JS_CACHE_EXPRESSION */) {
  3342. node = node.value;
  3343. }
  3344. }
  3345. }
  3346. const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
  3347. const { helper, removeHelper } = context;
  3348. return processFor(node, dir, context, forNode => {
  3349. // create the loop render function expression now, and add the
  3350. // iterator on exit after all children have been traversed
  3351. const renderExp = createCallExpression(helper(RENDER_LIST), [
  3352. forNode.source
  3353. ]);
  3354. const isTemplate = isTemplateNode(node);
  3355. const memo = findDir(node, 'memo');
  3356. const keyProp = findProp(node, `key`);
  3357. const keyExp = keyProp &&
  3358. (keyProp.type === 6 /* NodeTypes.ATTRIBUTE */
  3359. ? createSimpleExpression(keyProp.value.content, true)
  3360. : keyProp.exp);
  3361. const keyProperty = keyProp ? createObjectProperty(`key`, keyExp) : null;
  3362. const isStableFragment = forNode.source.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  3363. forNode.source.constType > 0 /* ConstantTypes.NOT_CONSTANT */;
  3364. const fragmentFlag = isStableFragment
  3365. ? 64 /* PatchFlags.STABLE_FRAGMENT */
  3366. : keyProp
  3367. ? 128 /* PatchFlags.KEYED_FRAGMENT */
  3368. : 256 /* PatchFlags.UNKEYED_FRAGMENT */;
  3369. forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
  3370. (` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, false /* isComponent */, node.loc);
  3371. return () => {
  3372. // finish the codegen now that all children have been traversed
  3373. let childBlock;
  3374. const { children } = forNode;
  3375. // check <template v-for> key placement
  3376. if (isTemplate) {
  3377. node.children.some(c => {
  3378. if (c.type === 1 /* NodeTypes.ELEMENT */) {
  3379. const key = findProp(c, 'key');
  3380. if (key) {
  3381. context.onError(createCompilerError(33 /* ErrorCodes.X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
  3382. return true;
  3383. }
  3384. }
  3385. });
  3386. }
  3387. const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* NodeTypes.ELEMENT */;
  3388. const slotOutlet = isSlotOutlet(node)
  3389. ? node
  3390. : isTemplate &&
  3391. node.children.length === 1 &&
  3392. isSlotOutlet(node.children[0])
  3393. ? node.children[0] // api-extractor somehow fails to infer this
  3394. : null;
  3395. if (slotOutlet) {
  3396. // <slot v-for="..."> or <template v-for="..."><slot/></template>
  3397. childBlock = slotOutlet.codegenNode;
  3398. if (isTemplate && keyProperty) {
  3399. // <template v-for="..." :key="..."><slot/></template>
  3400. // we need to inject the key to the renderSlot() call.
  3401. // the props for renderSlot is passed as the 3rd argument.
  3402. injectProp(childBlock, keyProperty, context);
  3403. }
  3404. }
  3405. else if (needFragmentWrapper) {
  3406. // <template v-for="..."> with text or multi-elements
  3407. // should generate a fragment block for each loop
  3408. childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* PatchFlags.STABLE_FRAGMENT */ +
  3409. (` /* ${PatchFlagNames[64 /* PatchFlags.STABLE_FRAGMENT */]} */`
  3410. ), undefined, undefined, true, undefined, false /* isComponent */);
  3411. }
  3412. else {
  3413. // Normal element v-for. Directly use the child's codegenNode
  3414. // but mark it as a block.
  3415. childBlock = children[0]
  3416. .codegenNode;
  3417. if (isTemplate && keyProperty) {
  3418. injectProp(childBlock, keyProperty, context);
  3419. }
  3420. if (childBlock.isBlock !== !isStableFragment) {
  3421. if (childBlock.isBlock) {
  3422. // switch from block to vnode
  3423. removeHelper(OPEN_BLOCK);
  3424. removeHelper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
  3425. }
  3426. else {
  3427. // switch from vnode to block
  3428. removeHelper(getVNodeHelper(context.inSSR, childBlock.isComponent));
  3429. }
  3430. }
  3431. childBlock.isBlock = !isStableFragment;
  3432. if (childBlock.isBlock) {
  3433. helper(OPEN_BLOCK);
  3434. helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
  3435. }
  3436. else {
  3437. helper(getVNodeHelper(context.inSSR, childBlock.isComponent));
  3438. }
  3439. }
  3440. if (memo) {
  3441. const loop = createFunctionExpression(createForLoopParams(forNode.parseResult, [
  3442. createSimpleExpression(`_cached`)
  3443. ]));
  3444. loop.body = createBlockStatement([
  3445. createCompoundExpression([`const _memo = (`, memo.exp, `)`]),
  3446. createCompoundExpression([
  3447. `if (_cached`,
  3448. ...(keyExp ? [` && _cached.key === `, keyExp] : []),
  3449. ` && ${context.helperString(IS_MEMO_SAME)}(_cached, _memo)) return _cached`
  3450. ]),
  3451. createCompoundExpression([`const _item = `, childBlock]),
  3452. createSimpleExpression(`_item.memo = _memo`),
  3453. createSimpleExpression(`return _item`)
  3454. ]);
  3455. renderExp.arguments.push(loop, createSimpleExpression(`_cache`), createSimpleExpression(String(context.cached++)));
  3456. }
  3457. else {
  3458. renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
  3459. }
  3460. };
  3461. });
  3462. });
  3463. // target-agnostic transform used for both Client and SSR
  3464. function processFor(node, dir, context, processCodegen) {
  3465. if (!dir.exp) {
  3466. context.onError(createCompilerError(31 /* ErrorCodes.X_V_FOR_NO_EXPRESSION */, dir.loc));
  3467. return;
  3468. }
  3469. const parseResult = parseForExpression(
  3470. // can only be simple expression because vFor transform is applied
  3471. // before expression transform.
  3472. dir.exp, context);
  3473. if (!parseResult) {
  3474. context.onError(createCompilerError(32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
  3475. return;
  3476. }
  3477. const { addIdentifiers, removeIdentifiers, scopes } = context;
  3478. const { source, value, key, index } = parseResult;
  3479. const forNode = {
  3480. type: 11 /* NodeTypes.FOR */,
  3481. loc: dir.loc,
  3482. source,
  3483. valueAlias: value,
  3484. keyAlias: key,
  3485. objectIndexAlias: index,
  3486. parseResult,
  3487. children: isTemplateNode(node) ? node.children : [node]
  3488. };
  3489. context.replaceNode(forNode);
  3490. // bookkeeping
  3491. scopes.vFor++;
  3492. const onExit = processCodegen && processCodegen(forNode);
  3493. return () => {
  3494. scopes.vFor--;
  3495. if (onExit)
  3496. onExit();
  3497. };
  3498. }
  3499. const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
  3500. // This regex doesn't cover the case if key or index aliases have destructuring,
  3501. // but those do not make sense in the first place, so this works in practice.
  3502. const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
  3503. const stripParensRE = /^\(|\)$/g;
  3504. function parseForExpression(input, context) {
  3505. const loc = input.loc;
  3506. const exp = input.content;
  3507. const inMatch = exp.match(forAliasRE);
  3508. if (!inMatch)
  3509. return;
  3510. const [, LHS, RHS] = inMatch;
  3511. const result = {
  3512. source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
  3513. value: undefined,
  3514. key: undefined,
  3515. index: undefined
  3516. };
  3517. {
  3518. validateBrowserExpression(result.source, context);
  3519. }
  3520. let valueContent = LHS.trim().replace(stripParensRE, '').trim();
  3521. const trimmedOffset = LHS.indexOf(valueContent);
  3522. const iteratorMatch = valueContent.match(forIteratorRE);
  3523. if (iteratorMatch) {
  3524. valueContent = valueContent.replace(forIteratorRE, '').trim();
  3525. const keyContent = iteratorMatch[1].trim();
  3526. let keyOffset;
  3527. if (keyContent) {
  3528. keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
  3529. result.key = createAliasExpression(loc, keyContent, keyOffset);
  3530. {
  3531. validateBrowserExpression(result.key, context, true);
  3532. }
  3533. }
  3534. if (iteratorMatch[2]) {
  3535. const indexContent = iteratorMatch[2].trim();
  3536. if (indexContent) {
  3537. result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
  3538. ? keyOffset + keyContent.length
  3539. : trimmedOffset + valueContent.length));
  3540. {
  3541. validateBrowserExpression(result.index, context, true);
  3542. }
  3543. }
  3544. }
  3545. }
  3546. if (valueContent) {
  3547. result.value = createAliasExpression(loc, valueContent, trimmedOffset);
  3548. {
  3549. validateBrowserExpression(result.value, context, true);
  3550. }
  3551. }
  3552. return result;
  3553. }
  3554. function createAliasExpression(range, content, offset) {
  3555. return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
  3556. }
  3557. function createForLoopParams({ value, key, index }, memoArgs = []) {
  3558. return createParamsList([value, key, index, ...memoArgs]);
  3559. }
  3560. function createParamsList(args) {
  3561. let i = args.length;
  3562. while (i--) {
  3563. if (args[i])
  3564. break;
  3565. }
  3566. return args
  3567. .slice(0, i + 1)
  3568. .map((arg, i) => arg || createSimpleExpression(`_`.repeat(i + 1), false));
  3569. }
  3570. const defaultFallback = createSimpleExpression(`undefined`, false);
  3571. // A NodeTransform that:
  3572. // 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
  3573. // by transformExpression. This is only applied in non-browser builds with
  3574. // { prefixIdentifiers: true }.
  3575. // 2. Track v-slot depths so that we know a slot is inside another slot.
  3576. // Note the exit callback is executed before buildSlots() on the same node,
  3577. // so only nested slots see positive numbers.
  3578. const trackSlotScopes = (node, context) => {
  3579. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  3580. (node.tagType === 1 /* ElementTypes.COMPONENT */ ||
  3581. node.tagType === 3 /* ElementTypes.TEMPLATE */)) {
  3582. // We are only checking non-empty v-slot here
  3583. // since we only care about slots that introduce scope variables.
  3584. const vSlot = findDir(node, 'slot');
  3585. if (vSlot) {
  3586. vSlot.exp;
  3587. context.scopes.vSlot++;
  3588. return () => {
  3589. context.scopes.vSlot--;
  3590. };
  3591. }
  3592. }
  3593. };
  3594. // A NodeTransform that tracks scope identifiers for scoped slots with v-for.
  3595. // This transform is only applied in non-browser builds with { prefixIdentifiers: true }
  3596. const trackVForSlotScopes = (node, context) => {
  3597. let vFor;
  3598. if (isTemplateNode(node) &&
  3599. node.props.some(isVSlot) &&
  3600. (vFor = findDir(node, 'for'))) {
  3601. const result = (vFor.parseResult = parseForExpression(vFor.exp, context));
  3602. if (result) {
  3603. const { value, key, index } = result;
  3604. const { addIdentifiers, removeIdentifiers } = context;
  3605. value && addIdentifiers(value);
  3606. key && addIdentifiers(key);
  3607. index && addIdentifiers(index);
  3608. return () => {
  3609. value && removeIdentifiers(value);
  3610. key && removeIdentifiers(key);
  3611. index && removeIdentifiers(index);
  3612. };
  3613. }
  3614. }
  3615. };
  3616. const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
  3617. // Instead of being a DirectiveTransform, v-slot processing is called during
  3618. // transformElement to build the slots object for a component.
  3619. function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
  3620. context.helper(WITH_CTX);
  3621. const { children, loc } = node;
  3622. const slotsProperties = [];
  3623. const dynamicSlots = [];
  3624. // If the slot is inside a v-for or another v-slot, force it to be dynamic
  3625. // since it likely uses a scope variable.
  3626. let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
  3627. // 1. Check for slot with slotProps on component itself.
  3628. // <Comp v-slot="{ prop }"/>
  3629. const onComponentSlot = findDir(node, 'slot', true);
  3630. if (onComponentSlot) {
  3631. const { arg, exp } = onComponentSlot;
  3632. if (arg && !isStaticExp(arg)) {
  3633. hasDynamicSlots = true;
  3634. }
  3635. slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
  3636. }
  3637. // 2. Iterate through children and check for template slots
  3638. // <template v-slot:foo="{ prop }">
  3639. let hasTemplateSlots = false;
  3640. let hasNamedDefaultSlot = false;
  3641. const implicitDefaultChildren = [];
  3642. const seenSlotNames = new Set();
  3643. let conditionalBranchIndex = 0;
  3644. for (let i = 0; i < children.length; i++) {
  3645. const slotElement = children[i];
  3646. let slotDir;
  3647. if (!isTemplateNode(slotElement) ||
  3648. !(slotDir = findDir(slotElement, 'slot', true))) {
  3649. // not a <template v-slot>, skip.
  3650. if (slotElement.type !== 3 /* NodeTypes.COMMENT */) {
  3651. implicitDefaultChildren.push(slotElement);
  3652. }
  3653. continue;
  3654. }
  3655. if (onComponentSlot) {
  3656. // already has on-component slot - this is incorrect usage.
  3657. context.onError(createCompilerError(37 /* ErrorCodes.X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
  3658. break;
  3659. }
  3660. hasTemplateSlots = true;
  3661. const { children: slotChildren, loc: slotLoc } = slotElement;
  3662. const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
  3663. // check if name is dynamic.
  3664. let staticSlotName;
  3665. if (isStaticExp(slotName)) {
  3666. staticSlotName = slotName ? slotName.content : `default`;
  3667. }
  3668. else {
  3669. hasDynamicSlots = true;
  3670. }
  3671. const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
  3672. // check if this slot is conditional (v-if/v-for)
  3673. let vIf;
  3674. let vElse;
  3675. let vFor;
  3676. if ((vIf = findDir(slotElement, 'if'))) {
  3677. hasDynamicSlots = true;
  3678. dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++), defaultFallback));
  3679. }
  3680. else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
  3681. // find adjacent v-if
  3682. let j = i;
  3683. let prev;
  3684. while (j--) {
  3685. prev = children[j];
  3686. if (prev.type !== 3 /* NodeTypes.COMMENT */) {
  3687. break;
  3688. }
  3689. }
  3690. if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
  3691. // remove node
  3692. children.splice(i, 1);
  3693. i--;
  3694. // attach this slot to previous conditional
  3695. let conditional = dynamicSlots[dynamicSlots.length - 1];
  3696. while (conditional.alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */) {
  3697. conditional = conditional.alternate;
  3698. }
  3699. conditional.alternate = vElse.exp
  3700. ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++), defaultFallback)
  3701. : buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++);
  3702. }
  3703. else {
  3704. context.onError(createCompilerError(30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
  3705. }
  3706. }
  3707. else if ((vFor = findDir(slotElement, 'for'))) {
  3708. hasDynamicSlots = true;
  3709. const parseResult = vFor.parseResult ||
  3710. parseForExpression(vFor.exp, context);
  3711. if (parseResult) {
  3712. // Render the dynamic slots as an array and add it to the createSlot()
  3713. // args. The runtime knows how to handle it appropriately.
  3714. dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
  3715. parseResult.source,
  3716. createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
  3717. ]));
  3718. }
  3719. else {
  3720. context.onError(createCompilerError(32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
  3721. }
  3722. }
  3723. else {
  3724. // check duplicate static names
  3725. if (staticSlotName) {
  3726. if (seenSlotNames.has(staticSlotName)) {
  3727. context.onError(createCompilerError(38 /* ErrorCodes.X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
  3728. continue;
  3729. }
  3730. seenSlotNames.add(staticSlotName);
  3731. if (staticSlotName === 'default') {
  3732. hasNamedDefaultSlot = true;
  3733. }
  3734. }
  3735. slotsProperties.push(createObjectProperty(slotName, slotFunction));
  3736. }
  3737. }
  3738. if (!onComponentSlot) {
  3739. const buildDefaultSlotProperty = (props, children) => {
  3740. const fn = buildSlotFn(props, children, loc);
  3741. if (context.compatConfig) {
  3742. fn.isNonScopedSlot = true;
  3743. }
  3744. return createObjectProperty(`default`, fn);
  3745. };
  3746. if (!hasTemplateSlots) {
  3747. // implicit default slot (on component)
  3748. slotsProperties.push(buildDefaultSlotProperty(undefined, children));
  3749. }
  3750. else if (implicitDefaultChildren.length &&
  3751. // #3766
  3752. // with whitespace: 'preserve', whitespaces between slots will end up in
  3753. // implicitDefaultChildren. Ignore if all implicit children are whitespaces.
  3754. implicitDefaultChildren.some(node => isNonWhitespaceContent(node))) {
  3755. // implicit default slot (mixed with named slots)
  3756. if (hasNamedDefaultSlot) {
  3757. context.onError(createCompilerError(39 /* ErrorCodes.X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
  3758. }
  3759. else {
  3760. slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
  3761. }
  3762. }
  3763. }
  3764. const slotFlag = hasDynamicSlots
  3765. ? 2 /* SlotFlags.DYNAMIC */
  3766. : hasForwardedSlots(node.children)
  3767. ? 3 /* SlotFlags.FORWARDED */
  3768. : 1 /* SlotFlags.STABLE */;
  3769. let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
  3770. // 2 = compiled but dynamic = can skip normalization, but must run diff
  3771. // 1 = compiled and static = can skip normalization AND diff as optimized
  3772. createSimpleExpression(slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
  3773. if (dynamicSlots.length) {
  3774. slots = createCallExpression(context.helper(CREATE_SLOTS), [
  3775. slots,
  3776. createArrayExpression(dynamicSlots)
  3777. ]);
  3778. }
  3779. return {
  3780. slots,
  3781. hasDynamicSlots
  3782. };
  3783. }
  3784. function buildDynamicSlot(name, fn, index) {
  3785. const props = [
  3786. createObjectProperty(`name`, name),
  3787. createObjectProperty(`fn`, fn)
  3788. ];
  3789. if (index != null) {
  3790. props.push(createObjectProperty(`key`, createSimpleExpression(String(index), true)));
  3791. }
  3792. return createObjectExpression(props);
  3793. }
  3794. function hasForwardedSlots(children) {
  3795. for (let i = 0; i < children.length; i++) {
  3796. const child = children[i];
  3797. switch (child.type) {
  3798. case 1 /* NodeTypes.ELEMENT */:
  3799. if (child.tagType === 2 /* ElementTypes.SLOT */ ||
  3800. hasForwardedSlots(child.children)) {
  3801. return true;
  3802. }
  3803. break;
  3804. case 9 /* NodeTypes.IF */:
  3805. if (hasForwardedSlots(child.branches))
  3806. return true;
  3807. break;
  3808. case 10 /* NodeTypes.IF_BRANCH */:
  3809. case 11 /* NodeTypes.FOR */:
  3810. if (hasForwardedSlots(child.children))
  3811. return true;
  3812. break;
  3813. }
  3814. }
  3815. return false;
  3816. }
  3817. function isNonWhitespaceContent(node) {
  3818. if (node.type !== 2 /* NodeTypes.TEXT */ && node.type !== 12 /* NodeTypes.TEXT_CALL */)
  3819. return true;
  3820. return node.type === 2 /* NodeTypes.TEXT */
  3821. ? !!node.content.trim()
  3822. : isNonWhitespaceContent(node.content);
  3823. }
  3824. // some directive transforms (e.g. v-model) may return a symbol for runtime
  3825. // import, which should be used instead of a resolveDirective call.
  3826. const directiveImportMap = new WeakMap();
  3827. // generate a JavaScript AST for this element's codegen
  3828. const transformElement = (node, context) => {
  3829. // perform the work on exit, after all child expressions have been
  3830. // processed and merged.
  3831. return function postTransformElement() {
  3832. node = context.currentNode;
  3833. if (!(node.type === 1 /* NodeTypes.ELEMENT */ &&
  3834. (node.tagType === 0 /* ElementTypes.ELEMENT */ ||
  3835. node.tagType === 1 /* ElementTypes.COMPONENT */))) {
  3836. return;
  3837. }
  3838. const { tag, props } = node;
  3839. const isComponent = node.tagType === 1 /* ElementTypes.COMPONENT */;
  3840. // The goal of the transform is to create a codegenNode implementing the
  3841. // VNodeCall interface.
  3842. let vnodeTag = isComponent
  3843. ? resolveComponentType(node, context)
  3844. : `"${tag}"`;
  3845. const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
  3846. let vnodeProps;
  3847. let vnodeChildren;
  3848. let vnodePatchFlag;
  3849. let patchFlag = 0;
  3850. let vnodeDynamicProps;
  3851. let dynamicPropNames;
  3852. let vnodeDirectives;
  3853. let shouldUseBlock =
  3854. // dynamic component may resolve to plain elements
  3855. isDynamicComponent ||
  3856. vnodeTag === TELEPORT ||
  3857. vnodeTag === SUSPENSE ||
  3858. (!isComponent &&
  3859. // <svg> and <foreignObject> must be forced into blocks so that block
  3860. // updates inside get proper isSVG flag at runtime. (#639, #643)
  3861. // This is technically web-specific, but splitting the logic out of core
  3862. // leads to too much unnecessary complexity.
  3863. (tag === 'svg' || tag === 'foreignObject'));
  3864. // props
  3865. if (props.length > 0) {
  3866. const propsBuildResult = buildProps(node, context, undefined, isComponent, isDynamicComponent);
  3867. vnodeProps = propsBuildResult.props;
  3868. patchFlag = propsBuildResult.patchFlag;
  3869. dynamicPropNames = propsBuildResult.dynamicPropNames;
  3870. const directives = propsBuildResult.directives;
  3871. vnodeDirectives =
  3872. directives && directives.length
  3873. ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
  3874. : undefined;
  3875. if (propsBuildResult.shouldUseBlock) {
  3876. shouldUseBlock = true;
  3877. }
  3878. }
  3879. // children
  3880. if (node.children.length > 0) {
  3881. if (vnodeTag === KEEP_ALIVE) {
  3882. // Although a built-in component, we compile KeepAlive with raw children
  3883. // instead of slot functions so that it can be used inside Transition
  3884. // or other Transition-wrapping HOCs.
  3885. // To ensure correct updates with block optimizations, we need to:
  3886. // 1. Force keep-alive into a block. This avoids its children being
  3887. // collected by a parent block.
  3888. shouldUseBlock = true;
  3889. // 2. Force keep-alive to always be updated, since it uses raw children.
  3890. patchFlag |= 1024 /* PatchFlags.DYNAMIC_SLOTS */;
  3891. if (node.children.length > 1) {
  3892. context.onError(createCompilerError(46 /* ErrorCodes.X_KEEP_ALIVE_INVALID_CHILDREN */, {
  3893. start: node.children[0].loc.start,
  3894. end: node.children[node.children.length - 1].loc.end,
  3895. source: ''
  3896. }));
  3897. }
  3898. }
  3899. const shouldBuildAsSlots = isComponent &&
  3900. // Teleport is not a real component and has dedicated runtime handling
  3901. vnodeTag !== TELEPORT &&
  3902. // explained above.
  3903. vnodeTag !== KEEP_ALIVE;
  3904. if (shouldBuildAsSlots) {
  3905. const { slots, hasDynamicSlots } = buildSlots(node, context);
  3906. vnodeChildren = slots;
  3907. if (hasDynamicSlots) {
  3908. patchFlag |= 1024 /* PatchFlags.DYNAMIC_SLOTS */;
  3909. }
  3910. }
  3911. else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
  3912. const child = node.children[0];
  3913. const type = child.type;
  3914. // check for dynamic text children
  3915. const hasDynamicTextChild = type === 5 /* NodeTypes.INTERPOLATION */ ||
  3916. type === 8 /* NodeTypes.COMPOUND_EXPRESSION */;
  3917. if (hasDynamicTextChild &&
  3918. getConstantType(child, context) === 0 /* ConstantTypes.NOT_CONSTANT */) {
  3919. patchFlag |= 1 /* PatchFlags.TEXT */;
  3920. }
  3921. // pass directly if the only child is a text node
  3922. // (plain / interpolation / expression)
  3923. if (hasDynamicTextChild || type === 2 /* NodeTypes.TEXT */) {
  3924. vnodeChildren = child;
  3925. }
  3926. else {
  3927. vnodeChildren = node.children;
  3928. }
  3929. }
  3930. else {
  3931. vnodeChildren = node.children;
  3932. }
  3933. }
  3934. // patchFlag & dynamicPropNames
  3935. if (patchFlag !== 0) {
  3936. {
  3937. if (patchFlag < 0) {
  3938. // special flags (negative and mutually exclusive)
  3939. vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
  3940. }
  3941. else {
  3942. // bitwise flags
  3943. const flagNames = Object.keys(PatchFlagNames)
  3944. .map(Number)
  3945. .filter(n => n > 0 && patchFlag & n)
  3946. .map(n => PatchFlagNames[n])
  3947. .join(`, `);
  3948. vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
  3949. }
  3950. }
  3951. if (dynamicPropNames && dynamicPropNames.length) {
  3952. vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
  3953. }
  3954. }
  3955. node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, isComponent, node.loc);
  3956. };
  3957. };
  3958. function resolveComponentType(node, context, ssr = false) {
  3959. let { tag } = node;
  3960. // 1. dynamic component
  3961. const isExplicitDynamic = isComponentTag(tag);
  3962. const isProp = findProp(node, 'is');
  3963. if (isProp) {
  3964. if (isExplicitDynamic ||
  3965. (isCompatEnabled("COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */, context))) {
  3966. const exp = isProp.type === 6 /* NodeTypes.ATTRIBUTE */
  3967. ? isProp.value && createSimpleExpression(isProp.value.content, true)
  3968. : isProp.exp;
  3969. if (exp) {
  3970. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  3971. exp
  3972. ]);
  3973. }
  3974. }
  3975. else if (isProp.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  3976. isProp.value.content.startsWith('vue:')) {
  3977. // <button is="vue:xxx">
  3978. // if not <component>, only is value that starts with "vue:" will be
  3979. // treated as component by the parse phase and reach here, unless it's
  3980. // compat mode where all is values are considered components
  3981. tag = isProp.value.content.slice(4);
  3982. }
  3983. }
  3984. // 1.5 v-is (TODO: Deprecate)
  3985. const isDir = !isExplicitDynamic && findDir(node, 'is');
  3986. if (isDir && isDir.exp) {
  3987. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  3988. isDir.exp
  3989. ]);
  3990. }
  3991. // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
  3992. const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
  3993. if (builtIn) {
  3994. // built-ins are simply fallthroughs / have special handling during ssr
  3995. // so we don't need to import their runtime equivalents
  3996. if (!ssr)
  3997. context.helper(builtIn);
  3998. return builtIn;
  3999. }
  4000. // 5. user component (resolve)
  4001. context.helper(RESOLVE_COMPONENT);
  4002. context.components.add(tag);
  4003. return toValidAssetId(tag, `component`);
  4004. }
  4005. function buildProps(node, context, props = node.props, isComponent, isDynamicComponent, ssr = false) {
  4006. const { tag, loc: elementLoc, children } = node;
  4007. let properties = [];
  4008. const mergeArgs = [];
  4009. const runtimeDirectives = [];
  4010. const hasChildren = children.length > 0;
  4011. let shouldUseBlock = false;
  4012. // patchFlag analysis
  4013. let patchFlag = 0;
  4014. let hasRef = false;
  4015. let hasClassBinding = false;
  4016. let hasStyleBinding = false;
  4017. let hasHydrationEventBinding = false;
  4018. let hasDynamicKeys = false;
  4019. let hasVnodeHook = false;
  4020. const dynamicPropNames = [];
  4021. const pushMergeArg = (arg) => {
  4022. if (properties.length) {
  4023. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  4024. properties = [];
  4025. }
  4026. if (arg)
  4027. mergeArgs.push(arg);
  4028. };
  4029. const analyzePatchFlag = ({ key, value }) => {
  4030. if (isStaticExp(key)) {
  4031. const name = key.content;
  4032. const isEventHandler = isOn(name);
  4033. if (isEventHandler &&
  4034. (!isComponent || isDynamicComponent) &&
  4035. // omit the flag for click handlers because hydration gives click
  4036. // dedicated fast path.
  4037. name.toLowerCase() !== 'onclick' &&
  4038. // omit v-model handlers
  4039. name !== 'onUpdate:modelValue' &&
  4040. // omit onVnodeXXX hooks
  4041. !isReservedProp(name)) {
  4042. hasHydrationEventBinding = true;
  4043. }
  4044. if (isEventHandler && isReservedProp(name)) {
  4045. hasVnodeHook = true;
  4046. }
  4047. if (value.type === 20 /* NodeTypes.JS_CACHE_EXPRESSION */ ||
  4048. ((value.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
  4049. value.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) &&
  4050. getConstantType(value, context) > 0)) {
  4051. // skip if the prop is a cached handler or has constant value
  4052. return;
  4053. }
  4054. if (name === 'ref') {
  4055. hasRef = true;
  4056. }
  4057. else if (name === 'class') {
  4058. hasClassBinding = true;
  4059. }
  4060. else if (name === 'style') {
  4061. hasStyleBinding = true;
  4062. }
  4063. else if (name !== 'key' && !dynamicPropNames.includes(name)) {
  4064. dynamicPropNames.push(name);
  4065. }
  4066. // treat the dynamic class and style binding of the component as dynamic props
  4067. if (isComponent &&
  4068. (name === 'class' || name === 'style') &&
  4069. !dynamicPropNames.includes(name)) {
  4070. dynamicPropNames.push(name);
  4071. }
  4072. }
  4073. else {
  4074. hasDynamicKeys = true;
  4075. }
  4076. };
  4077. for (let i = 0; i < props.length; i++) {
  4078. // static attribute
  4079. const prop = props[i];
  4080. if (prop.type === 6 /* NodeTypes.ATTRIBUTE */) {
  4081. const { loc, name, value } = prop;
  4082. let isStatic = true;
  4083. if (name === 'ref') {
  4084. hasRef = true;
  4085. if (context.scopes.vFor > 0) {
  4086. properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
  4087. }
  4088. }
  4089. // skip is on <component>, or is="vue:xxx"
  4090. if (name === 'is' &&
  4091. (isComponentTag(tag) ||
  4092. (value && value.content.startsWith('vue:')) ||
  4093. (isCompatEnabled("COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */, context)))) {
  4094. continue;
  4095. }
  4096. properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', isStatic, value ? value.loc : loc)));
  4097. }
  4098. else {
  4099. // directives
  4100. const { name, arg, exp, loc } = prop;
  4101. const isVBind = name === 'bind';
  4102. const isVOn = name === 'on';
  4103. // skip v-slot - it is handled by its dedicated transform.
  4104. if (name === 'slot') {
  4105. if (!isComponent) {
  4106. context.onError(createCompilerError(40 /* ErrorCodes.X_V_SLOT_MISPLACED */, loc));
  4107. }
  4108. continue;
  4109. }
  4110. // skip v-once/v-memo - they are handled by dedicated transforms.
  4111. if (name === 'once' || name === 'memo') {
  4112. continue;
  4113. }
  4114. // skip v-is and :is on <component>
  4115. if (name === 'is' ||
  4116. (isVBind &&
  4117. isStaticArgOf(arg, 'is') &&
  4118. (isComponentTag(tag) ||
  4119. (isCompatEnabled("COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */, context))))) {
  4120. continue;
  4121. }
  4122. // skip v-on in SSR compilation
  4123. if (isVOn && ssr) {
  4124. continue;
  4125. }
  4126. if (
  4127. // #938: elements with dynamic keys should be forced into blocks
  4128. (isVBind && isStaticArgOf(arg, 'key')) ||
  4129. // inline before-update hooks need to force block so that it is invoked
  4130. // before children
  4131. (isVOn && hasChildren && isStaticArgOf(arg, 'vue:before-update'))) {
  4132. shouldUseBlock = true;
  4133. }
  4134. if (isVBind && isStaticArgOf(arg, 'ref') && context.scopes.vFor > 0) {
  4135. properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
  4136. }
  4137. // special case for v-bind and v-on with no argument
  4138. if (!arg && (isVBind || isVOn)) {
  4139. hasDynamicKeys = true;
  4140. if (exp) {
  4141. if (isVBind) {
  4142. // have to merge early for compat build check
  4143. pushMergeArg();
  4144. {
  4145. // 2.x v-bind object order compat
  4146. {
  4147. const hasOverridableKeys = mergeArgs.some(arg => {
  4148. if (arg.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
  4149. return arg.properties.some(({ key }) => {
  4150. if (key.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
  4151. !key.isStatic) {
  4152. return true;
  4153. }
  4154. return (key.content !== 'class' &&
  4155. key.content !== 'style' &&
  4156. !isOn(key.content));
  4157. });
  4158. }
  4159. else {
  4160. // dynamic expression
  4161. return true;
  4162. }
  4163. });
  4164. if (hasOverridableKeys) {
  4165. checkCompatEnabled("COMPILER_V_BIND_OBJECT_ORDER" /* CompilerDeprecationTypes.COMPILER_V_BIND_OBJECT_ORDER */, context, loc);
  4166. }
  4167. }
  4168. if (isCompatEnabled("COMPILER_V_BIND_OBJECT_ORDER" /* CompilerDeprecationTypes.COMPILER_V_BIND_OBJECT_ORDER */, context)) {
  4169. mergeArgs.unshift(exp);
  4170. continue;
  4171. }
  4172. }
  4173. mergeArgs.push(exp);
  4174. }
  4175. else {
  4176. // v-on="obj" -> toHandlers(obj)
  4177. pushMergeArg({
  4178. type: 14 /* NodeTypes.JS_CALL_EXPRESSION */,
  4179. loc,
  4180. callee: context.helper(TO_HANDLERS),
  4181. arguments: isComponent ? [exp] : [exp, `true`]
  4182. });
  4183. }
  4184. }
  4185. else {
  4186. context.onError(createCompilerError(isVBind
  4187. ? 34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */
  4188. : 35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */, loc));
  4189. }
  4190. continue;
  4191. }
  4192. const directiveTransform = context.directiveTransforms[name];
  4193. if (directiveTransform) {
  4194. // has built-in directive transform.
  4195. const { props, needRuntime } = directiveTransform(prop, node, context);
  4196. !ssr && props.forEach(analyzePatchFlag);
  4197. if (isVOn && arg && !isStaticExp(arg)) {
  4198. pushMergeArg(createObjectExpression(props, elementLoc));
  4199. }
  4200. else {
  4201. properties.push(...props);
  4202. }
  4203. if (needRuntime) {
  4204. runtimeDirectives.push(prop);
  4205. if (isSymbol(needRuntime)) {
  4206. directiveImportMap.set(prop, needRuntime);
  4207. }
  4208. }
  4209. }
  4210. else if (!isBuiltInDirective(name)) {
  4211. // no built-in transform, this is a user custom directive.
  4212. runtimeDirectives.push(prop);
  4213. // custom dirs may use beforeUpdate so they need to force blocks
  4214. // to ensure before-update gets called before children update
  4215. if (hasChildren) {
  4216. shouldUseBlock = true;
  4217. }
  4218. }
  4219. }
  4220. }
  4221. let propsExpression = undefined;
  4222. // has v-bind="object" or v-on="object", wrap with mergeProps
  4223. if (mergeArgs.length) {
  4224. // close up any not-yet-merged props
  4225. pushMergeArg();
  4226. if (mergeArgs.length > 1) {
  4227. propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
  4228. }
  4229. else {
  4230. // single v-bind with nothing else - no need for a mergeProps call
  4231. propsExpression = mergeArgs[0];
  4232. }
  4233. }
  4234. else if (properties.length) {
  4235. propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
  4236. }
  4237. // patchFlag analysis
  4238. if (hasDynamicKeys) {
  4239. patchFlag |= 16 /* PatchFlags.FULL_PROPS */;
  4240. }
  4241. else {
  4242. if (hasClassBinding && !isComponent) {
  4243. patchFlag |= 2 /* PatchFlags.CLASS */;
  4244. }
  4245. if (hasStyleBinding && !isComponent) {
  4246. patchFlag |= 4 /* PatchFlags.STYLE */;
  4247. }
  4248. if (dynamicPropNames.length) {
  4249. patchFlag |= 8 /* PatchFlags.PROPS */;
  4250. }
  4251. if (hasHydrationEventBinding) {
  4252. patchFlag |= 32 /* PatchFlags.HYDRATE_EVENTS */;
  4253. }
  4254. }
  4255. if (!shouldUseBlock &&
  4256. (patchFlag === 0 || patchFlag === 32 /* PatchFlags.HYDRATE_EVENTS */) &&
  4257. (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
  4258. patchFlag |= 512 /* PatchFlags.NEED_PATCH */;
  4259. }
  4260. // pre-normalize props, SSR is skipped for now
  4261. if (!context.inSSR && propsExpression) {
  4262. switch (propsExpression.type) {
  4263. case 15 /* NodeTypes.JS_OBJECT_EXPRESSION */:
  4264. // means that there is no v-bind,
  4265. // but still need to deal with dynamic key binding
  4266. let classKeyIndex = -1;
  4267. let styleKeyIndex = -1;
  4268. let hasDynamicKey = false;
  4269. for (let i = 0; i < propsExpression.properties.length; i++) {
  4270. const key = propsExpression.properties[i].key;
  4271. if (isStaticExp(key)) {
  4272. if (key.content === 'class') {
  4273. classKeyIndex = i;
  4274. }
  4275. else if (key.content === 'style') {
  4276. styleKeyIndex = i;
  4277. }
  4278. }
  4279. else if (!key.isHandlerKey) {
  4280. hasDynamicKey = true;
  4281. }
  4282. }
  4283. const classProp = propsExpression.properties[classKeyIndex];
  4284. const styleProp = propsExpression.properties[styleKeyIndex];
  4285. // no dynamic key
  4286. if (!hasDynamicKey) {
  4287. if (classProp && !isStaticExp(classProp.value)) {
  4288. classProp.value = createCallExpression(context.helper(NORMALIZE_CLASS), [classProp.value]);
  4289. }
  4290. if (styleProp &&
  4291. // the static style is compiled into an object,
  4292. // so use `hasStyleBinding` to ensure that it is a dynamic style binding
  4293. (hasStyleBinding ||
  4294. (styleProp.value.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  4295. styleProp.value.content.trim()[0] === `[`) ||
  4296. // v-bind:style and style both exist,
  4297. // v-bind:style with static literal object
  4298. styleProp.value.type === 17 /* NodeTypes.JS_ARRAY_EXPRESSION */)) {
  4299. styleProp.value = createCallExpression(context.helper(NORMALIZE_STYLE), [styleProp.value]);
  4300. }
  4301. }
  4302. else {
  4303. // dynamic key binding, wrap with `normalizeProps`
  4304. propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [propsExpression]);
  4305. }
  4306. break;
  4307. case 14 /* NodeTypes.JS_CALL_EXPRESSION */:
  4308. // mergeProps call, do nothing
  4309. break;
  4310. default:
  4311. // single v-bind
  4312. propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [
  4313. createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [
  4314. propsExpression
  4315. ])
  4316. ]);
  4317. break;
  4318. }
  4319. }
  4320. return {
  4321. props: propsExpression,
  4322. directives: runtimeDirectives,
  4323. patchFlag,
  4324. dynamicPropNames,
  4325. shouldUseBlock
  4326. };
  4327. }
  4328. // Dedupe props in an object literal.
  4329. // Literal duplicated attributes would have been warned during the parse phase,
  4330. // however, it's possible to encounter duplicated `onXXX` handlers with different
  4331. // modifiers. We also need to merge static and dynamic class / style attributes.
  4332. // - onXXX handlers / style: merge into array
  4333. // - class: merge into single expression with concatenation
  4334. function dedupeProperties(properties) {
  4335. const knownProps = new Map();
  4336. const deduped = [];
  4337. for (let i = 0; i < properties.length; i++) {
  4338. const prop = properties[i];
  4339. // dynamic keys are always allowed
  4340. if (prop.key.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
  4341. deduped.push(prop);
  4342. continue;
  4343. }
  4344. const name = prop.key.content;
  4345. const existing = knownProps.get(name);
  4346. if (existing) {
  4347. if (name === 'style' || name === 'class' || isOn(name)) {
  4348. mergeAsArray(existing, prop);
  4349. }
  4350. // unexpected duplicate, should have emitted error during parse
  4351. }
  4352. else {
  4353. knownProps.set(name, prop);
  4354. deduped.push(prop);
  4355. }
  4356. }
  4357. return deduped;
  4358. }
  4359. function mergeAsArray(existing, incoming) {
  4360. if (existing.value.type === 17 /* NodeTypes.JS_ARRAY_EXPRESSION */) {
  4361. existing.value.elements.push(incoming.value);
  4362. }
  4363. else {
  4364. existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
  4365. }
  4366. }
  4367. function buildDirectiveArgs(dir, context) {
  4368. const dirArgs = [];
  4369. const runtime = directiveImportMap.get(dir);
  4370. if (runtime) {
  4371. // built-in directive with runtime
  4372. dirArgs.push(context.helperString(runtime));
  4373. }
  4374. else {
  4375. {
  4376. // inject statement for resolving directive
  4377. context.helper(RESOLVE_DIRECTIVE);
  4378. context.directives.add(dir.name);
  4379. dirArgs.push(toValidAssetId(dir.name, `directive`));
  4380. }
  4381. }
  4382. const { loc } = dir;
  4383. if (dir.exp)
  4384. dirArgs.push(dir.exp);
  4385. if (dir.arg) {
  4386. if (!dir.exp) {
  4387. dirArgs.push(`void 0`);
  4388. }
  4389. dirArgs.push(dir.arg);
  4390. }
  4391. if (Object.keys(dir.modifiers).length) {
  4392. if (!dir.arg) {
  4393. if (!dir.exp) {
  4394. dirArgs.push(`void 0`);
  4395. }
  4396. dirArgs.push(`void 0`);
  4397. }
  4398. const trueExpression = createSimpleExpression(`true`, false, loc);
  4399. dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
  4400. }
  4401. return createArrayExpression(dirArgs, dir.loc);
  4402. }
  4403. function stringifyDynamicPropNames(props) {
  4404. let propsNamesString = `[`;
  4405. for (let i = 0, l = props.length; i < l; i++) {
  4406. propsNamesString += JSON.stringify(props[i]);
  4407. if (i < l - 1)
  4408. propsNamesString += ', ';
  4409. }
  4410. return propsNamesString + `]`;
  4411. }
  4412. function isComponentTag(tag) {
  4413. return tag === 'component' || tag === 'Component';
  4414. }
  4415. const transformSlotOutlet = (node, context) => {
  4416. if (isSlotOutlet(node)) {
  4417. const { children, loc } = node;
  4418. const { slotName, slotProps } = processSlotOutlet(node, context);
  4419. const slotArgs = [
  4420. context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
  4421. slotName,
  4422. '{}',
  4423. 'undefined',
  4424. 'true'
  4425. ];
  4426. let expectedLen = 2;
  4427. if (slotProps) {
  4428. slotArgs[2] = slotProps;
  4429. expectedLen = 3;
  4430. }
  4431. if (children.length) {
  4432. slotArgs[3] = createFunctionExpression([], children, false, false, loc);
  4433. expectedLen = 4;
  4434. }
  4435. if (context.scopeId && !context.slotted) {
  4436. expectedLen = 5;
  4437. }
  4438. slotArgs.splice(expectedLen); // remove unused arguments
  4439. node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
  4440. }
  4441. };
  4442. function processSlotOutlet(node, context) {
  4443. let slotName = `"default"`;
  4444. let slotProps = undefined;
  4445. const nonNameProps = [];
  4446. for (let i = 0; i < node.props.length; i++) {
  4447. const p = node.props[i];
  4448. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  4449. if (p.value) {
  4450. if (p.name === 'name') {
  4451. slotName = JSON.stringify(p.value.content);
  4452. }
  4453. else {
  4454. p.name = camelize(p.name);
  4455. nonNameProps.push(p);
  4456. }
  4457. }
  4458. }
  4459. else {
  4460. if (p.name === 'bind' && isStaticArgOf(p.arg, 'name')) {
  4461. if (p.exp)
  4462. slotName = p.exp;
  4463. }
  4464. else {
  4465. if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
  4466. p.arg.content = camelize(p.arg.content);
  4467. }
  4468. nonNameProps.push(p);
  4469. }
  4470. }
  4471. }
  4472. if (nonNameProps.length > 0) {
  4473. const { props, directives } = buildProps(node, context, nonNameProps, false, false);
  4474. slotProps = props;
  4475. if (directives.length) {
  4476. context.onError(createCompilerError(36 /* ErrorCodes.X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
  4477. }
  4478. }
  4479. return {
  4480. slotName,
  4481. slotProps
  4482. };
  4483. }
  4484. const fnExpRE = /^\s*([\w$_]+|(async\s*)?\([^)]*?\))\s*(:[^=]+)?=>|^\s*(async\s+)?function(?:\s+[\w$]+)?\s*\(/;
  4485. const transformOn = (dir, node, context, augmentor) => {
  4486. const { loc, modifiers, arg } = dir;
  4487. if (!dir.exp && !modifiers.length) {
  4488. context.onError(createCompilerError(35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */, loc));
  4489. }
  4490. let eventName;
  4491. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  4492. if (arg.isStatic) {
  4493. let rawName = arg.content;
  4494. // TODO deprecate @vnodeXXX usage
  4495. if (rawName.startsWith('vue:')) {
  4496. rawName = `vnode-${rawName.slice(4)}`;
  4497. }
  4498. const eventString = node.tagType !== 0 /* ElementTypes.ELEMENT */ ||
  4499. rawName.startsWith('vnode') ||
  4500. !/[A-Z]/.test(rawName)
  4501. ? // for non-element and vnode lifecycle event listeners, auto convert
  4502. // it to camelCase. See issue #2249
  4503. toHandlerKey(camelize(rawName))
  4504. : // preserve case for plain element listeners that have uppercase
  4505. // letters, as these may be custom elements' custom events
  4506. `on:${rawName}`;
  4507. eventName = createSimpleExpression(eventString, true, arg.loc);
  4508. }
  4509. else {
  4510. // #2388
  4511. eventName = createCompoundExpression([
  4512. `${context.helperString(TO_HANDLER_KEY)}(`,
  4513. arg,
  4514. `)`
  4515. ]);
  4516. }
  4517. }
  4518. else {
  4519. // already a compound expression.
  4520. eventName = arg;
  4521. eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
  4522. eventName.children.push(`)`);
  4523. }
  4524. // handler processing
  4525. let exp = dir.exp;
  4526. if (exp && !exp.content.trim()) {
  4527. exp = undefined;
  4528. }
  4529. let shouldCache = context.cacheHandlers && !exp && !context.inVOnce;
  4530. if (exp) {
  4531. const isMemberExp = isMemberExpression(exp.content);
  4532. const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
  4533. const hasMultipleStatements = exp.content.includes(`;`);
  4534. {
  4535. validateBrowserExpression(exp, context, false, hasMultipleStatements);
  4536. }
  4537. if (isInlineStatement || (shouldCache && isMemberExp)) {
  4538. // wrap inline statement in a function expression
  4539. exp = createCompoundExpression([
  4540. `${isInlineStatement
  4541. ? `$event`
  4542. : `${``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
  4543. exp,
  4544. hasMultipleStatements ? `}` : `)`
  4545. ]);
  4546. }
  4547. }
  4548. let ret = {
  4549. props: [
  4550. createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
  4551. ]
  4552. };
  4553. // apply extended compiler augmentor
  4554. if (augmentor) {
  4555. ret = augmentor(ret);
  4556. }
  4557. if (shouldCache) {
  4558. // cache handlers so that it's always the same handler being passed down.
  4559. // this avoids unnecessary re-renders when users use inline handlers on
  4560. // components.
  4561. ret.props[0].value = context.cache(ret.props[0].value);
  4562. }
  4563. // mark the key as handler for props normalization check
  4564. ret.props.forEach(p => (p.key.isHandlerKey = true));
  4565. return ret;
  4566. };
  4567. // v-bind without arg is handled directly in ./transformElements.ts due to it affecting
  4568. // codegen for the entire props object. This transform here is only for v-bind
  4569. // *with* args.
  4570. const transformBind = (dir, _node, context) => {
  4571. const { exp, modifiers, loc } = dir;
  4572. const arg = dir.arg;
  4573. if (arg.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  4574. arg.children.unshift(`(`);
  4575. arg.children.push(`) || ""`);
  4576. }
  4577. else if (!arg.isStatic) {
  4578. arg.content = `${arg.content} || ""`;
  4579. }
  4580. // .sync is replaced by v-model:arg
  4581. if (modifiers.includes('camel')) {
  4582. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  4583. if (arg.isStatic) {
  4584. arg.content = camelize(arg.content);
  4585. }
  4586. else {
  4587. arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
  4588. }
  4589. }
  4590. else {
  4591. arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
  4592. arg.children.push(`)`);
  4593. }
  4594. }
  4595. if (!context.inSSR) {
  4596. if (modifiers.includes('prop')) {
  4597. injectPrefix(arg, '.');
  4598. }
  4599. if (modifiers.includes('attr')) {
  4600. injectPrefix(arg, '^');
  4601. }
  4602. }
  4603. if (!exp ||
  4604. (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && !exp.content.trim())) {
  4605. context.onError(createCompilerError(34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */, loc));
  4606. return {
  4607. props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
  4608. };
  4609. }
  4610. return {
  4611. props: [createObjectProperty(arg, exp)]
  4612. };
  4613. };
  4614. const injectPrefix = (arg, prefix) => {
  4615. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  4616. if (arg.isStatic) {
  4617. arg.content = prefix + arg.content;
  4618. }
  4619. else {
  4620. arg.content = `\`${prefix}\${${arg.content}}\``;
  4621. }
  4622. }
  4623. else {
  4624. arg.children.unshift(`'${prefix}' + (`);
  4625. arg.children.push(`)`);
  4626. }
  4627. };
  4628. // Merge adjacent text nodes and expressions into a single expression
  4629. // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
  4630. const transformText = (node, context) => {
  4631. if (node.type === 0 /* NodeTypes.ROOT */ ||
  4632. node.type === 1 /* NodeTypes.ELEMENT */ ||
  4633. node.type === 11 /* NodeTypes.FOR */ ||
  4634. node.type === 10 /* NodeTypes.IF_BRANCH */) {
  4635. // perform the transform on node exit so that all expressions have already
  4636. // been processed.
  4637. return () => {
  4638. const children = node.children;
  4639. let currentContainer = undefined;
  4640. let hasText = false;
  4641. for (let i = 0; i < children.length; i++) {
  4642. const child = children[i];
  4643. if (isText(child)) {
  4644. hasText = true;
  4645. for (let j = i + 1; j < children.length; j++) {
  4646. const next = children[j];
  4647. if (isText(next)) {
  4648. if (!currentContainer) {
  4649. currentContainer = children[i] = createCompoundExpression([child], child.loc);
  4650. }
  4651. // merge adjacent text node into current
  4652. currentContainer.children.push(` + `, next);
  4653. children.splice(j, 1);
  4654. j--;
  4655. }
  4656. else {
  4657. currentContainer = undefined;
  4658. break;
  4659. }
  4660. }
  4661. }
  4662. }
  4663. if (!hasText ||
  4664. // if this is a plain element with a single text child, leave it
  4665. // as-is since the runtime has dedicated fast path for this by directly
  4666. // setting textContent of the element.
  4667. // for component root it's always normalized anyway.
  4668. (children.length === 1 &&
  4669. (node.type === 0 /* NodeTypes.ROOT */ ||
  4670. (node.type === 1 /* NodeTypes.ELEMENT */ &&
  4671. node.tagType === 0 /* ElementTypes.ELEMENT */ &&
  4672. // #3756
  4673. // custom directives can potentially add DOM elements arbitrarily,
  4674. // we need to avoid setting textContent of the element at runtime
  4675. // to avoid accidentally overwriting the DOM elements added
  4676. // by the user through custom directives.
  4677. !node.props.find(p => p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  4678. !context.directiveTransforms[p.name]) &&
  4679. // in compat mode, <template> tags with no special directives
  4680. // will be rendered as a fragment so its children must be
  4681. // converted into vnodes.
  4682. !(node.tag === 'template'))))) {
  4683. return;
  4684. }
  4685. // pre-convert text nodes into createTextVNode(text) calls to avoid
  4686. // runtime normalization.
  4687. for (let i = 0; i < children.length; i++) {
  4688. const child = children[i];
  4689. if (isText(child) || child.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) {
  4690. const callArgs = [];
  4691. // createTextVNode defaults to single whitespace, so if it is a
  4692. // single space the code could be an empty call to save bytes.
  4693. if (child.type !== 2 /* NodeTypes.TEXT */ || child.content !== ' ') {
  4694. callArgs.push(child);
  4695. }
  4696. // mark dynamic text with flag so it gets patched inside a block
  4697. if (!context.ssr &&
  4698. getConstantType(child, context) === 0 /* ConstantTypes.NOT_CONSTANT */) {
  4699. callArgs.push(1 /* PatchFlags.TEXT */ +
  4700. (` /* ${PatchFlagNames[1 /* PatchFlags.TEXT */]} */` ));
  4701. }
  4702. children[i] = {
  4703. type: 12 /* NodeTypes.TEXT_CALL */,
  4704. content: child,
  4705. loc: child.loc,
  4706. codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
  4707. };
  4708. }
  4709. }
  4710. };
  4711. }
  4712. };
  4713. const seen = new WeakSet();
  4714. const transformOnce = (node, context) => {
  4715. if (node.type === 1 /* NodeTypes.ELEMENT */ && findDir(node, 'once', true)) {
  4716. if (seen.has(node) || context.inVOnce) {
  4717. return;
  4718. }
  4719. seen.add(node);
  4720. context.inVOnce = true;
  4721. context.helper(SET_BLOCK_TRACKING);
  4722. return () => {
  4723. context.inVOnce = false;
  4724. const cur = context.currentNode;
  4725. if (cur.codegenNode) {
  4726. cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
  4727. }
  4728. };
  4729. }
  4730. };
  4731. const transformModel = (dir, node, context) => {
  4732. const { exp, arg } = dir;
  4733. if (!exp) {
  4734. context.onError(createCompilerError(41 /* ErrorCodes.X_V_MODEL_NO_EXPRESSION */, dir.loc));
  4735. return createTransformProps();
  4736. }
  4737. const rawExp = exp.loc.source;
  4738. const expString = exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ? exp.content : rawExp;
  4739. // im SFC <script setup> inline mode, the exp may have been transformed into
  4740. // _unref(exp)
  4741. const bindingType = context.bindingMetadata[rawExp];
  4742. // check props
  4743. if (bindingType === "props" /* BindingTypes.PROPS */ ||
  4744. bindingType === "props-aliased" /* BindingTypes.PROPS_ALIASED */) {
  4745. context.onError(createCompilerError(44 /* ErrorCodes.X_V_MODEL_ON_PROPS */, exp.loc));
  4746. return createTransformProps();
  4747. }
  4748. const maybeRef = !true ;
  4749. if (!expString.trim() ||
  4750. (!isMemberExpression(expString) && !maybeRef)) {
  4751. context.onError(createCompilerError(42 /* ErrorCodes.X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
  4752. return createTransformProps();
  4753. }
  4754. const propName = arg ? arg : createSimpleExpression('modelValue', true);
  4755. const eventName = arg
  4756. ? isStaticExp(arg)
  4757. ? `onUpdate:${arg.content}`
  4758. : createCompoundExpression(['"onUpdate:" + ', arg])
  4759. : `onUpdate:modelValue`;
  4760. let assignmentExp;
  4761. const eventArg = context.isTS ? `($event: any)` : `$event`;
  4762. {
  4763. assignmentExp = createCompoundExpression([
  4764. `${eventArg} => ((`,
  4765. exp,
  4766. `) = $event)`
  4767. ]);
  4768. }
  4769. const props = [
  4770. // modelValue: foo
  4771. createObjectProperty(propName, dir.exp),
  4772. // "onUpdate:modelValue": $event => (foo = $event)
  4773. createObjectProperty(eventName, assignmentExp)
  4774. ];
  4775. // modelModifiers: { foo: true, "bar-baz": true }
  4776. if (dir.modifiers.length && node.tagType === 1 /* ElementTypes.COMPONENT */) {
  4777. const modifiers = dir.modifiers
  4778. .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
  4779. .join(`, `);
  4780. const modifiersKey = arg
  4781. ? isStaticExp(arg)
  4782. ? `${arg.content}Modifiers`
  4783. : createCompoundExpression([arg, ' + "Modifiers"'])
  4784. : `modelModifiers`;
  4785. props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* ConstantTypes.CAN_HOIST */)));
  4786. }
  4787. return createTransformProps(props);
  4788. };
  4789. function createTransformProps(props = []) {
  4790. return { props };
  4791. }
  4792. const validDivisionCharRE = /[\w).+\-_$\]]/;
  4793. const transformFilter = (node, context) => {
  4794. if (!isCompatEnabled("COMPILER_FILTER" /* CompilerDeprecationTypes.COMPILER_FILTERS */, context)) {
  4795. return;
  4796. }
  4797. if (node.type === 5 /* NodeTypes.INTERPOLATION */) {
  4798. // filter rewrite is applied before expression transform so only
  4799. // simple expressions are possible at this stage
  4800. rewriteFilter(node.content, context);
  4801. }
  4802. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  4803. node.props.forEach((prop) => {
  4804. if (prop.type === 7 /* NodeTypes.DIRECTIVE */ &&
  4805. prop.name !== 'for' &&
  4806. prop.exp) {
  4807. rewriteFilter(prop.exp, context);
  4808. }
  4809. });
  4810. }
  4811. };
  4812. function rewriteFilter(node, context) {
  4813. if (node.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  4814. parseFilter(node, context);
  4815. }
  4816. else {
  4817. for (let i = 0; i < node.children.length; i++) {
  4818. const child = node.children[i];
  4819. if (typeof child !== 'object')
  4820. continue;
  4821. if (child.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  4822. parseFilter(child, context);
  4823. }
  4824. else if (child.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) {
  4825. rewriteFilter(node, context);
  4826. }
  4827. else if (child.type === 5 /* NodeTypes.INTERPOLATION */) {
  4828. rewriteFilter(child.content, context);
  4829. }
  4830. }
  4831. }
  4832. }
  4833. function parseFilter(node, context) {
  4834. const exp = node.content;
  4835. let inSingle = false;
  4836. let inDouble = false;
  4837. let inTemplateString = false;
  4838. let inRegex = false;
  4839. let curly = 0;
  4840. let square = 0;
  4841. let paren = 0;
  4842. let lastFilterIndex = 0;
  4843. let c, prev, i, expression, filters = [];
  4844. for (i = 0; i < exp.length; i++) {
  4845. prev = c;
  4846. c = exp.charCodeAt(i);
  4847. if (inSingle) {
  4848. if (c === 0x27 && prev !== 0x5c)
  4849. inSingle = false;
  4850. }
  4851. else if (inDouble) {
  4852. if (c === 0x22 && prev !== 0x5c)
  4853. inDouble = false;
  4854. }
  4855. else if (inTemplateString) {
  4856. if (c === 0x60 && prev !== 0x5c)
  4857. inTemplateString = false;
  4858. }
  4859. else if (inRegex) {
  4860. if (c === 0x2f && prev !== 0x5c)
  4861. inRegex = false;
  4862. }
  4863. else if (c === 0x7c && // pipe
  4864. exp.charCodeAt(i + 1) !== 0x7c &&
  4865. exp.charCodeAt(i - 1) !== 0x7c &&
  4866. !curly &&
  4867. !square &&
  4868. !paren) {
  4869. if (expression === undefined) {
  4870. // first filter, end of expression
  4871. lastFilterIndex = i + 1;
  4872. expression = exp.slice(0, i).trim();
  4873. }
  4874. else {
  4875. pushFilter();
  4876. }
  4877. }
  4878. else {
  4879. switch (c) {
  4880. case 0x22:
  4881. inDouble = true;
  4882. break; // "
  4883. case 0x27:
  4884. inSingle = true;
  4885. break; // '
  4886. case 0x60:
  4887. inTemplateString = true;
  4888. break; // `
  4889. case 0x28:
  4890. paren++;
  4891. break; // (
  4892. case 0x29:
  4893. paren--;
  4894. break; // )
  4895. case 0x5b:
  4896. square++;
  4897. break; // [
  4898. case 0x5d:
  4899. square--;
  4900. break; // ]
  4901. case 0x7b:
  4902. curly++;
  4903. break; // {
  4904. case 0x7d:
  4905. curly--;
  4906. break; // }
  4907. }
  4908. if (c === 0x2f) {
  4909. // /
  4910. let j = i - 1;
  4911. let p;
  4912. // find first non-whitespace prev char
  4913. for (; j >= 0; j--) {
  4914. p = exp.charAt(j);
  4915. if (p !== ' ')
  4916. break;
  4917. }
  4918. if (!p || !validDivisionCharRE.test(p)) {
  4919. inRegex = true;
  4920. }
  4921. }
  4922. }
  4923. }
  4924. if (expression === undefined) {
  4925. expression = exp.slice(0, i).trim();
  4926. }
  4927. else if (lastFilterIndex !== 0) {
  4928. pushFilter();
  4929. }
  4930. function pushFilter() {
  4931. filters.push(exp.slice(lastFilterIndex, i).trim());
  4932. lastFilterIndex = i + 1;
  4933. }
  4934. if (filters.length) {
  4935. warnDeprecation("COMPILER_FILTER" /* CompilerDeprecationTypes.COMPILER_FILTERS */, context, node.loc);
  4936. for (i = 0; i < filters.length; i++) {
  4937. expression = wrapFilter(expression, filters[i], context);
  4938. }
  4939. node.content = expression;
  4940. }
  4941. }
  4942. function wrapFilter(exp, filter, context) {
  4943. context.helper(RESOLVE_FILTER);
  4944. const i = filter.indexOf('(');
  4945. if (i < 0) {
  4946. context.filters.add(filter);
  4947. return `${toValidAssetId(filter, 'filter')}(${exp})`;
  4948. }
  4949. else {
  4950. const name = filter.slice(0, i);
  4951. const args = filter.slice(i + 1);
  4952. context.filters.add(name);
  4953. return `${toValidAssetId(name, 'filter')}(${exp}${args !== ')' ? ',' + args : args}`;
  4954. }
  4955. }
  4956. const seen$1 = new WeakSet();
  4957. const transformMemo = (node, context) => {
  4958. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  4959. const dir = findDir(node, 'memo');
  4960. if (!dir || seen$1.has(node)) {
  4961. return;
  4962. }
  4963. seen$1.add(node);
  4964. return () => {
  4965. const codegenNode = node.codegenNode ||
  4966. context.currentNode.codegenNode;
  4967. if (codegenNode && codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  4968. // non-component sub tree should be turned into a block
  4969. if (node.tagType !== 1 /* ElementTypes.COMPONENT */) {
  4970. makeBlock(codegenNode, context);
  4971. }
  4972. node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [
  4973. dir.exp,
  4974. createFunctionExpression(undefined, codegenNode),
  4975. `_cache`,
  4976. String(context.cached++)
  4977. ]);
  4978. }
  4979. };
  4980. }
  4981. };
  4982. function getBaseTransformPreset(prefixIdentifiers) {
  4983. return [
  4984. [
  4985. transformOnce,
  4986. transformIf,
  4987. transformMemo,
  4988. transformFor,
  4989. ...([transformFilter] ),
  4990. ...([transformExpression]
  4991. ),
  4992. transformSlotOutlet,
  4993. transformElement,
  4994. trackSlotScopes,
  4995. transformText
  4996. ],
  4997. {
  4998. on: transformOn,
  4999. bind: transformBind,
  5000. model: transformModel
  5001. }
  5002. ];
  5003. }
  5004. // we name it `baseCompile` so that higher order compilers like
  5005. // @vue/compiler-dom can export `compile` while re-exporting everything else.
  5006. function baseCompile(template, options = {}) {
  5007. const onError = options.onError || defaultOnError;
  5008. const isModuleMode = options.mode === 'module';
  5009. /* istanbul ignore if */
  5010. {
  5011. if (options.prefixIdentifiers === true) {
  5012. onError(createCompilerError(47 /* ErrorCodes.X_PREFIX_ID_NOT_SUPPORTED */));
  5013. }
  5014. else if (isModuleMode) {
  5015. onError(createCompilerError(48 /* ErrorCodes.X_MODULE_MODE_NOT_SUPPORTED */));
  5016. }
  5017. }
  5018. const prefixIdentifiers = !true ;
  5019. if (options.cacheHandlers) {
  5020. onError(createCompilerError(49 /* ErrorCodes.X_CACHE_HANDLER_NOT_SUPPORTED */));
  5021. }
  5022. if (options.scopeId && !isModuleMode) {
  5023. onError(createCompilerError(50 /* ErrorCodes.X_SCOPE_ID_NOT_SUPPORTED */));
  5024. }
  5025. const ast = isString(template) ? baseParse(template, options) : template;
  5026. const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
  5027. transform(ast, extend({}, options, {
  5028. prefixIdentifiers,
  5029. nodeTransforms: [
  5030. ...nodeTransforms,
  5031. ...(options.nodeTransforms || []) // user transforms
  5032. ],
  5033. directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
  5034. )
  5035. }));
  5036. return generate(ast, extend({}, options, {
  5037. prefixIdentifiers
  5038. }));
  5039. }
  5040. const noopDirectiveTransform = () => ({ props: [] });
  5041. const V_MODEL_RADIO = Symbol(`vModelRadio` );
  5042. const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` );
  5043. const V_MODEL_TEXT = Symbol(`vModelText` );
  5044. const V_MODEL_SELECT = Symbol(`vModelSelect` );
  5045. const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` );
  5046. const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` );
  5047. const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` );
  5048. const V_SHOW = Symbol(`vShow` );
  5049. const TRANSITION = Symbol(`Transition` );
  5050. const TRANSITION_GROUP = Symbol(`TransitionGroup` );
  5051. registerRuntimeHelpers({
  5052. [V_MODEL_RADIO]: `vModelRadio`,
  5053. [V_MODEL_CHECKBOX]: `vModelCheckbox`,
  5054. [V_MODEL_TEXT]: `vModelText`,
  5055. [V_MODEL_SELECT]: `vModelSelect`,
  5056. [V_MODEL_DYNAMIC]: `vModelDynamic`,
  5057. [V_ON_WITH_MODIFIERS]: `withModifiers`,
  5058. [V_ON_WITH_KEYS]: `withKeys`,
  5059. [V_SHOW]: `vShow`,
  5060. [TRANSITION]: `Transition`,
  5061. [TRANSITION_GROUP]: `TransitionGroup`
  5062. });
  5063. /* eslint-disable no-restricted-globals */
  5064. let decoder;
  5065. function decodeHtmlBrowser(raw, asAttr = false) {
  5066. if (!decoder) {
  5067. decoder = document.createElement('div');
  5068. }
  5069. if (asAttr) {
  5070. decoder.innerHTML = `<div foo="${raw.replace(/"/g, '&quot;')}">`;
  5071. return decoder.children[0].getAttribute('foo');
  5072. }
  5073. else {
  5074. decoder.innerHTML = raw;
  5075. return decoder.textContent;
  5076. }
  5077. }
  5078. const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
  5079. const parserOptions = {
  5080. isVoidTag,
  5081. isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
  5082. isPreTag: tag => tag === 'pre',
  5083. decodeEntities: decodeHtmlBrowser ,
  5084. isBuiltInComponent: (tag) => {
  5085. if (isBuiltInType(tag, `Transition`)) {
  5086. return TRANSITION;
  5087. }
  5088. else if (isBuiltInType(tag, `TransitionGroup`)) {
  5089. return TRANSITION_GROUP;
  5090. }
  5091. },
  5092. // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
  5093. getNamespace(tag, parent) {
  5094. let ns = parent ? parent.ns : 0 /* DOMNamespaces.HTML */;
  5095. if (parent && ns === 2 /* DOMNamespaces.MATH_ML */) {
  5096. if (parent.tag === 'annotation-xml') {
  5097. if (tag === 'svg') {
  5098. return 1 /* DOMNamespaces.SVG */;
  5099. }
  5100. if (parent.props.some(a => a.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  5101. a.name === 'encoding' &&
  5102. a.value != null &&
  5103. (a.value.content === 'text/html' ||
  5104. a.value.content === 'application/xhtml+xml'))) {
  5105. ns = 0 /* DOMNamespaces.HTML */;
  5106. }
  5107. }
  5108. else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
  5109. tag !== 'mglyph' &&
  5110. tag !== 'malignmark') {
  5111. ns = 0 /* DOMNamespaces.HTML */;
  5112. }
  5113. }
  5114. else if (parent && ns === 1 /* DOMNamespaces.SVG */) {
  5115. if (parent.tag === 'foreignObject' ||
  5116. parent.tag === 'desc' ||
  5117. parent.tag === 'title') {
  5118. ns = 0 /* DOMNamespaces.HTML */;
  5119. }
  5120. }
  5121. if (ns === 0 /* DOMNamespaces.HTML */) {
  5122. if (tag === 'svg') {
  5123. return 1 /* DOMNamespaces.SVG */;
  5124. }
  5125. if (tag === 'math') {
  5126. return 2 /* DOMNamespaces.MATH_ML */;
  5127. }
  5128. }
  5129. return ns;
  5130. },
  5131. // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
  5132. getTextMode({ tag, ns }) {
  5133. if (ns === 0 /* DOMNamespaces.HTML */) {
  5134. if (tag === 'textarea' || tag === 'title') {
  5135. return 1 /* TextModes.RCDATA */;
  5136. }
  5137. if (isRawTextContainer(tag)) {
  5138. return 2 /* TextModes.RAWTEXT */;
  5139. }
  5140. }
  5141. return 0 /* TextModes.DATA */;
  5142. }
  5143. };
  5144. // Parse inline CSS strings for static style attributes into an object.
  5145. // This is a NodeTransform since it works on the static `style` attribute and
  5146. // converts it into a dynamic equivalent:
  5147. // style="color: red" -> :style='{ "color": "red" }'
  5148. // It is then processed by `transformElement` and included in the generated
  5149. // props.
  5150. const transformStyle = node => {
  5151. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  5152. node.props.forEach((p, i) => {
  5153. if (p.type === 6 /* NodeTypes.ATTRIBUTE */ && p.name === 'style' && p.value) {
  5154. // replace p with an expression node
  5155. node.props[i] = {
  5156. type: 7 /* NodeTypes.DIRECTIVE */,
  5157. name: `bind`,
  5158. arg: createSimpleExpression(`style`, true, p.loc),
  5159. exp: parseInlineCSS(p.value.content, p.loc),
  5160. modifiers: [],
  5161. loc: p.loc
  5162. };
  5163. }
  5164. });
  5165. }
  5166. };
  5167. const parseInlineCSS = (cssText, loc) => {
  5168. const normalized = parseStringStyle(cssText);
  5169. return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  5170. };
  5171. function createDOMCompilerError(code, loc) {
  5172. return createCompilerError(code, loc, DOMErrorMessages );
  5173. }
  5174. const DOMErrorMessages = {
  5175. [51 /* DOMErrorCodes.X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
  5176. [52 /* DOMErrorCodes.X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
  5177. [53 /* DOMErrorCodes.X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
  5178. [54 /* DOMErrorCodes.X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
  5179. [55 /* DOMErrorCodes.X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
  5180. [56 /* DOMErrorCodes.X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
  5181. [57 /* DOMErrorCodes.X_V_MODEL_ON_FILE_INPUT_ELEMENT */]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`,
  5182. [58 /* DOMErrorCodes.X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
  5183. [59 /* DOMErrorCodes.X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
  5184. [60 /* DOMErrorCodes.X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
  5185. [61 /* DOMErrorCodes.X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
  5186. };
  5187. const transformVHtml = (dir, node, context) => {
  5188. const { exp, loc } = dir;
  5189. if (!exp) {
  5190. context.onError(createDOMCompilerError(51 /* DOMErrorCodes.X_V_HTML_NO_EXPRESSION */, loc));
  5191. }
  5192. if (node.children.length) {
  5193. context.onError(createDOMCompilerError(52 /* DOMErrorCodes.X_V_HTML_WITH_CHILDREN */, loc));
  5194. node.children.length = 0;
  5195. }
  5196. return {
  5197. props: [
  5198. createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
  5199. ]
  5200. };
  5201. };
  5202. const transformVText = (dir, node, context) => {
  5203. const { exp, loc } = dir;
  5204. if (!exp) {
  5205. context.onError(createDOMCompilerError(53 /* DOMErrorCodes.X_V_TEXT_NO_EXPRESSION */, loc));
  5206. }
  5207. if (node.children.length) {
  5208. context.onError(createDOMCompilerError(54 /* DOMErrorCodes.X_V_TEXT_WITH_CHILDREN */, loc));
  5209. node.children.length = 0;
  5210. }
  5211. return {
  5212. props: [
  5213. createObjectProperty(createSimpleExpression(`textContent`, true), exp
  5214. ? getConstantType(exp, context) > 0
  5215. ? exp
  5216. : createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
  5217. : createSimpleExpression('', true))
  5218. ]
  5219. };
  5220. };
  5221. const transformModel$1 = (dir, node, context) => {
  5222. const baseResult = transformModel(dir, node, context);
  5223. // base transform has errors OR component v-model (only need props)
  5224. if (!baseResult.props.length || node.tagType === 1 /* ElementTypes.COMPONENT */) {
  5225. return baseResult;
  5226. }
  5227. if (dir.arg) {
  5228. context.onError(createDOMCompilerError(56 /* DOMErrorCodes.X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
  5229. }
  5230. function checkDuplicatedValue() {
  5231. const value = findProp(node, 'value');
  5232. if (value) {
  5233. context.onError(createDOMCompilerError(58 /* DOMErrorCodes.X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
  5234. }
  5235. }
  5236. const { tag } = node;
  5237. const isCustomElement = context.isCustomElement(tag);
  5238. if (tag === 'input' ||
  5239. tag === 'textarea' ||
  5240. tag === 'select' ||
  5241. isCustomElement) {
  5242. let directiveToUse = V_MODEL_TEXT;
  5243. let isInvalidType = false;
  5244. if (tag === 'input' || isCustomElement) {
  5245. const type = findProp(node, `type`);
  5246. if (type) {
  5247. if (type.type === 7 /* NodeTypes.DIRECTIVE */) {
  5248. // :type="foo"
  5249. directiveToUse = V_MODEL_DYNAMIC;
  5250. }
  5251. else if (type.value) {
  5252. switch (type.value.content) {
  5253. case 'radio':
  5254. directiveToUse = V_MODEL_RADIO;
  5255. break;
  5256. case 'checkbox':
  5257. directiveToUse = V_MODEL_CHECKBOX;
  5258. break;
  5259. case 'file':
  5260. isInvalidType = true;
  5261. context.onError(createDOMCompilerError(57 /* DOMErrorCodes.X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
  5262. break;
  5263. default:
  5264. // text type
  5265. checkDuplicatedValue();
  5266. break;
  5267. }
  5268. }
  5269. }
  5270. else if (hasDynamicKeyVBind(node)) {
  5271. // element has bindings with dynamic keys, which can possibly contain
  5272. // "type".
  5273. directiveToUse = V_MODEL_DYNAMIC;
  5274. }
  5275. else {
  5276. // text type
  5277. checkDuplicatedValue();
  5278. }
  5279. }
  5280. else if (tag === 'select') {
  5281. directiveToUse = V_MODEL_SELECT;
  5282. }
  5283. else {
  5284. // textarea
  5285. checkDuplicatedValue();
  5286. }
  5287. // inject runtime directive
  5288. // by returning the helper symbol via needRuntime
  5289. // the import will replaced a resolveDirective call.
  5290. if (!isInvalidType) {
  5291. baseResult.needRuntime = context.helper(directiveToUse);
  5292. }
  5293. }
  5294. else {
  5295. context.onError(createDOMCompilerError(55 /* DOMErrorCodes.X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
  5296. }
  5297. // native vmodel doesn't need the `modelValue` props since they are also
  5298. // passed to the runtime as `binding.value`. removing it reduces code size.
  5299. baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  5300. p.key.content === 'modelValue'));
  5301. return baseResult;
  5302. };
  5303. const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
  5304. const isNonKeyModifier = /*#__PURE__*/ makeMap(
  5305. // event propagation management
  5306. `stop,prevent,self,` +
  5307. // system modifiers + exact
  5308. `ctrl,shift,alt,meta,exact,` +
  5309. // mouse
  5310. `middle`);
  5311. // left & right could be mouse or key modifiers based on event type
  5312. const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
  5313. const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
  5314. const resolveModifiers = (key, modifiers, context, loc) => {
  5315. const keyModifiers = [];
  5316. const nonKeyModifiers = [];
  5317. const eventOptionModifiers = [];
  5318. for (let i = 0; i < modifiers.length; i++) {
  5319. const modifier = modifiers[i];
  5320. if (modifier === 'native' &&
  5321. checkCompatEnabled("COMPILER_V_ON_NATIVE" /* CompilerDeprecationTypes.COMPILER_V_ON_NATIVE */, context, loc)) {
  5322. eventOptionModifiers.push(modifier);
  5323. }
  5324. else if (isEventOptionModifier(modifier)) {
  5325. // eventOptionModifiers: modifiers for addEventListener() options,
  5326. // e.g. .passive & .capture
  5327. eventOptionModifiers.push(modifier);
  5328. }
  5329. else {
  5330. // runtimeModifiers: modifiers that needs runtime guards
  5331. if (maybeKeyModifier(modifier)) {
  5332. if (isStaticExp(key)) {
  5333. if (isKeyboardEvent(key.content)) {
  5334. keyModifiers.push(modifier);
  5335. }
  5336. else {
  5337. nonKeyModifiers.push(modifier);
  5338. }
  5339. }
  5340. else {
  5341. keyModifiers.push(modifier);
  5342. nonKeyModifiers.push(modifier);
  5343. }
  5344. }
  5345. else {
  5346. if (isNonKeyModifier(modifier)) {
  5347. nonKeyModifiers.push(modifier);
  5348. }
  5349. else {
  5350. keyModifiers.push(modifier);
  5351. }
  5352. }
  5353. }
  5354. }
  5355. return {
  5356. keyModifiers,
  5357. nonKeyModifiers,
  5358. eventOptionModifiers
  5359. };
  5360. };
  5361. const transformClick = (key, event) => {
  5362. const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
  5363. return isStaticClick
  5364. ? createSimpleExpression(event, true)
  5365. : key.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */
  5366. ? createCompoundExpression([
  5367. `(`,
  5368. key,
  5369. `) === "onClick" ? "${event}" : (`,
  5370. key,
  5371. `)`
  5372. ])
  5373. : key;
  5374. };
  5375. const transformOn$1 = (dir, node, context) => {
  5376. return transformOn(dir, node, context, baseResult => {
  5377. const { modifiers } = dir;
  5378. if (!modifiers.length)
  5379. return baseResult;
  5380. let { key, value: handlerExp } = baseResult.props[0];
  5381. const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
  5382. // normalize click.right and click.middle since they don't actually fire
  5383. if (nonKeyModifiers.includes('right')) {
  5384. key = transformClick(key, `onContextmenu`);
  5385. }
  5386. if (nonKeyModifiers.includes('middle')) {
  5387. key = transformClick(key, `onMouseup`);
  5388. }
  5389. if (nonKeyModifiers.length) {
  5390. handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
  5391. handlerExp,
  5392. JSON.stringify(nonKeyModifiers)
  5393. ]);
  5394. }
  5395. if (keyModifiers.length &&
  5396. // if event name is dynamic, always wrap with keys guard
  5397. (!isStaticExp(key) || isKeyboardEvent(key.content))) {
  5398. handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
  5399. handlerExp,
  5400. JSON.stringify(keyModifiers)
  5401. ]);
  5402. }
  5403. if (eventOptionModifiers.length) {
  5404. const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
  5405. key = isStaticExp(key)
  5406. ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
  5407. : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
  5408. }
  5409. return {
  5410. props: [createObjectProperty(key, handlerExp)]
  5411. };
  5412. });
  5413. };
  5414. const transformShow = (dir, node, context) => {
  5415. const { exp, loc } = dir;
  5416. if (!exp) {
  5417. context.onError(createDOMCompilerError(59 /* DOMErrorCodes.X_V_SHOW_NO_EXPRESSION */, loc));
  5418. }
  5419. return {
  5420. props: [],
  5421. needRuntime: context.helper(V_SHOW)
  5422. };
  5423. };
  5424. const transformTransition = (node, context) => {
  5425. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  5426. node.tagType === 1 /* ElementTypes.COMPONENT */) {
  5427. const component = context.isBuiltInComponent(node.tag);
  5428. if (component === TRANSITION) {
  5429. return () => {
  5430. if (!node.children.length) {
  5431. return;
  5432. }
  5433. // warn multiple transition children
  5434. if (hasMultipleChildren(node)) {
  5435. context.onError(createDOMCompilerError(60 /* DOMErrorCodes.X_TRANSITION_INVALID_CHILDREN */, {
  5436. start: node.children[0].loc.start,
  5437. end: node.children[node.children.length - 1].loc.end,
  5438. source: ''
  5439. }));
  5440. }
  5441. // check if it's s single child w/ v-show
  5442. // if yes, inject "persisted: true" to the transition props
  5443. const child = node.children[0];
  5444. if (child.type === 1 /* NodeTypes.ELEMENT */) {
  5445. for (const p of child.props) {
  5446. if (p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'show') {
  5447. node.props.push({
  5448. type: 6 /* NodeTypes.ATTRIBUTE */,
  5449. name: 'persisted',
  5450. value: undefined,
  5451. loc: node.loc
  5452. });
  5453. }
  5454. }
  5455. }
  5456. };
  5457. }
  5458. }
  5459. };
  5460. function hasMultipleChildren(node) {
  5461. // #1352 filter out potential comment nodes.
  5462. const children = (node.children = node.children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */ &&
  5463. !(c.type === 2 /* NodeTypes.TEXT */ && !c.content.trim())));
  5464. const child = children[0];
  5465. return (children.length !== 1 ||
  5466. child.type === 11 /* NodeTypes.FOR */ ||
  5467. (child.type === 9 /* NodeTypes.IF */ && child.branches.some(hasMultipleChildren)));
  5468. }
  5469. const ignoreSideEffectTags = (node, context) => {
  5470. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  5471. node.tagType === 0 /* ElementTypes.ELEMENT */ &&
  5472. (node.tag === 'script' || node.tag === 'style')) {
  5473. context.onError(createDOMCompilerError(61 /* DOMErrorCodes.X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
  5474. context.removeNode();
  5475. }
  5476. };
  5477. const DOMNodeTransforms = [
  5478. transformStyle,
  5479. ...([transformTransition] )
  5480. ];
  5481. const DOMDirectiveTransforms = {
  5482. cloak: noopDirectiveTransform,
  5483. html: transformVHtml,
  5484. text: transformVText,
  5485. model: transformModel$1,
  5486. on: transformOn$1,
  5487. show: transformShow
  5488. };
  5489. function compile(template, options = {}) {
  5490. return baseCompile(template, extend({}, parserOptions, options, {
  5491. nodeTransforms: [
  5492. // ignore <script> and <tag>
  5493. // this is not put inside DOMNodeTransforms because that list is used
  5494. // by compiler-ssr to generate vnode fallback branches
  5495. ignoreSideEffectTags,
  5496. ...DOMNodeTransforms,
  5497. ...(options.nodeTransforms || [])
  5498. ],
  5499. directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
  5500. transformHoist: null
  5501. }));
  5502. }
  5503. function parse(template, options = {}) {
  5504. return baseParse(template, extend({}, parserOptions, options));
  5505. }
  5506. export { BASE_TRANSITION, CAMELIZE, CAPITALIZE, CREATE_BLOCK, CREATE_COMMENT, CREATE_ELEMENT_BLOCK, CREATE_ELEMENT_VNODE, CREATE_SLOTS, CREATE_STATIC, CREATE_TEXT, CREATE_VNODE, DOMDirectiveTransforms, DOMNodeTransforms, FRAGMENT, GUARD_REACTIVE_PROPS, IS_MEMO_SAME, IS_REF, KEEP_ALIVE, MERGE_PROPS, NORMALIZE_CLASS, NORMALIZE_PROPS, NORMALIZE_STYLE, OPEN_BLOCK, POP_SCOPE_ID, PUSH_SCOPE_ID, RENDER_LIST, RENDER_SLOT, RESOLVE_COMPONENT, RESOLVE_DIRECTIVE, RESOLVE_DYNAMIC_COMPONENT, RESOLVE_FILTER, SET_BLOCK_TRACKING, SUSPENSE, TELEPORT, TO_DISPLAY_STRING, TO_HANDLERS, TO_HANDLER_KEY, TRANSITION, TRANSITION_GROUP, UNREF, V_MODEL_CHECKBOX, V_MODEL_DYNAMIC, V_MODEL_RADIO, V_MODEL_SELECT, V_MODEL_TEXT, V_ON_WITH_KEYS, V_ON_WITH_MODIFIERS, V_SHOW, WITH_CTX, WITH_DIRECTIVES, WITH_MEMO, advancePositionWithClone, advancePositionWithMutation, assert, baseCompile, baseParse, buildDirectiveArgs, buildProps, buildSlots, checkCompatEnabled, compile, createArrayExpression, createAssignmentExpression, createBlockStatement, createCacheExpression, createCallExpression, createCompilerError, createCompoundExpression, createConditionalExpression, createDOMCompilerError, createForLoopParams, createFunctionExpression, createIfStatement, createInterpolation, createObjectExpression, createObjectProperty, createReturnStatement, createRoot, createSequenceExpression, createSimpleExpression, createStructuralDirectiveTransform, createTemplateLiteral, createTransformContext, createVNodeCall, extractIdentifiers, findDir, findProp, generate, generateCodeFrame, getBaseTransformPreset, getConstantType, getInnerRange, getMemoedVNodeCall, getVNodeBlockHelper, getVNodeHelper, hasDynamicKeyVBind, hasScopeRef, helperNameMap, injectProp, isBuiltInType, isCoreComponent, isFunctionType, isInDestructureAssignment, isMemberExpression, isMemberExpressionBrowser, isMemberExpressionNode, isReferencedIdentifier, isSimpleIdentifier, isSlotOutlet, isStaticArgOf, isStaticExp, isStaticProperty, isStaticPropertyKey, isTemplateNode, isText, isVSlot, locStub, makeBlock, noopDirectiveTransform, parse, parserOptions, processExpression, processFor, processIf, processSlotOutlet, registerRuntimeHelpers, resolveComponentType, stringifyExpression, toValidAssetId, trackSlotScopes, trackVForSlotScopes, transform, transformBind, transformElement, transformExpression, transformModel, transformOn, transformStyle, traverseNode, walkBlockDeclarations, walkFunctionParams, walkIdentifiers, warnDeprecation };